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
use okapi::openapi3::{Components, OpenApi, SchemaObject};
use okapi::schemars::schema::{InstanceType, Schema, SingleOrVec};

/// Parse OpenAPI 3 schema
pub fn parse_schema(file_content: &str) -> OpenApi {
    let schema = serde_yaml::from_str::<OpenApi>(file_content).expect("Failed to parse document");

    if schema.components.is_none() {
        log::error!("components is missing!");
        panic!()
    }

    schema
}

fn expect_single<E>(e: &SingleOrVec<E>) -> &E {
    match e {
        SingleOrVec::Single(e) => e,
        SingleOrVec::Vec(v) => &v[0],
    }
}

fn expect_schema_object(s: &Schema) -> &SchemaObject {
    match s {
        Schema::Bool(_) => {
            panic!("Got unexpected bool!");
        }
        Schema::Object(o) => o,
    }
}

#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type")]
pub enum NodeType {
    Null,
    Boolean,
    Array { item: Box<TreeNode> },
    Object { children: Vec<TreeNode> },
    String,
    Number,
    Integer,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct TreeNode {
    pub name: String,
    #[serde(flatten)]
    pub r#type: NodeType,
}

impl TreeNode {
    /// Merge two TreeNode
    pub fn merge_with(&self, other: &Self) -> Self {
        if !matches!(self.r#type, NodeType::String | NodeType::Object { .. }) {
            panic!("Cannot merge!");
        }

        if !matches!(other.r#type, NodeType::String | NodeType::Object { .. }) {
            panic!("Cannot merge other!");
        }

        let r#type = match (&self.r#type, &other.r#type) {
            (NodeType::String, NodeType::String) => NodeType::String,
            (NodeType::String, NodeType::Object { children })
            | (NodeType::Object { children }, NodeType::String) => NodeType::Object {
                children: children.clone(),
            },

            (NodeType::Object { children: c1 }, NodeType::Object { children: c2 }) => {
                let mut children = c1.clone();
                children.append(&mut c2.clone());
                NodeType::Object { children }
            }

            (_, _) => unreachable!(),
        };

        TreeNode {
            name: self.name.to_string(),
            r#type,
        }
    }
}

/// Construct the tree of a given structure name
pub fn build_tree(struct_name: &str, components: &Components) -> TreeNode {
    let schema = components
        .schemas
        .get(struct_name)
        .unwrap_or_else(|| panic!("Missing {struct_name}"));

    build_tree_schema(schema, struct_name, components)
}

/// Build a structure tree using a schema
fn build_tree_schema(
    schema: &SchemaObject,
    struct_name: &str,
    components: &Components,
) -> TreeNode {
    if let Some(name) = &schema.reference {
        return build_tree(
            name.strip_prefix("#/components/schemas/").unwrap(),
            components,
        );
    }

    if let Some(subschemas) = &schema.subschemas {
        if let Some(all_of) = &subschemas.all_of {
            assert!(!all_of.is_empty());
            let mut tree =
                build_tree_schema(expect_schema_object(&all_of[0]), struct_name, components);

            for other in all_of.iter().skip(1) {
                let other = build_tree_schema(expect_schema_object(other), struct_name, components);
                tree = tree.merge_with(&other);
            }

            return tree;
        } else {
            panic!("Unsupported case!");
        }
    }

    let schema_type = schema
        .instance_type
        .as_ref()
        .map(expect_single)
        .unwrap_or(&InstanceType::String);

    let r#type = match schema_type {
        InstanceType::Null => NodeType::Null,
        InstanceType::Boolean => NodeType::Boolean,
        InstanceType::Object => {
            let children = schema
                .object
                .as_ref()
                .map(|s| s.properties.clone())
                .unwrap_or_default()
                .iter()
                .map(|e| {
                    let o = expect_schema_object(e.1);
                    build_tree_schema(o, e.0, components)
                })
                .collect::<Vec<_>>();
            NodeType::Object { children }
        }
        InstanceType::Array => {
            let item = expect_schema_object(expect_single(
                schema.array.as_ref().unwrap().items.as_ref().unwrap(),
            ));
            NodeType::Array {
                item: Box::new(build_tree_schema(
                    item,
                    &format!("{struct_name}[]"),
                    components,
                )),
            }
        }
        InstanceType::Number => NodeType::Number,
        InstanceType::String => NodeType::String,
        InstanceType::Integer => NodeType::Integer,
    };

    TreeNode {
        name: struct_name.to_string(),
        r#type,
    }
}