migrate to typify and use quote (#4)

This commit is contained in:
Adam Leventhal 2021-10-02 11:40:03 -07:00 committed by GitHub
parent eec74acf18
commit 865dbd4be4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 1291 additions and 1089 deletions

439
Cargo.lock generated
View File

@ -3,10 +3,19 @@
version = 3 version = 3
[[package]] [[package]]
name = "anyhow" name = "aho-corasick"
version = "1.0.41" version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15af2628f6890fe2609a3b91bef4c83450512802e59489f9c1cb1fa5df064a61" checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f"
dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61604a8f862e1d5c3229fdd78f8b02c68dcf73a4c4b05fd636d12240aaa242c1"
[[package]] [[package]]
name = "autocfg" name = "autocfg"
@ -14,12 +23,36 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "convert_case"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]] [[package]]
name = "dtoa" name = "dtoa"
version = "0.4.8" version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0" checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0"
[[package]]
name = "dyn-clone"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee2626afccd7561a06cf1367e2950c4718ea04565e20fb5029b6c7d8ad09abcf"
[[package]] [[package]]
name = "getopts" name = "getopts"
version = "0.2.21" version = "0.2.21"
@ -30,16 +63,36 @@ dependencies = [
] ]
[[package]] [[package]]
name = "hashbrown" name = "getrandom"
version = "0.9.1" version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "hashbrown"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]]
name = "home"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2456aef2e6b6a9784192ae780c0f15bc57df0e918585282325e8c8ac27737654"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.6.2" version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3" checksum = "bc633605454125dec4b66843673f01c7df2b89479b32e0ed634e43a91cff62a5"
dependencies = [ dependencies = [
"autocfg", "autocfg",
"hashbrown", "hashbrown",
@ -48,9 +101,21 @@ dependencies = [
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "0.4.7" version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8f7255a17a627354f321ef0055d63b898c6fb27eff628af4d1b66b7331edf6"
[[package]] [[package]]
name = "linked-hash-map" name = "linked-hash-map"
@ -59,10 +124,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]] [[package]]
name = "openapiv3" name = "memchr"
version = "1.0.0-beta.1" version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abe6e1dfe8bc4931d6e90adbe2cec19e3fd67f7453d64e9a17cbf8dc16a67ec9" checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a"
[[package]]
name = "openapiv3"
version = "1.0.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791f5f66415ca5d11fb29e8dcf0b923adff5b2c9bd1cf54621777494c8f8f688"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"serde", "serde",
@ -71,10 +142,25 @@ dependencies = [
] ]
[[package]] [[package]]
name = "proc-macro2" name = "pest"
version = "1.0.27" version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0d8caf72986c1a598726adc988bb5984792ef84f5ee5aa50209145ee8077038" checksum = "10f4872ae94d7b90ae48754df22fd42ad52ce740b8f370b03da4835417403e53"
dependencies = [
"ucd-trie",
]
[[package]]
name = "ppv-lite86"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857"
[[package]]
name = "proc-macro2"
version = "1.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f5105d4fdaab20335ca9565e106a5d9b82b6219b5ba735731124ac6711d23d"
dependencies = [ dependencies = [
"unicode-xid", "unicode-xid",
] ]
@ -85,9 +171,15 @@ version = "0.0.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"getopts", "getopts",
"indexmap",
"openapiv3", "openapiv3",
"proc-macro2",
"quote",
"rustfmt-wrapper",
"schemars",
"serde", "serde",
"serde_json", "serde_json",
"typify",
] ]
[[package]] [[package]]
@ -99,6 +191,91 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "rand"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"rand_hc",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
dependencies = [
"getrandom",
]
[[package]]
name = "rand_hc"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d51e9f596de227fda2ea6c84607f5558e196eeaf43c986b724ba4fb8fdf497e7"
dependencies = [
"rand_core",
]
[[package]]
name = "redox_syscall"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff"
dependencies = [
"bitflags",
]
[[package]]
name = "regex"
version = "1.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.6.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
[[package]]
name = "remove_dir_all"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
dependencies = [
"winapi",
]
[[package]]
name = "rustfmt-wrapper"
version = "0.1.0"
source = "git+https://github.com/oxidecomputer/typify#825df8c1192f91f9edd27de0b81a858514d1865a"
dependencies = [
"tempfile",
"thiserror",
"toolchain_find",
]
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.5" version = "1.0.5"
@ -106,19 +283,81 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]] [[package]]
name = "serde" name = "same-file"
version = "1.0.126" version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7505abeacaec74ae4778d9d9328fe5a5d04253220a85c4ee022239fc996d03" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "schemars"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7a48d098c2a7fdf5740b19deb1181b4fb8a9e68e03ae517c14cde04b5725409"
dependencies = [
"dyn-clone",
"schemars_derive",
"serde",
"serde_json",
]
[[package]]
name = "schemars_derive"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a9ea2a613fe4cd7118b2bb101a25d8ae6192e1975179b67b2f17afd11e70ac8"
dependencies = [
"proc-macro2",
"quote",
"serde_derive_internals",
"syn",
]
[[package]]
name = "semver"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6"
dependencies = [
"semver-parser",
]
[[package]]
name = "semver-parser"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7"
dependencies = [
"pest",
]
[[package]]
name = "serde"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.126" version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "963a7dbc9895aeac7ac90e74f34a5d5261828f79df35cbed41e10189d3804d43" checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_derive_internals"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dbab34ca63057a1f15280bdf3c39f2b1eb1b54c17e98360e511637aef7418c6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -127,9 +366,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.64" version = "1.0.68"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8"
dependencies = [ dependencies = [
"itoa", "itoa",
"ryu", "ryu",
@ -138,21 +377,21 @@ dependencies = [
[[package]] [[package]]
name = "serde_yaml" name = "serde_yaml"
version = "0.8.17" version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15654ed4ab61726bf918a39cb8d98a2e2995b002387807fa6ba58fdf7f59bb23" checksum = "d8c608a35705a5d3cdc9fbe403147647ff34b921f8e833e49306df898f9b20af"
dependencies = [ dependencies = [
"dtoa", "dtoa",
"linked-hash-map", "indexmap",
"serde", "serde",
"yaml-rust", "yaml-rust",
] ]
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.73" version = "1.0.77"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f71489ff30030d2ae598524f61326b902466f72a0fb1a8564c001cc63425bcc7" checksum = "5239bc68e0fef57495900cfea4e8dc75596d9a319d7e16b1e0a440d24e6fe0a0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -160,10 +399,100 @@ dependencies = [
] ]
[[package]] [[package]]
name = "unicode-width" name = "tempfile"
version = "0.1.8" version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" checksum = "dac1c663cfc93810f88aed9b8941d48cabf856a1b111c29a40439018d870eb22"
dependencies = [
"cfg-if",
"libc",
"rand",
"redox_syscall",
"remove_dir_all",
"winapi",
]
[[package]]
name = "thiserror"
version = "1.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "602eca064b2d83369e2b2f34b09c70b605402801927c65c11071ac911d299b88"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad553cc2c78e8de258400763a647e80e6d1b31ee237275d756f6836d204494c"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "toolchain_find"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e85654a10e7a07a47c6f19d93818f3f343e22927f2fa280c84f7c8042743413"
dependencies = [
"home",
"lazy_static",
"regex",
"semver",
"walkdir",
]
[[package]]
name = "typify"
version = "0.0.1"
source = "git+https://github.com/oxidecomputer/typify#825df8c1192f91f9edd27de0b81a858514d1865a"
dependencies = [
"rustfmt-wrapper",
"typify-impl",
"typify-macro",
]
[[package]]
name = "typify-impl"
version = "0.0.1"
source = "git+https://github.com/oxidecomputer/typify#825df8c1192f91f9edd27de0b81a858514d1865a"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"schemars",
"serde_json",
"syn",
"thiserror",
]
[[package]]
name = "typify-macro"
version = "0.0.1"
source = "git+https://github.com/oxidecomputer/typify#825df8c1192f91f9edd27de0b81a858514d1865a"
dependencies = [
"proc-macro2",
"quote",
"schemars",
"serde_json",
"syn",
"typify-impl",
]
[[package]]
name = "ucd-trie"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c"
[[package]]
name = "unicode-width"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
@ -171,6 +500,54 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
name = "walkdir"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56"
dependencies = [
"same-file",
"winapi",
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.10.2+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]] [[package]]
name = "yaml-rust" name = "yaml-rust"
version = "0.4.5" version = "0.4.5"

