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
use crate::*;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpenAPI {
pub openapi: String,
pub info: Info,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub servers: Vec<Server>,
pub paths: Paths,
#[serde(skip_serializing_if = "Option::is_none")]
pub components: Option<Components>,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub security: Option<Vec<SecurityRequirement>>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<Tag>,
#[serde(rename = "externalDocs")]
#[serde(skip_serializing_if = "Option::is_none")]
pub external_docs: Option<ExternalDocumentation>,
#[serde(flatten, deserialize_with = "crate::util::deserialize_extensions")]
pub extensions: IndexMap<String, serde_json::Value>,
}
impl OpenAPI {
pub fn operations(&self) -> impl Iterator<Item=(&str, &str, &Operation, &PathItem)> {
self.paths
.iter()
.filter_map(|(path, item)| item.as_item().map(|i| (path, i)))
.flat_map(|(path, item)| {
item.iter()
.map(move |(method, op)| (path.as_str(), method, op, item))
})
}
pub fn operations_mut(&mut self) -> impl Iterator<Item=(&str, &str, &mut Operation)> {
self.paths
.iter_mut()
.filter_map(|(path, item)| item.as_mut().map(|i| (path, i)))
.flat_map(|(path, item)| {
item.iter_mut()
.map(move |(method, op)| (path.as_str(), method, op))
})
}
pub fn get_operation_mut(&mut self, operation_id: &str) -> Option<&mut Operation> {
self.operations_mut().find(|(_, _, op)| op.operation_id.as_ref().unwrap() == operation_id).map(|(_, _, op)| op)
}
pub fn get_operation(&self, operation_id: &str) -> Option<(&Operation, &PathItem)> {
self.operations()
.find(|(_, _, op, _)| op.operation_id.as_ref().unwrap() == operation_id)
.map(|(_, _, op, item)| (op, item))
}
pub fn schemas_mut(&mut self) -> &mut IndexMap<String, ReferenceOr<Schema>> {
&mut self.components
.as_mut()
.unwrap()
.schemas
}
pub fn schemas(&self) -> &IndexMap<String, ReferenceOr<Schema>> {
&self.components
.as_ref()
.unwrap()
.schemas
}
pub fn merge(mut self, other: OpenAPI) -> Result<Self, MergeError> {
merge_map(&mut self.info.extensions, other.info.extensions);
merge_vec(&mut self.servers, other.servers, |a, b| a.url == b.url);
for (path, item) in other.paths {
let item = item.into_item().ok_or_else(|| MergeError::new("PathItem references are not yet supported. Please opena n issue if you need this feature."))?;
if self.paths.paths.contains_key(&path) {
let self_item = self.paths.paths.get_mut(&path).unwrap().as_mut().ok_or_else(|| MergeError::new("PathItem references are not yet supported. Please open an issue if you need this feature."))?;
option_or(&mut self_item.get, item.get);
option_or(&mut self_item.put, item.put);
option_or(&mut self_item.post, item.post);
option_or(&mut self_item.delete, item.delete);
option_or(&mut self_item.options, item.options);
option_or(&mut self_item.head, item.head);
option_or(&mut self_item.patch, item.patch);
option_or(&mut self_item.trace, item.trace);
merge_vec(&mut self_item.servers, item.servers, |a, b| a.url == b.url);
merge_map(&mut self_item.extensions, item.extensions);
if self_item.parameters.len() != item.parameters.len() {
return Err(MergeError(format!("PathItem {} parameters do not have the same length", path)));
}
for (a, b) in self_item.parameters.iter_mut().zip(item.parameters) {
let a = a.as_item().ok_or_else(|| MergeError::new("Parameter references are not yet supported. Please open an issue if you need this feature."))?;
let b = b.as_item().ok_or_else(|| MergeError::new("Parameter references are not yet supported. Please open an issue if you need this feature."))?;
let a = a.parameter_data_ref();
let b = b.parameter_data_ref();
if a.name != b.name {
return Err(MergeError(format!("PathItem {} parameter {} does not have the same name as {}", path, a.name, b.name)));
}
}
} else {
self.paths.paths.insert(path, ReferenceOr::Item(item));
}
}
if self.components.is_none() {
self.components = other.components
} else if let (Some(self_components), Some(other_components)) = (&mut self.components, other.components) {
merge_map(&mut self_components.extensions, other_components.extensions);
merge_map(&mut self_components.schemas, other_components.schemas);
merge_map(&mut self_components.responses, other_components.responses);
merge_map(&mut self_components.parameters, other_components.parameters);
merge_map(&mut self_components.examples, other_components.examples);
merge_map(&mut self_components.request_bodies, other_components.request_bodies);
merge_map(&mut self_components.headers, other_components.headers);
merge_map(&mut self_components.security_schemes, other_components.security_schemes);
merge_map(&mut self_components.links, other_components.links);
merge_map(&mut self_components.callbacks, other_components.callbacks);
}
if self.security.is_none() {
self.security = other.security;
} else if let (Some(self_security), Some(other_security)) = (&mut self.security, other.security) {
merge_vec(self_security, other_security, |a, b| {
if a.len() != b.len() {
return false;
}
a.iter().all(|(a, _)| b.contains_key(a))
});
}
merge_vec(&mut self.tags, other.tags, |a, b| a.name == b.name);
match self.external_docs.as_mut() {
Some(ext) => {
if let Some(other) = other.external_docs {
merge_map(&mut ext.extensions, other.extensions)
}
},
None => self.external_docs = other.external_docs
}
merge_map(&mut self.extensions, other.extensions);
Ok(self)
}
pub fn merge_overwrite(self, other: OpenAPI) -> Result<Self, MergeError> {
other.merge(self)
}
}
impl Default for OpenAPI {
fn default() -> Self {
OpenAPI {
openapi: "3.0.3".to_string(),
info: Default::default(),
servers: vec![],
paths: Default::default(),
components: None,
security: None,
tags: vec![],
external_docs: None,
extensions: Default::default(),
}
}
}
fn merge_vec<T>(original: &mut Vec<T>, mut other: Vec<T>, cmp: fn(&T, &T) -> bool) {
other.retain(|o| original.iter().any(|r| cmp(o, r)));
original.extend(other);
}
fn merge_map<K, V>(original: &mut IndexMap<K, V>, mut other: IndexMap<K, V>) where K: Eq + std::hash::Hash {
other.retain(|k, _| original.contains_key(k));
original.extend(other);
}
fn option_or<T>(original: &mut Option<T>, other: Option<T>) {
if original.is_none() {
*original = other;
}
}
#[derive(Debug)]
pub struct MergeError(String);
impl MergeError {
pub fn new(msg: &str) -> Self {
MergeError(msg.to_string())
}
}
impl std::error::Error for MergeError {}
impl std::fmt::Display for MergeError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}