-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcmd_api.rs
355 lines (292 loc) · 12 KB
/
cmd_api.rs
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
use std::{
collections::HashMap,
fmt::Write as _,
io::{Read, Write},
};
use anyhow::{anyhow, Result};
use clap::Parser;
use serde::{Deserialize, Serialize};
/// Makes an authenticated HTTP request to the Zoo API and prints the response.
///
/// The endpoint argument should be a path of a Zoo API endpoint.
///
/// The default HTTP request method is "GET" normally and "POST" if any parameters
/// were added. Override the method with `--method`.
///
/// Pass one or more `-f/--raw-field` values in "key=value" format to add static string
/// parameters to the request payload. To add non-string or otherwise dynamic values, see
/// `--field` below. Note that adding request parameters will automatically switch the
/// request method to POST. To send the parameters as a GET query string instead, use
/// `--method GET`.
///
/// The `-F/--field` flag has magic type conversion based on the format of the value:
///
/// - literal values "true", "false", "null", and integer/float numbers get converted to
/// appropriate JSON types;
/// - if the value starts with "@", the rest of the value is interpreted as a
/// filename to read the value from. Pass "-" to read from standard input.
///
/// Raw request body may be passed from the outside via a file specified by `--input`.
/// Pass "-" to read from standard input. In this mode, parameters specified via
/// `--field` flags are serialized into URL query parameters.
///
/// In `--paginate` mode, all pages of results will sequentially be requested until
/// there are no more pages of results.
#[derive(Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct CmdApi {
/// The endpoint to request.
#[clap(name = "endpoint", required = true)]
pub endpoint: String,
/// The HTTP method for the request.
#[clap(short = 'X', long)]
pub method: Option<http::method::Method>,
/// Make additional HTTP requests to fetch all pages of results.
#[clap(long, conflicts_with = "input")]
pub paginate: bool,
/// Add a typed parameter in key=value format.
#[clap(short = 'F', long)]
pub field: Vec<String>,
/// Add a string parameter in key=value format.
#[clap(short = 'f', long)]
pub raw_field: Vec<String>,
/// The file to use as body for the HTTP request (use "-" to read from standard input).
#[clap(long, default_value = "", conflicts_with = "paginate")]
pub input: String,
/// Include HTTP response headers in the output.
#[clap(short, long)]
pub include: bool,
/// Add a HTTP request header in `key:value` format.
#[clap(short = 'H', long)]
pub header: Vec<String>,
}
/// The JSON type for a paginated response.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PaginatableResponse {
/// The items in the response.
pub items: Vec<serde_json::Value>,
/// The pagination information for the response.
pub next_page: Option<String>,
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for CmdApi {
async fn run(&self, ctx: &mut crate::context::Context) -> Result<()> {
// Let's get the api client.
let client = ctx.api_client("")?;
// Make sure the endpoint starts with a slash.
let mut endpoint = self.endpoint.to_string();
if !self.endpoint.starts_with('/') {
endpoint = format!("/{endpoint}");
}
// Parse the fields.
let params = self.parse_fields(ctx)?;
// Set them as our body if they exist.
let mut b = String::new();
if !params.is_empty() {
b = serde_json::to_string(¶ms)?;
}
let mut bytes = b.as_bytes().to_vec();
// If they didn't specify the method and we have parameters, we'l
// assume they want to use POST.
let method = if let Some(m) = &self.method {
m.clone()
} else if !params.is_empty() {
http::method::Method::POST
} else {
http::method::Method::GET
};
if self.paginate && method != http::method::Method::GET {
return Err(anyhow!("the `--paginate` option is not supported for non-GET requests",));
}
// Parse the input file.
if !self.input.is_empty() {
// Read the input file.
let mut buf = Vec::new();
if self.input == "-" {
// Read from stdin.
ctx.io.stdin.read_to_end(&mut buf)?;
} else {
let mut input_file = std::fs::File::open(&self.input)?;
input_file.read_to_end(&mut buf)?;
}
// Set this as our body.
bytes.clone_from(&buf);
// Set our params to the query string.
if !params.is_empty() {
let mut query_string = String::new();
for (key, value) in params {
if !query_string.is_empty() {
query_string.push('&');
}
write!(query_string, "{key}={value}")?;
}
endpoint = add_query_string(&endpoint, &query_string);
}
}
// Make the request.
let mut has_next_page = true;
let mut result = serde_json::Value::Null;
let mut page_results: Vec<serde_json::Value> = Vec::new();
while has_next_page {
let body = if bytes.is_empty() {
None
} else {
Some(reqwest::Body::from(bytes.clone()))
};
let mut req = client.request_raw(method.clone(), &endpoint, body).await?;
// Let's add our headers.
let headers = self.parse_headers()?;
if !headers.is_empty() {
for (key, value) in headers {
req = kittycad::RequestBuilder(req.0.header(key, value));
}
}
let resp = req.0.send().await?;
// Print the response headers if requested.
if self.include {
writeln!(ctx.io.out, "{:?} {}", resp.version(), resp.status())?;
print_headers(ctx, resp.headers())?;
}
if resp.status() == 204 {
return Ok(());
}
if !resp.status().is_success() {
return Err(anyhow!(
"{} {}",
resp.status(),
resp.status().canonical_reason().unwrap_or("")
));
}
if self.paginate {
let mut page: PaginatableResponse = resp.json().await?;
if !page.items.is_empty() {
page_results.append(&mut page.items);
}
match page.next_page {
Some(next_page) => {
endpoint = add_query_string(&endpoint, &format!("page_token={next_page}"));
}
None => {
has_next_page = false;
}
}
} else {
// Read the response body.
result = resp.json().await?;
has_next_page = false;
}
}
if self.paginate {
result = serde_json::Value::Array(page_results);
}
ctx.io.write_output_json(&result)?;
Ok(())
}
}
impl CmdApi {
fn parse_headers(&self) -> Result<HashMap<String, String>> {
let mut headers: HashMap<String, String> = HashMap::new();
for h in self.header.iter() {
let mut parts = h.splitn(2, ':');
let key = parts.next().ok_or_else(|| anyhow!("missing key in --header"))?;
let value = parts.next().ok_or_else(|| anyhow!("missing value in --header"))?;
headers.insert(key.to_string(), value.to_string());
}
Ok(headers)
}
fn parse_fields(&self, ctx: &mut crate::context::Context) -> Result<HashMap<String, serde_json::Value>> {
let mut params: HashMap<String, serde_json::Value> = HashMap::new();
// Parse the raw fields.
// These are always added as strings.
for f in self.raw_field.iter() {
let mut parts = f.splitn(2, '=');
let key = parts.next().ok_or_else(|| anyhow!("missing key in --raw-field"))?;
let value = parts.next().ok_or_else(|| anyhow!("missing value in --raw-field"))?;
params.insert(key.to_string(), serde_json::Value::String(value.to_string()));
}
// Parse the typed fields.
for t in self.field.iter() {
let mut parts = t.splitn(2, '=');
let key = parts.next().ok_or_else(|| anyhow!("missing key in --field"))?;
let value = parts.next().ok_or_else(|| anyhow!("missing value in --field"))?;
// See if value parses as an integer.
if let Ok(i) = value.parse::<i64>() {
params.insert(key.to_string(), serde_json::Value::Number(i.into()));
continue;
}
// See if value parses as a float.
if let Ok(f) = value.parse::<f64>() {
let num = serde_json::Number::from_f64(f).ok_or_else(|| anyhow!("invalid float {}", f))?;
params.insert(key.to_string(), serde_json::Value::Number(num));
continue;
}
// Check the rest.
let value = match value {
"true" => serde_json::Value::Bool(true),
"false" => serde_json::Value::Bool(false),
"null" => serde_json::Value::Null,
_ => {
// Check if we have a file.
if value.starts_with('@') {
let filename = value.trim_start_matches('@');
let mut file = std::fs::File::open(filename)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
serde_json::Value::String(contents)
} else if value == "-" {
// Read from stdin.
let mut contents = String::new();
ctx.io.stdin.read_to_string(&mut contents)?;
serde_json::Value::String(contents)
} else {
serde_json::Value::String(value.to_string())
}
}
};
params.insert(key.to_string(), value);
}
Ok(params)
}
}
fn print_headers(ctx: &mut crate::context::Context, headers: &reqwest::header::HeaderMap) -> Result<()> {
let mut names: Vec<String> = headers.keys().map(|k| k.as_str().to_string()).collect();
names.sort_by_key(|a| a.to_lowercase());
let cs = ctx.io.color_scheme();
let mut tw = tabwriter::TabWriter::new(vec![]);
for name in names {
if name.to_lowercase() == "status" {
continue;
}
let value = headers.get(name.as_str()).unwrap();
writeln!(tw, "{}:\t{:?}", cs.cyan(&name), value)?;
}
tw.flush()?;
let table = String::from_utf8(tw.into_inner()?)?;
writeln!(ctx.io.out, "{table}")?;
Ok(())
}
fn add_query_string(endpoint: &str, query_string: &str) -> String {
if endpoint.contains('?') {
format!("{endpoint}&{query_string}")
} else {
format!("{endpoint}?{query_string}")
}
}
#[cfg(test)]
mod test {
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn test_add_query_string() {
let mut endpoint = "https://api.github.com/users/octocat/repos";
let mut query_string = "page=2&per_page=100";
let mut result = add_query_string(endpoint, query_string);
let mut expected = "https://api.github.com/users/octocat/repos?page=2&per_page=100";
assert_eq!(result, expected);
endpoint = "https://api.github.com/users/octocat/repos?page=2&per_page=100";
query_string = "foo=bar";
result = add_query_string(endpoint, query_string);
expected = "https://api.github.com/users/octocat/repos?page=2&per_page=100&foo=bar";
assert_eq!(result, expected);
}
}