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
use crate::utils::cli_matches::UPPER_CLI_FILE_LIMIT;
use crate::utils::url::{GOAT_URL, TAXONOMY};
use crate::utils::utils::{
lines_from_file, parse_comma_separated, some_kind_of_uppercase_first_letter,
};
use anyhow::{bail, Result};
use futures::StreamExt;
use reqwest;
use reqwest::header::ACCEPT;
use serde_json::Value;
#[derive(Clone, Debug)]
pub struct Lookup {
pub search: String,
pub size: u64,
}
impl Lookup {
pub fn make_url(&self) -> String {
let mut url = String::new();
url += &GOAT_URL;
url += &"lookup?";
let search_term = format!("searchTerm={}", self.search);
url += &search_term;
let size = format!("&size={}", self.size);
url += &size;
url += &format!("&result=taxon&taxonomy={}", &*TAXONOMY);
url
}
}
pub struct Lookups {
pub entries: Vec<Lookup>,
}
impl Lookups {
fn new(matches: &clap::ArgMatches) -> Result<Self> {
let tax_name_op = matches.value_of("taxon");
let filename_op = matches.value_of("file");
let no_hits = matches.value_of("size").unwrap();
let no_hits = no_hits.parse::<u64>().unwrap_or(10);
let tax_name_vector: Vec<String>;
match tax_name_op {
Some(s) => tax_name_vector = parse_comma_separated(s),
None => match filename_op {
Some(s) => {
tax_name_vector = lines_from_file(s)?;
if tax_name_vector.len() > *UPPER_CLI_FILE_LIMIT {
bail!(
"[-]\tNumber of taxa specified cannot exceed {}.",
*UPPER_CLI_FILE_LIMIT
)
}
}
None => bail!("[-]\tOne of -f (--file) or -t (--tax-id) should be specified."),
},
}
let mut res = Vec::new();
for el in tax_name_vector {
res.push(Lookup {
search: el,
size: no_hits,
})
}
Ok(Self { entries: res })
}
pub fn make_urls(&self) -> Vec<String> {
let mut url_vector = Vec::new();
for el in &self.entries {
url_vector.push(el.make_url());
}
url_vector
}
}
#[derive(Clone)]
pub struct Collector {
pub search: Option<String>,
pub taxon_id: Vec<Option<String>>,
pub taxon_rank: Vec<Option<String>>,
pub taxon_names: Vec<Option<Vec<(String, String)>>>,
pub suggestions: Option<Vec<Option<String>>>,
}
impl Collector {
pub fn print_result(&self, index: usize) -> Result<()> {
match &self.search {
Some(search) => {
match &self.suggestions {
Some(suggestions) => {
let mut suggestion_str = String::new();
for el in suggestions {
match el {
Some(s) => {
suggestion_str += &some_kind_of_uppercase_first_letter(&s[..]);
suggestion_str += ", ";
}
None => {}
}
}
if suggestion_str.len() > 2 {
suggestion_str.drain(suggestion_str.len() - 2..);
Ok(eprintln!("[-]\tDid you mean: {}?", suggestion_str))
} else {
Ok(eprintln!("[-]\tThere are no results."))
}
}
None => {
let taxon_id = self.taxon_id.clone();
let taxon_rank = self.taxon_rank.clone();
let taxon_names = self.taxon_names.clone();
let taxon_ids_op: Option<Vec<String>> = taxon_id.into_iter().collect();
let taxon_ranks_op: Option<Vec<String>> = taxon_rank.into_iter().collect();
let taxon_names_op: Option<Vec<Vec<(String, String)>>> =
taxon_names.into_iter().collect();
if index == 0 {
println!("taxon\trank\tsearch_query\tname\ttype");
}
match taxon_names_op {
Some(n) => {
let taxon_ids = match taxon_ids_op {
Some(t) => t,
None => vec![],
};
let taxon_ranks = match taxon_ranks_op {
Some(t) => t,
None => vec![],
};
let mut zipped_taxon_vectors =
taxon_ids.iter().zip(taxon_ranks.iter()).zip(n.iter());
let mut whole_res_string = String::new();
while let Some(((taxon_id, taxon_rank), taxon_ranks)) =
zipped_taxon_vectors.next()
{
for el in taxon_ranks {
let row = format!(
"{}\t{}\t{}\t{}\t{}\n",
taxon_id, taxon_rank, search, el.0, el.1
);
whole_res_string += &row;
}
}
whole_res_string.pop();
Ok(println!("{}", whole_res_string))
}
None => Ok(eprintln!("There were no taxon names.")),
}
}
}
}
None => Ok(eprintln!("No results.")),
}
}
pub fn return_taxid_vec(&self) -> Result<Option<String>> {
match &self.search {
Some(search) => {
match &self.suggestions {
Some(suggestions) => {
let mut suggestion_str = String::new();
for el in suggestions {
match el {
Some(s) => {
suggestion_str += &some_kind_of_uppercase_first_letter(&s[..]);
suggestion_str += ", ";
}
None => {}
}
}
if suggestion_str.len() > 2 {
suggestion_str.drain(suggestion_str.len() - 2..);
eprintln!(
"[-]\tYou searched {}. Did you mean: {}?",
search, suggestion_str
);
Ok(None)
} else {
eprintln!("[-]\tThere are no results for the search: {}", search);
Ok(None)
}
}
None => {
let taxon_id = self.taxon_id.clone();
let taxon_ids_op: Option<Vec<String>> = taxon_id.into_iter().collect();
let taxon_id = match taxon_ids_op {
Some(t) => t.join("%2C"),
None => "No taxon ID".to_string(),
};
Ok(Some(taxon_id))
}
}
}
None => bail!("No results."),
}
}
}
pub async fn lookup(matches: &clap::ArgMatches, cli: bool) -> Result<Option<Vec<String>>> {
let lookups = Lookups::new(matches)?;
let url_vector_api = lookups.make_urls();
let print_url = matches.is_present("url");
let size = matches.value_of("size").unwrap();
let search_query_op = lookups.entries.get(0);
let search_query = match search_query_op {
Some(q) => &q.search,
None => "None",
};
if print_url {
for (index, url) in url_vector_api.iter().enumerate() {
println!("{}.\tGoaT lookup API URL: {}", index, url);
}
if cli {
std::process::exit(0);
}
}
let concurrent_requests = url_vector_api.len();
let fetches = futures::stream::iter(url_vector_api.into_iter().map(|path| async move {
let client = reqwest::Client::new();
match again::retry(|| client.get(&path).header(ACCEPT, "application/json").send()).await {
Ok(resp) => match resp.text().await {
Ok(body) => {
let v: Value = serde_json::from_str(&body)?;
let request_size_op = &v["status"]["hits"].as_u64();
match request_size_op {
Some(s) => {
if size.parse::<u64>()? < *s {
eprintln!(
"[-]\tFor seach query {}, size specified ({}) was less than the number of results returned, ({}).",
search_query, size, s
)
}
},
None => (),
}
let suggestions_text_op = &v["suggestions"].as_array();
let mut suggestions_vec = Vec::new();
let suggestions_text = match suggestions_text_op {
Some(suggestions) => {
for el in *suggestions {
let sug_str = el["suggestion"]["text"].as_str();
let sug_string_op = sug_str.map(String::from);
suggestions_vec.push(sug_string_op);
}
Some(suggestions_vec.clone())
}
None => None,
};
let mut taxon_id_vec = Vec::new();
let mut taxon_rank_vec = Vec::new();
let mut taxon_names_array_vec = Vec::new();
let results_array = v["results"].as_array();
match results_array {
Some(arr) => {
for el in arr {
let taxon_id = el["result"]["taxon_id"].as_str();
let taxon_rank = el["result"]["taxon_rank"].as_str();
let taxon_names_array_op = el["result"]["taxon_names"].as_array();
let taxon_names_array = match taxon_names_array_op {
Some(vec) => {
let mut collect_names = Vec::new();
for el in vec.into_iter() {
let key = el["name"].as_str().unwrap_or("-");
let value = el["class"].as_str().unwrap_or("-");
collect_names
.push((key.to_string(), value.to_string()));
}
Some(collect_names)
}
None => None,
};
taxon_id_vec.push(taxon_id);
taxon_rank_vec.push(taxon_rank);
taxon_names_array_vec.push(taxon_names_array);
}
}
None => {}
}
let taxon_id = taxon_id_vec.iter().map(|e| e.map(String::from)).collect();
let taxon_rank = taxon_rank_vec.iter().map(|e| e.map(String::from)).collect();
Ok(Collector {
search: Some(search_query.to_string()),
suggestions: suggestions_text,
taxon_id,
taxon_names: taxon_names_array_vec,
taxon_rank,
})
}
Err(_) => bail!("ERROR reading {}", path),
},
Err(_) => bail!("ERROR downloading {}", path),
}
}))
.buffer_unordered(concurrent_requests)
.collect::<Vec<_>>();
let awaited_fetches = fetches.await;
let mut return_taxid_vec: Vec<String> = Vec::new();
for (index, el) in awaited_fetches.iter().enumerate() {
match el {
Ok(e) => {
if cli {
e.print_result(index)?;
} else {
let taxid_op = e.return_taxid_vec()?;
match taxid_op {
Some(s) => return_taxid_vec.push(s),
None => return_taxid_vec.push("-".to_string()),
}
}
}
Err(_) => bail!("No results found."),
}
}
Ok(Some(return_taxid_vec))
}