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
|
use crate::openapi::*;
use eyre::WrapErr;
use heck::ToPascalCase;
use std::fmt::Write;
pub fn create_structs(spec: &OpenApiV2) -> eyre::Result<String> {
let mut s = String::new();
s.push_str("use structs::*;\n");
s.push_str("pub mod structs {\n");
s.push_str("use crate::StructureError;");
if let Some(definitions) = &spec.definitions {
for (name, schema) in definitions {
let strukt = create_struct_for_definition(&spec, name, schema)?;
s.push_str(&strukt);
}
}
if let Some(responses) = &spec.responses {
for (name, response) in responses {
if let Some(headers) = &response.headers {
let strukt = create_header_struct(name, headers)?;
s.push_str(&strukt);
}
}
}
for (_, item) in &spec.paths {
let strukt = create_query_structs_for_path(item)?;
s.push_str(&strukt);
}
s.push_str("\n}");
Ok(s)
}
pub fn create_struct_for_definition(
spec: &OpenApiV2,
name: &str,
schema: &Schema,
) -> eyre::Result<String> {
if matches!(schema._type, Some(SchemaType::One(Primitive::Array))) {
return Ok(String::new());
}
let docs = create_struct_docs(schema)?;
let mut fields = String::new();
let required = schema.required.as_deref().unwrap_or_default();
if let Some(properties) = &schema.properties {
for (prop_name, prop_schema) in properties {
let prop_ty = crate::schema_ref_type_name(spec, prop_schema)?;
let field_name = crate::sanitize_ident(prop_name);
let mut field_ty = prop_ty.clone();
if field_name.ends_with("url") && field_name != "ssh_url" && field_ty == "String" {
field_ty = "url::Url".into()
}
if field_ty == name {
field_ty = format!("Box<{field_ty}>")
}
if !required.contains(prop_name) {
field_ty = format!("Option<{field_ty}>")
}
if field_ty == "Option<url::Url>" {
fields.push_str("#[serde(deserialize_with = \"crate::none_if_blank_url\")]\n");
}
if field_ty == "time::OffsetDateTime" {
fields.push_str("#[serde(with = \"time::serde::rfc3339\")]\n");
}
if field_ty == "Option<time::OffsetDateTime>" {
fields.push_str("#[serde(with = \"time::serde::rfc3339::option\")]\n");
}
if let MaybeRef::Value { value } = &prop_schema {
if let Some(desc) = &value.description {
for line in desc.lines() {
fields.push_str("/// ");
fields.push_str(line);
fields.push_str("\n/// \n");
}
}
}
if &field_name != prop_name {
fields.push_str("#[serde(rename = \"");
fields.push_str(prop_name);
fields.push_str("\")]\n");
}
fields.push_str("pub ");
fields.push_str(&field_name);
fields.push_str(": ");
fields.push_str(&field_ty);
fields.push_str(",\n");
}
}
if let Some(additonal_schema) = &schema.additional_properties {
let prop_ty = crate::schema_ref_type_name(spec, additonal_schema)?;
fields.push_str("#[serde(flatten)]\n");
fields.push_str("pub additional: std::collections::BTreeMap<String, ");
fields.push_str(&prop_ty);
fields.push_str(">,\n");
}
let out = format!("{docs}#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]\npub struct {name} {{\n{fields}}}\n\n");
Ok(out)
}
fn create_struct_docs(schema: &Schema) -> eyre::Result<String> {
let doc = match &schema.description {
Some(desc) => {
let mut out = String::new();
for line in desc.lines() {
out.push_str("/// ");
out.push_str(line);
out.push_str("\n/// \n");
}
out
}
None => String::new(),
};
Ok(doc)
}
pub fn create_query_structs_for_path(item: &PathItem) -> eyre::Result<String> {
let mut s = String::new();
if let Some(op) = &item.get {
s.push_str(&create_query_struct(op).wrap_err("GET")?);
}
if let Some(op) = &item.put {
s.push_str(&create_query_struct(op).wrap_err("PUT")?);
}
if let Some(op) = &item.post {
s.push_str(&create_query_struct(op).wrap_err("POST")?);
}
if let Some(op) = &item.delete {
s.push_str(&create_query_struct(op).wrap_err("DELETE")?);
}
if let Some(op) = &item.options {
s.push_str(&create_query_struct(op).wrap_err("OPTIONS")?);
}
if let Some(op) = &item.head {
s.push_str(&create_query_struct(op).wrap_err("HEAD")?);
}
if let Some(op) = &item.patch {
s.push_str(&create_query_struct(op).wrap_err("PATCH")?);
}
Ok(s)
}
pub fn query_struct_name(op: &Operation) -> eyre::Result<String> {
let mut ty = op
.operation_id
.as_deref()
.ok_or_else(|| eyre::eyre!("operation did not have id"))?
.to_pascal_case()
.replace("o_auth2", "oauth2");
ty.push_str("Query");
Ok(ty)
}
fn create_query_struct(op: &Operation) -> eyre::Result<String> {
let params = match &op.parameters {
Some(params) => params,
None => return Ok(String::new()),
};
let mut fields = String::new();
let mut imp = String::new();
for param in params {
let param = match ¶m {
MaybeRef::Value { value } => value,
MaybeRef::Ref { _ref } => eyre::bail!("todo: add deref parameters"),
};
if let ParameterIn::Query { param: query_param } = ¶m._in {
let ty = crate::methods::param_type(query_param, true)?;
let field_name = crate::sanitize_ident(¶m.name);
if let Some(desc) = ¶m.description {
for line in desc.lines() {
fields.push_str("/// ");
fields.push_str(line);
fields.push_str("\n/// \n");
}
}
fields.push_str("pub ");
fields.push_str(&field_name);
fields.push_str(": ");
if query_param.required {
fields.push_str(&ty);
} else {
fields.push_str("Option<");
fields.push_str(&ty);
fields.push_str(">");
}
fields.push_str(",\n");
let mut handler = String::new();
if query_param.required {
writeln!(&mut handler, "let {field_name} = &self.{field_name};")?;
} else {
writeln!(
&mut handler,
"if let Some({field_name}) = &self.{field_name} {{"
)?;
}
match &query_param._type {
ParameterType::String => match query_param.format.as_deref() {
Some("date-time" | "date") => {
writeln!(
&mut handler,
"write!(f, \"{}={{field_name}}&\", field_name = {field_name}.format(&time::format_description::well_known::Rfc3339).unwrap())?;",
param.name)?;
}
_ => {
writeln!(
&mut handler,
"write!(f, \"{}={{{}}}&\")?;",
param.name,
field_name.strip_prefix("r#").unwrap_or(&field_name)
)?;
}
},
ParameterType::Number | ParameterType::Integer | ParameterType::Boolean => {
writeln!(
&mut handler,
"write!(f, \"{}={{{}}}&\")?;",
param.name,
field_name.strip_prefix("r#").unwrap_or(&field_name)
)?;
}
ParameterType::Array => {
let format = query_param
.collection_format
.unwrap_or(CollectionFormat::Csv);
let item = query_param
.items
.as_ref()
.ok_or_else(|| eyre::eyre!("array must have item type defined"))?;
let item_pusher = match item._type {
ParameterType::String => {
match query_param.format.as_deref() {
Some("date-time" | "date") => {
"write!(f, \"{{date}}\", item.format(&time::format_description::well_known::Rfc3339).unwrap())?;"
},
_ => {
"write!(f, \"{item}\")?;"
}
}
},
ParameterType::Number |
ParameterType::Integer |
ParameterType::Boolean => {
"write!(f, \"{item}\")?;"
},
ParameterType::Array => {
eyre::bail!("nested arrays not supported in query");
},
ParameterType::File => eyre::bail!("cannot send file in query"),
};
match format {
CollectionFormat::Csv => {
handler.push_str(&simple_query_array(
param,
item_pusher,
&field_name,
",",
)?);
}
CollectionFormat::Ssv => {
handler.push_str(&simple_query_array(
param,
item_pusher,
&field_name,
" ",
)?);
}
CollectionFormat::Tsv => {
handler.push_str(&simple_query_array(
param,
item_pusher,
&field_name,
"\\t",
)?);
}
CollectionFormat::Pipes => {
handler.push_str(&simple_query_array(
param,
item_pusher,
&field_name,
"|",
)?);
}
CollectionFormat::Multi => {
writeln!(&mut handler)?;
writeln!(&mut handler, "if !{field_name}.is_empty() {{")?;
writeln!(&mut handler, "for item in {field_name} {{")?;
writeln!(&mut handler, "write!(f, \"{}=\")?;", param.name)?;
handler.push_str(item_pusher);
handler.push('\n');
writeln!(&mut handler, "write!(f, \"&\")?;")?;
writeln!(&mut handler, "}}")?;
writeln!(&mut handler, "}}")?;
}
}
}
ParameterType::File => eyre::bail!("cannot send file in query"),
}
if !query_param.required {
writeln!(&mut handler, "}}")?;
}
imp.push_str(&handler);
}
}
let result = if fields.is_empty() {
String::new()
} else {
let op_name = query_struct_name(op)?;
format!(
"
pub struct {op_name} {{
{fields}
}}
impl std::fmt::Display for {op_name} {{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{
{imp}
Ok(())
}}
}}
"
)
};
Ok(result)
}
fn simple_query_array(
param: &Parameter,
item_pusher: &str,
name: &str,
sep: &str,
) -> eyre::Result<String> {
let mut out = String::new();
writeln!(
&mut out,
"
if !{name}.is_empty() {{
write!(f, \"{}=\")?;
for (item, i) in {name}.iter().enumerate() {{
{item_pusher}
if i < {name}.len() - 1 {{
write!(f, \"{sep}\")?;
}}
}}
write!(f, \"&\")?;
}}",
param.name
)?;
Ok(out)
}
fn create_header_struct(
name: &str,
headers: &std::collections::BTreeMap<String, Header>,
) -> eyre::Result<String> {
let ty_name = format!("{name}Headers").to_pascal_case();
let mut fields = String::new();
let mut imp = String::new();
let mut imp_ret = String::new();
for (header_name, header) in headers {
let ty = header_type(header)?;
let field_name = crate::sanitize_ident(header_name);
fields.push_str("pub ");
fields.push_str(&field_name);
fields.push_str(": Option<");
fields.push_str(&ty);
fields.push_str(">,\n");
write!(
&mut imp,
"
let {field_name} = map.get(\"{header_name}\").map(|s| -> Result<_, _> {{
let s = s.to_str().map_err(|_| StructureError::HeaderNotAscii)?;
"
)
.unwrap();
match &header._type {
ParameterType::String => imp.push_str("Ok(s.to_string())"),
ParameterType::Number => match header.format.as_deref() {
Some("float") => {
imp.push_str("s.parse::<f32>().map_err(|_| StructureError::HeaderParseFailed)")
}
Some("double") | _ => {
imp.push_str("s.parse::<f64>()).map_err(|_| StructureError::HeaderParseFailed)")
}
},
ParameterType::Integer => match header.format.as_deref() {
Some("int64") => {
imp.push_str("s.parse::<u64>().map_err(|_| StructureError::HeaderParseFailed)")
}
Some("int32") | _ => {
imp.push_str("s.parse::<u32>().map_err(|_| StructureError::HeaderParseFailed)")
}
},
ParameterType::Boolean => {
imp.push_str("s.parse::<bool>().map_err(|_| StructureError::HeaderParseFailed)")
}
ParameterType::Array => {
let sep = match header.collection_format {
Some(CollectionFormat::Csv) | None => ",",
Some(CollectionFormat::Ssv) => " ",
Some(CollectionFormat::Tsv) => "\\t",
Some(CollectionFormat::Pipes) => "|",
Some(CollectionFormat::Multi) => {
eyre::bail!("multi format not supported in headers")
}
};
let items = header
.items
.as_ref()
.ok_or_else(|| eyre::eyre!("items property must be set for arrays"))?;
if items._type == ParameterType::String {
imp.push_str("Ok(");
}
imp.push_str("s.split(\"");
imp.push_str(sep);
imp.push_str("\").map(|s| ");
imp.push_str(match items._type {
ParameterType::String => "s.to_string()).collect::<Vec<_>>())",
ParameterType::Number => match items.format.as_deref() {
Some("float") => "s.parse::<f32>()).collect::<Result<Vec<_>, _>>().map_err(|_| StructureError::HeaderParseFailed)",
Some("double") | _ => "s.parse::<f64>()).collect::<Result<Vec<_>, _>>().map_err(|_| StructureError::HeaderParseFailed)",
},
ParameterType::Integer => match items.format.as_deref() {
Some("int64") => "s.parse::<u64>()).collect::<Result<Vec<_>, _>>().map_err(|_| StructureError::HeaderParseFailed)",
Some("int32") | _ => "s.parse::<u32>()).collect::<Result<Vec<_>, _>>().map_err(|_| StructureError::HeaderParseFailed)",
},
ParameterType::Boolean => "s.parse::<bool>()).collect::<Result<Vec<_>, _>>().map_err(|_| StructureError::HeaderParseFailed)",
ParameterType::Array => eyre::bail!("nested arrays not supported in headers"),
ParameterType::File => eyre::bail!("files not supported in headers"),
});
}
ParameterType::File => eyre::bail!("files not supported in headers"),
}
imp.push_str("}).transpose()?;");
imp_ret.push_str(&field_name);
imp_ret.push_str(", ");
}
Ok(format!(
"
pub struct {ty_name} {{
{fields}
}}
impl TryFrom<&reqwest::header::HeaderMap> for {ty_name} {{
type Error = StructureError;
fn try_from(map: &reqwest::header::HeaderMap) -> Result<Self, Self::Error> {{
{imp}
Ok(Self {{ {imp_ret} }})
}}
}}
"
))
}
pub fn header_type(header: &Header) -> eyre::Result<String> {
crate::methods::param_type_inner(
&header._type,
header.format.as_deref(),
header.items.as_ref(),
true,
)
}
|