View File

@ -9,6 +9,12 @@ description = "An OpenAPI client generator"
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"
getopts = "0.2" getopts = "0.2"
indexmap = "1.7.0"
openapiv3 = "1.0.0-beta.2"
proc-macro2 = "1.0.29"
quote = "1.0.9"
rustfmt-wrapper = { git = "https://github.com/oxidecomputer/typify" }
schemars = "0.8.5"
serde = { version = "1", features = [ "derive" ] } serde = { version = "1", features = [ "derive" ] }
serde_json = "1" serde_json = "1.0.68"
openapiv3 = "1.0.0-beta.1" typify = { git = "https://github.com/oxidecomputer/typify" }

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,6 @@
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
#[derive(Eq, PartialEq, Clone, Debug)] #[derive(Eq, PartialEq, Clone, Debug)]
enum Component { enum Component {
@ -12,28 +14,31 @@ pub struct Template {
} }
impl Template { impl Template {
pub fn compile(&self) -> String { pub fn compile(&self) -> TokenStream {
let mut out = " let url = format!(\"{}".to_string(); let mut fmt = String::new();
fmt.push_str("{}");
for c in self.components.iter() { for c in self.components.iter() {
out.push('/'); fmt.push('/');
match c { match c {
Component::Constant(n) => out.push_str(n), Component::Constant(n) => fmt.push_str(n),
Component::Parameter(_) => out.push_str("{}"), Component::Parameter(_) => fmt.push_str("{}"),
} }
} }
out.push_str("\",\n");
out.push_str(" self.baseurl,\n"); let components = self.components.iter().filter_map(|component| {
for c in self.components.iter() { if let Component::Parameter(n) = &component {
if let Component::Parameter(n) = &c { let param = format_ident!("{}", n);
out.push_str(&format!( Some(quote! {
" \ progenitor_support::encode_path(&#param.to_string())
progenitor_support::encode_path(&{}.to_string()),\n", })
n } else {
)); None
} }
});
quote! {
let url = format!(#fmt, self.baseurl, #(#components,)*);
} }
out.push_str(" );\n");
out
} }
pub fn names(&self) -> Vec<String> { pub fn names(&self) -> Vec<String> {
@ -192,11 +197,13 @@ mod test {
fn compile() -> Result<()> { fn compile() -> Result<()> {
let t = parse("/measure/{number}")?; let t = parse("/measure/{number}")?;
let out = t.compile(); let out = t.compile();
let want = " let url = format!(\"{}/measure/{}\",\ let want = quote::quote! {
\n self.baseurl,\ let url = format!("{}/measure/{}",
\n progenitor_support::encode_path(&number.to_string()),\ self.baseurl,
\n );\n"; progenitor_support::encode_path(&number.to_string()),
assert_eq!(want, &out); );
};
assert_eq!(want.to_string(), out.to_string());
Ok(()) Ok(())
} }
} }

523
src/to_schema.rs Normal file
View File

@ -0,0 +1,523 @@
use indexmap::IndexMap;
use openapiv3::AnySchema;
use serde_json::Value;
pub trait ToSchema {
fn to_schema(&self) -> schemars::schema::Schema;
}
trait Convert<T> {
fn convert(&self) -> T;
}
impl ToSchema for openapiv3::Schema {
fn to_schema(&self) -> schemars::schema::Schema {
self.convert()
}
}
impl ToSchema for openapiv3::ReferenceOr<openapiv3::Schema> {
fn to_schema(&self) -> schemars::schema::Schema {
self.convert()
}
}
impl<I, T> Convert<Vec<T>> for Vec<I>
where
I: Convert<T>,
{
fn convert(&self) -> Vec<T> {
self.iter().map(Convert::convert).collect()
}
}
impl<I, T> Convert<Option<Vec<T>>> for Vec<I>
where
I: Convert<T>,
{
fn convert(&self) -> Option<Vec<T>> {
if self.is_empty() {
None
} else {
Some(self.iter().map(Convert::convert).collect())
}
}
}
impl Convert<schemars::schema::Schema>
for openapiv3::ReferenceOr<openapiv3::Schema>
{
fn convert(&self) -> schemars::schema::Schema {
match self {
openapiv3::ReferenceOr::Reference { reference } => {
schemars::schema::SchemaObject::new_ref(reference.clone())
.into()
}
openapiv3::ReferenceOr::Item(schema) => schema.convert(),
}
}
}
impl<T, TT> Convert<TT> for openapiv3::ReferenceOr<Box<T>>
where
openapiv3::ReferenceOr<T>: Convert<TT>,
T: Clone,
{
fn convert(&self) -> TT {
self.clone().unbox().convert()
}
}
impl Convert<schemars::schema::Schema> for openapiv3::Schema {
fn convert(&self) -> schemars::schema::Schema {
// TODO the discriminator field is used in a way that seems both
// important and unfortunately redundant. It corresponds to the same
// regime as internally tagged enums in the serde sense: a field that
// the discriminator defines is used to determine which schema is
// valid. This can base used in two ways:
// 1. It can be used within a struct to identify a particular, required
// field. This is typically done on a "base" class in an OOP hierarchy.
// Child class structs "extend" that base class by using an allOf
// construction where the parent is one of the subschemas. To recognize
// this case, we need to check all subschemas in an allOf to see if any
// of them have a discriminator. If they do, we can simply construct an
// additional structure for the allOf that has a fixed value for that
// field.
// 2. It can be used within a oneOf or anyOf schema to determine which
// subschema is relevant. This is easier to detect because it doesn't
// required chasing references. For each subschema we can then make it
// an allOf union of the actual subschema along with a fixed-field
// structure.
let openapiv3::SchemaData {
nullable,
discriminator: _, // TODO: see above
external_docs: _, // TODO: append to description?
title,
description,
default,
deprecated,
read_only,
write_only,
example,
} = self.schema_data.clone();
let metadata = schemars::schema::Metadata {
id: None,
title,
description,
default,
deprecated,
read_only,
write_only,
examples: example.into_iter().collect::<Vec<_>>(),
};
let metadata = Some(Box::new(metadata)).reduce();
match &self.schema_kind {
openapiv3::SchemaKind::Type(openapiv3::Type::String(
openapiv3::StringType {
format,
pattern,
enumeration,
min_length,
max_length,
},
)) => schemars::schema::SchemaObject {
metadata,
instance_type: instance_type(
schemars::schema::InstanceType::String,
nullable,
),
format: format.convert(),
enum_values: enumeration.convert(),
string: Some(Box::new(schemars::schema::StringValidation {
max_length: max_length.convert(),
min_length: min_length.convert(),
pattern: pattern.clone(),
}))
.reduce(),
..Default::default()
},
openapiv3::SchemaKind::Type(openapiv3::Type::Number(
openapiv3::NumberType {
format,
multiple_of,
exclusive_minimum,
exclusive_maximum,
minimum,
maximum,
enumeration,
},
)) => {
let (maximum, exclusive_maximum) =
match (maximum, exclusive_maximum) {
(None, _) => (None, None),
(Some(v), false) => (Some(*v), None),
(Some(v), true) => (None, Some(*v)),
};
let (minimum, exclusive_minimum) =
match (minimum, exclusive_minimum) {
(None, _) => (None, None),
(Some(v), false) => (Some(*v), None),
(Some(v), true) => (None, Some(*v)),
};
schemars::schema::SchemaObject {
metadata,
instance_type: instance_type(
schemars::schema::InstanceType::Number,
nullable,
),
format: format.convert(),
enum_values: enumeration.convert(),
number: Some(Box::new(
schemars::schema::NumberValidation {
multiple_of: multiple_of.convert(),
maximum,
exclusive_maximum,
minimum,
exclusive_minimum,
},
))
.reduce(),
..Default::default()
}
}
openapiv3::SchemaKind::Type(openapiv3::Type::Integer(
openapiv3::IntegerType {
format,
multiple_of,
exclusive_minimum,
exclusive_maximum,
minimum,
maximum,
enumeration,
},
)) => {
let (maximum, exclusive_maximum) =
match (maximum, exclusive_maximum) {
(None, _) => (None, None),
(Some(v), false) => (Some(*v as f64), None),
(Some(v), true) => (None, Some(*v as f64)),
};
let (minimum, exclusive_minimum) =
match (minimum, exclusive_minimum) {
(None, _) => (None, None),
(Some(v), false) => (Some(*v as f64), None),
(Some(v), true) => (None, Some(*v as f64)),
};
schemars::schema::SchemaObject {
metadata,
instance_type: instance_type(
schemars::schema::InstanceType::Integer,
nullable,
),
format: format.convert(),
enum_values: enumeration.convert(),
number: Some(Box::new(
schemars::schema::NumberValidation {
multiple_of: multiple_of
.map(|v| v as f64)
.convert(),
maximum,
exclusive_maximum,
minimum,
exclusive_minimum,
},
))
.reduce(),
..Default::default()
}
}
openapiv3::SchemaKind::Type(openapiv3::Type::Object(
openapiv3::ObjectType {
properties,
required,
additional_properties,
min_properties,
max_properties,
},
)) => schemars::schema::SchemaObject {
metadata,
instance_type: instance_type(
schemars::schema::InstanceType::Object,
nullable,
),
object: Some(Box::new(schemars::schema::ObjectValidation {
max_properties: max_properties.convert(),
min_properties: min_properties.convert(),
required: required.convert(),
properties: properties.convert(),
pattern_properties: schemars::Map::default(),
additional_properties: additional_properties.convert(),
property_names: None,
}))
.reduce(),
..Default::default()
},
openapiv3::SchemaKind::Type(openapiv3::Type::Array(
openapiv3::ArrayType {
items,
min_items,
max_items,
unique_items,
},
)) => schemars::schema::SchemaObject {
metadata,
instance_type: instance_type(
schemars::schema::InstanceType::Array,
nullable,
),
array: Some(Box::new(schemars::schema::ArrayValidation {
items: items.as_ref().map(|items| {
schemars::schema::SingleOrVec::Single(Box::new(
items.convert(),
))
}),
additional_items: None,
max_items: max_items.convert(),
min_items: min_items.convert(),
unique_items: if *unique_items { Some(true) } else { None },
contains: None,
}))
.reduce(),
..Default::default()
},
openapiv3::SchemaKind::Type(openapiv3::Type::Boolean {}) => {
schemars::schema::SchemaObject {
metadata,
instance_type: instance_type(
schemars::schema::InstanceType::Boolean,
nullable,
),
..Default::default()
}
}
openapiv3::SchemaKind::OneOf { one_of } => {
schemars::schema::SchemaObject {
subschemas: Some(Box::new(
schemars::schema::SubschemaValidation {
one_of: Some(one_of.convert()),
..Default::default()
},
)),
..Default::default()
}
}
openapiv3::SchemaKind::AllOf { all_of } => {
schemars::schema::SchemaObject {
subschemas: Some(Box::new(
schemars::schema::SubschemaValidation {
all_of: Some(all_of.convert()),
..Default::default()
},
)),
..Default::default()
}
}
openapiv3::SchemaKind::AnyOf { any_of } => {
schemars::schema::SchemaObject {
subschemas: Some(Box::new(
schemars::schema::SubschemaValidation {
any_of: Some(any_of.convert()),
..Default::default()
},
)),
..Default::default()
}
}
// This is the permissive schema that allows anything to match.
openapiv3::SchemaKind::Any(AnySchema {
pattern: None,
multiple_of: None,
exclusive_minimum: None,
exclusive_maximum: None,
minimum: None,
maximum: None,
properties,
required,
additional_properties: None,
min_properties: None,
max_properties: None,
items: None,
min_items: None,
max_items: None,
unique_items: None,
format: None,
}) if properties.is_empty() && required.is_empty() => {
schemars::schema::Schema::Bool(true).into_object()
}
openapiv3::SchemaKind::Any(_) => {
panic!("not clear what we could usefully do here {:#?}", self)
}
}
.into()
}
}
impl<T> Convert<Option<String>> for openapiv3::VariantOrUnknownOrEmpty<T>
where
T: Convert<String>,
{
fn convert(&self) -> Option<String> {
match self {
openapiv3::VariantOrUnknownOrEmpty::Item(i) => Some(i.convert()),
openapiv3::VariantOrUnknownOrEmpty::Unknown(s) => Some(s.clone()),
openapiv3::VariantOrUnknownOrEmpty::Empty => None,
}
}
}
impl Convert<String> for openapiv3::StringFormat {
fn convert(&self) -> String {
match self {
openapiv3::StringFormat::Date => "date",
openapiv3::StringFormat::DateTime => "date-time",
openapiv3::StringFormat::Password => "password",
openapiv3::StringFormat::Byte => "byte",
openapiv3::StringFormat::Binary => "binary",
}
.to_string()
}
}
impl Convert<String> for openapiv3::NumberFormat {
fn convert(&self) -> String {
match self {
openapiv3::NumberFormat::Float => "float",
openapiv3::NumberFormat::Double => "double",
}
.to_string()
}
}
impl Convert<String> for openapiv3::IntegerFormat {
fn convert(&self) -> String {
match self {
openapiv3::IntegerFormat::Int32 => "int32",
openapiv3::IntegerFormat::Int64 => "int64",
}
.to_string()
}
}
impl Convert<Value> for Option<String> {
fn convert(&self) -> Value {
match self {
Some(value) => Value::String(value.clone()),
None => Value::Null,
}
}
}
impl Convert<Value> for f64 {
fn convert(&self) -> Value {
Value::Number(serde_json::Number::from_f64(*self).unwrap())
}
}
impl Convert<Value> for i64 {
fn convert(&self) -> Value {
Value::Number(serde_json::Number::from(*self))
}
}
fn instance_type(
instance_type: schemars::schema::InstanceType,
nullable: bool,
) -> Option<schemars::schema::SingleOrVec<schemars::schema::InstanceType>> {
if nullable {
Some(schemars::schema::SingleOrVec::Vec(vec![
instance_type,
schemars::schema::InstanceType::Null,
]))
} else {
Some(schemars::schema::SingleOrVec::Single(Box::new(
instance_type,
)))
}
}
impl Convert<Option<u32>> for Option<usize> {
fn convert(&self) -> Option<u32> {
(*self).map(|m| m as u32)
}
}
impl Convert<Option<f64>> for Option<f64> {
fn convert(&self) -> Option<f64> {
*self
}
}
impl Convert<schemars::Set<String>> for Vec<String> {
fn convert(&self) -> schemars::Set<String> {
self.iter().cloned().collect()
}
}
impl Convert<schemars::Map<String, schemars::schema::Schema>>
for IndexMap<String, openapiv3::ReferenceOr<Box<openapiv3::Schema>>>
{
fn convert(&self) -> schemars::Map<String, schemars::schema::Schema> {
self.iter().map(|(k, v)| (k.clone(), v.convert())).collect()
}
}
impl<T, TT> Convert<TT> for Box<T>
where
T: Convert<TT>,
{
fn convert(&self) -> TT {
self.as_ref().convert()
}
}
impl<T, TT> Convert<Option<Box<TT>>> for Option<T>
where
T: Convert<TT>,
{
fn convert(&self) -> Option<Box<TT>> {
self.as_ref().map(|t| Box::new(t.convert()))
}
}
impl Convert<schemars::schema::Schema> for openapiv3::AdditionalProperties {
fn convert(&self) -> schemars::schema::Schema {
match self {
openapiv3::AdditionalProperties::Any(b) => {
schemars::schema::Schema::Bool(*b)
}
openapiv3::AdditionalProperties::Schema(schema) => schema.convert(),
}
}
}
trait OptionReduce {
fn reduce(self) -> Self;
}
// If an Option is `Some` of it's default value, we can simplify that to `None`
impl<T> OptionReduce for Option<T>
where
T: Default + PartialEq + std::fmt::Debug,
{
fn reduce(self) -> Self {
match &self {
Some(s) if s != &T::default() => self,
_ => None,
}
}
}