goat_cli/count/
mod.rs

1//!
2//! Invoked by calling:
3//! `goat-cli count <args>`
4
5use crate::client::GoatClient;
6use crate::error::{Error, ErrorKind, Result};
7use futures::StreamExt;
8use serde_json::json;
9
10use crate::cli::SearchRequest;
11use crate::output::Table;
12use crate::utils::cli_matches::{self, CliAction};
13
14/// How to show a search query to the user; an empty one (no `-t`/`-f`)
15/// searches all taxa.
16fn query_label(search_query: &str) -> &str {
17    if search_query.is_empty() {
18        "<all taxa>"
19    } else {
20        search_query
21    }
22}
23
24/// `goat-cli count` presents an identical CLI to `goat-cli search` but prints
25/// to the console in the CLI call here, and to the stderr in the `goat-cli search` call.
26pub async fn count(
27    request: &SearchRequest,
28    cli: bool,
29    print_warning: bool,
30    unique_ids: Vec<String>,
31) -> Result<Option<u64>> {
32    let (size_int, url_vector, url_vector_api) =
33        match cli_matches::process_cli_args(request, "count", unique_ids)? {
34            CliAction::Continue { size, taxa, urls } => (size, taxa, urls),
35            CliAction::PrintedAndExit => return Ok(None),
36        };
37
38    let concurrent_requests = url_vector_api.len();
39
40    let client = GoatClient::new();
41    let fetches = futures::stream::iter(
42        url_vector_api
43            .into_iter()
44            .zip(url_vector.iter().cloned())
45            .map(|(path, search_query)| {
46                let client = client.clone();
47                async move {
48                    let v = client.get_json(&path).await?;
49                    let count = v["count"].as_u64().ok_or_else(|| {
50                        Error::new(ErrorKind::GenericCli(format!(
51                            "Bad count response: {:?}",
52                            v
53                        )))
54                    })?;
55                    Ok((search_query, count))
56                }
57            }),
58    )
59    .buffered(crate::client::concurrency(concurrent_requests))
60    .collect::<Vec<_>>();
61
62    let awaited_fetches = fetches.await;
63
64    match cli {
65        true => {
66            // print to console
67            let mut outer_count = 0;
68            let mut table = Table::new(&["search_query", "count"]);
69            for el in awaited_fetches {
70                let (search_query, count) = el?;
71                table.push(vec![json!(query_label(&search_query)), json!(count)]);
72                outer_count += count;
73            }
74            table.print(request.output.format)?;
75            Ok(Some(outer_count))
76        }
77        false => {
78            // need
79            let mut outer_count = 0;
80            // the zip does not correspond to the awaited fetches...
81            // need to match them
82            for el in awaited_fetches {
83                let (search_query, count) = match el {
84                    Ok(e) => e,
85                    Err(e) => return Err(e),
86                };
87                if print_warning && count == 0 {
88                    eprintln!("No results for search query {}.", query_label(&search_query));
89                } else if print_warning && size_int < count {
90                    eprintln!(
91                        "For search query {}, size specified ({}) was less than the number of results returned, ({}).",
92                        query_label(&search_query), size_int, count
93                    );
94                }
95                outer_count += count;
96            }
97
98            Ok(Some(outer_count))
99        }
100    }
101}