goat_cli/utils/
tax_ranks.rs

1use crate::error::{Error, ErrorKind, Result};
2use std::fmt;
3
4use crate::utils::utils;
5
6/// Taken from the NCBI taxdump
7/// on the date: 22.02.22.
8///
9/// These are all possible ranks that
10/// a user can return results as.
11const TAX_RANKS: &[&str; 44] = &[
12    "biotype",
13    "clade",
14    "class",
15    "cohort",
16    "family",
17    "forma",
18    "forma specialis",
19    "genotype",
20    "genus",
21    "infraclass",
22    "infraorder",
23    "isolate",
24    "kingdom",
25    "morph",
26    "no rank",
27    "order",
28    "parvorder",
29    "pathogroup",
30    "phylum",
31    "section",
32    "series",
33    "serogroup",
34    "serotype",
35    "species",
36    "species group",
37    "species subgroup",
38    "strain",
39    "subclass",
40    "subcohort",
41    "subfamily",
42    "subgenus",
43    "subkingdom",
44    "suborder",
45    "subphylum",
46    "subsection",
47    "subspecies",
48    "subtribe",
49    "superclass",
50    "superfamily",
51    "superkingdom",
52    "superorder",
53    "superphylum",
54    "tribe",
55    "varietas",
56];
57
58// we only really need to do two things
59// check if user has input a real tax rank
60// and display the tax ranks
61
62/// The [`TaxRanks`] struct holds the NCBI taxon
63/// ranks defined in the `TAX_RANKS` const.
64pub struct TaxRanks<'a> {
65    pub ranks: &'a [&'a str; 44],
66}
67
68impl<'a> TaxRanks<'a> {
69    /// Constructor for [`TaxRanks`].
70    pub fn init() -> Self {
71        Self { ranks: TAX_RANKS }
72    }
73
74    /// Convert a `--tax-rank` CLI comma separated string
75    /// into a URL encoded string of taxon ranks.
76    ///
77    /// If report == true, we are comparing a taxon rank for `report`.
78    /// Was unsure whether to keep this functionality here or to split
79    /// it out. Probably confusing to keep it here, but will change later.
80    pub fn parse(&self, cmp: &str, report: bool) -> Result<String> {
81        // if we are in the report API
82        if report {
83            let needle = cmp;
84            if self.ranks.contains(&needle) {
85                return Ok(needle.to_string());
86            } else {
87                return Err(Error::new(ErrorKind::TaxRank(format!(
88                    "Taxonomic rank \"{}\" is not recognised.\n\nEnter one of: {}",
89                    needle,
90                    Self::init()
91                ))));
92            }
93        }
94        // split the string on commas
95        let split = utils::parse_comma_separated(cmp);
96        let mut ranks_vec = Vec::new();
97
98        // iterate over split
99        for el in split {
100            if self.ranks.contains(&&el[..]) {
101                ranks_vec.push(el);
102            } else {
103                return Err(Error::new(ErrorKind::TaxRank(format!(
104                    "taxonomic rank \"{}\" is not recognised.\n\nEnter one of: {}",
105                    el,
106                    Self::init()
107                ))));
108            }
109        }
110
111        // Return unencoded — url builder handles encoding
112        Ok(format!(" AND tax_rank({})", ranks_vec.join(",")))
113    }
114}
115
116impl<'a> fmt::Display for TaxRanks<'a> {
117    /// Format [`TaxRanks`] into a comma separated list.
118    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119        // Use `self.number` to refer to each positional data point.
120        let tax_ranks_csv = self.ranks.join(", ");
121        write!(f, "{}", tax_ranks_csv)
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    // ── search mode (report = false) ─────────────────────────────────────────
130
131    #[test]
132    fn test_valid_rank_returns_url_segment() {
133        let tr = TaxRanks::init();
134        let result = tr.parse("species", false).unwrap();
135        assert!(result.contains("tax_rank"));
136        assert!(result.contains("species"));
137        assert!(result.starts_with(" AND tax_rank("));
138        assert!(result.ends_with(')'));
139    }
140
141    #[test]
142    fn test_multiple_ranks_comma_separated() {
143        let tr = TaxRanks::init();
144        let result = tr.parse("species,genus", false).unwrap();
145        assert!(result.contains("species"));
146        assert!(result.contains("genus"));
147        // both should be inside the same tax_rank() call, separated by a plain comma
148        assert!(result.contains(','));
149    }
150
151    #[test]
152    fn test_invalid_rank_search_mode_returns_err() {
153        let tr = TaxRanks::init();
154        let result = tr.parse("notarank", false);
155        assert!(result.is_err());
156    }
157
158    #[test]
159    fn test_invalid_rank_in_list_returns_err() {
160        let tr = TaxRanks::init();
161        let result = tr.parse("species,notarank", false);
162        assert!(result.is_err());
163    }
164
165    // ── report mode (report = true) ──────────────────────────────────────────
166
167    #[test]
168    fn test_report_mode_valid_rank_returns_plain_string() {
169        let tr = TaxRanks::init();
170        let result = tr.parse("genus", true).unwrap();
171        assert_eq!(result, "genus");
172    }
173
174    #[test]
175    fn test_report_mode_invalid_rank_returns_err() {
176        let tr = TaxRanks::init();
177        let result = tr.parse("notarank", true);
178        assert!(result.is_err());
179    }
180
181    #[test]
182    fn test_all_canonical_ranks_are_valid() {
183        let tr = TaxRanks::init();
184        for rank in tr.ranks.iter() {
185            assert!(
186                tr.parse(rank, false).is_ok(),
187                "rank '{}' should be valid",
188                rank
189            );
190        }
191    }
192}