1mod repr;
2mod spec2;
3mod spec3;
4
5use self::repr::filter_empty_types;
6use self::{
7 spec2::{use_spec2, Spec2},
8 spec3::{use_spec3, Spec3},
9};
10use repr::filter_unwanted_types;
11use serde::{Deserialize, Serialize};
12use std::{fs::File, io::Read, path::Path};
13
14#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
15#[serde(untagged)]
16pub enum OpenApi {
17 V2(Spec2),
18 V3(Spec3),
19}
20
21pub fn from_path<P>(path: P) -> OpenApi
22where
23 P: AsRef<Path>,
24{
25 from_reader(File::open(path).unwrap())
26}
27
28pub fn from_reader<R>(read: R) -> OpenApi
29where
30 R: Read,
31{
32 serde_yaml::from_reader::<R, OpenApi>(read).unwrap()
33}
34
35pub fn from_bytes(read: &[u8]) -> OpenApi {
36 serde_yaml::from_slice::<OpenApi>(read).unwrap()
37}
38
39pub fn use_spec(spec: &OpenApi, skip_empty: bool, skip_types: Vec<&str>) -> String {
40 let types = match spec {
41 OpenApi::V2(spec) => use_spec2(spec),
42 OpenApi::V3(spec) => use_spec3(spec),
43 };
44 format!(
45 "// This file was generated using https://crates.io/crates/lupinas-lullaby\n{}",
46 types
47 .into_iter()
48 .filter_map(|(name, tt)| {
49 if skip_empty {
50 filter_empty_types(&tt).map(|tt| (name, tt))
51 } else {
52 Some((name, tt))
53 }
54 })
55 .filter_map(|(name, tt)| filter_unwanted_types(&tt, &skip_types).map(|tt| (name, tt)))
56 .map(|(name, ttype)| format!("export type {} = {};", name, ttype))
57 .collect::<Vec<String>>()
58 .join("\n")
59 )
60}
61
62#[test]
63pub fn test_v2_json_examples() {
64 let _result = std::fs::read_dir("./data/v2.0/json")
65 .unwrap()
66 .map(|res| res.unwrap().path())
67 .filter(|path| path.is_file())
68 .map(|x| from_path(x))
69 .map(|spec| use_spec(&spec, false, vec![]))
70 .collect::<Vec<_>>();
71}
72
73#[test]
74pub fn test_v2_yaml_examples() {
75 let _result = std::fs::read_dir("./data/v2.0/yaml")
76 .unwrap()
77 .map(|res| res.unwrap().path())
78 .filter(|path| path.is_file())
79 .map(|x| from_path(x))
80 .map(|spec| use_spec(&spec, false, vec![]))
81 .collect::<Vec<_>>();
82}
83
84#[test]
85pub fn test_v3_examples() {
86 let _result = std::fs::read_dir("./data/v3.0")
87 .unwrap()
88 .map(|res| res.unwrap().path())
89 .filter(|path| path.is_file())
90 .map(|x| from_path(x))
91 .map(|spec| use_spec(&spec, false, vec![]))
92 .collect::<Vec<_>>();
93}