Skip to main content

gtars_refget/
inputs.rs

1//! Reusable expansion of multi-FASTA input specifications.
2//!
3//! Both the CLI (`gtars refget build`) and the Python binding share this single
4//! code path so that the resulting list of FASTA files — and therefore the
5//! resulting store — is identical regardless of how the inputs were specified.
6//!
7//! See [`expand_fasta_inputs`] for the ordering contract.
8
9use std::path::{Path, PathBuf};
10
11use anyhow::{anyhow, Context};
12
13/// Recognized FASTA extensions (case-insensitive). Used to filter directory
14/// contents. Plain explicit file paths are NOT required to match these.
15pub const FASTA_EXTENSIONS: &[&str] = &["fa", "fasta", "fna", "fa.gz", "fasta.gz", "fna.gz"];
16
17/// A bundle of user-supplied FASTA input specifications.
18///
19/// Entries in `paths` may be literal file paths, glob patterns, or directories.
20/// `file_list` is an optional file-of-filenames (fofn).
21#[derive(Debug, Default, Clone)]
22pub struct FastaInputs {
23    /// Literal paths to files, glob patterns, or directories, in the order
24    /// the caller supplied them (e.g. CLI positional args).
25    pub paths: Vec<PathBuf>,
26    /// Optional fofn: a file containing one path per line.
27    pub file_list: Option<PathBuf>,
28}
29
30/// Returns true if the entry's file name (case-insensitive) ends with one of
31/// the recognized FASTA extensions.
32fn has_fasta_extension(path: &Path) -> bool {
33    let name = match path.file_name().and_then(|n| n.to_str()) {
34        Some(n) => n.to_ascii_lowercase(),
35        None => return false,
36    };
37    FASTA_EXTENSIONS
38        .iter()
39        .any(|ext| name.ends_with(&format!(".{ext}")))
40}
41
42/// Returns true if the literal string looks like a glob pattern (contains any
43/// of the glob metacharacters `*`, `?`, `[`).
44fn looks_like_glob(s: &str) -> bool {
45    s.contains('*') || s.contains('?') || s.contains('[')
46}
47
48/// Expand a single working-list entry (path, glob, or directory) into zero or
49/// more concrete file paths, appending to `out`.
50fn expand_entry(entry: &Path, out: &mut Vec<PathBuf>) -> Result<(), anyhow::Error> {
51    let entry_str = entry.to_string_lossy();
52
53    if entry.is_dir() {
54        // Directory: keep top-level files with a FASTA extension, sorted.
55        let mut matches: Vec<PathBuf> = std::fs::read_dir(entry)
56            .with_context(|| format!("Failed to read directory '{}'", entry.display()))?
57            .filter_map(|e| e.ok().map(|e| e.path()))
58            .filter(|p| p.is_file() && has_fasta_extension(p))
59            .collect();
60        matches.sort();
61        out.extend(matches);
62        Ok(())
63    } else if looks_like_glob(&entry_str) {
64        // Glob pattern: expand, keep files only, sorted; empty match is an error.
65        let paths = glob::glob(&entry_str)
66            .with_context(|| format!("Invalid glob pattern '{}'", entry_str))?;
67        let mut matches: Vec<PathBuf> = Vec::new();
68        for p in paths {
69            let p = p.with_context(|| {
70                format!("Error reading path matched by glob '{}'", entry_str)
71            })?;
72            if p.is_file() {
73                matches.push(p);
74            }
75        }
76        if matches.is_empty() {
77            return Err(anyhow!("Glob pattern '{}' matched no files", entry_str));
78        }
79        matches.sort();
80        out.extend(matches);
81        Ok(())
82    } else {
83        // Plain file path: must exist. No extension requirement.
84        if !entry.exists() {
85            return Err(anyhow!("Input path does not exist: '{}'", entry.display()));
86        }
87        out.push(entry.to_path_buf());
88        Ok(())
89    }
90}
91
92/// Read a fofn (file-of-filenames) and return its meaningful lines as paths.
93///
94/// Each line is trimmed; blank lines and lines beginning with `#` are skipped.
95/// Relative paths are resolved relative to the current working directory (not
96/// the fofn's location).
97fn read_file_list(file_list: &Path) -> Result<Vec<PathBuf>, anyhow::Error> {
98    let contents = std::fs::read_to_string(file_list)
99        .with_context(|| format!("Failed to read file list '{}'", file_list.display()))?;
100    Ok(contents
101        .lines()
102        .map(|l| l.trim())
103        .filter(|l| !l.is_empty() && !l.starts_with('#'))
104        .map(PathBuf::from)
105        .collect())
106}
107
108/// Expand a [`FastaInputs`] bundle into a de-duplicated, deterministically
109/// ordered list of FASTA file paths.
110///
111/// # Ordering contract
112///
113/// Order is: explicit paths first (in argv order), then `file_list` lines (in
114/// file order); within each directory or glob the matches are sorted
115/// lexicographically; duplicates are removed keeping the first occurrence. This
116/// order is what feeds collection insertion and member order, so it is stable
117/// and identical across the CLI and Python entry points.
118///
119/// # Expansion rules
120///
121/// - **Directory**: top-level (non-recursive) files whose name ends with a
122///   [`FASTA_EXTENSIONS`] entry (case-insensitive), sorted lexicographically.
123/// - **Glob pattern** (contains `*`, `?`, or `[`): expanded with the `glob`
124///   crate, keeping files only, sorted lexicographically. A glob matching zero
125///   files is an error.
126/// - **Plain file path**: used as-is (no extension requirement). A
127///   non-existent path is an error.
128///
129/// A `file_list` line may itself be a glob or directory (so a fofn can mix
130/// forms).
131///
132/// # Errors
133///
134/// Returns an error if: a glob matches nothing, an explicit path does not
135/// exist, the fofn is unreadable, a glob pattern is malformed, or the final
136/// expanded list is empty.
137pub fn expand_fasta_inputs(inputs: &FastaInputs) -> Result<Vec<PathBuf>, anyhow::Error> {
138    // 1. Build the ordered working list: explicit paths first, then fofn lines.
139    let mut working: Vec<PathBuf> = inputs.paths.clone();
140    if let Some(file_list) = &inputs.file_list {
141        working.extend(read_file_list(file_list)?);
142    }
143
144    // 2. Expand each working-list entry.
145    let mut expanded: Vec<PathBuf> = Vec::new();
146    for entry in &working {
147        expand_entry(entry, &mut expanded)?;
148    }
149
150    // 3. De-duplicate by canonical path, preserving first-seen order.
151    let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
152    let mut result: Vec<PathBuf> = Vec::with_capacity(expanded.len());
153    for path in expanded {
154        let key = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
155        if seen.insert(key) {
156            result.push(path);
157        }
158    }
159
160    // 4. The final list must not be empty.
161    if result.is_empty() {
162        return Err(anyhow!("no FASTA inputs found after expansion"));
163    }
164
165    Ok(result)
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use std::fs::File;
172    use std::io::Write;
173    use tempfile::tempdir;
174
175    fn touch(dir: &Path, name: &str) -> PathBuf {
176        let p = dir.join(name);
177        File::create(&p).unwrap();
178        p
179    }
180
181    #[test]
182    fn fofn_parsing_skips_blanks_and_comments() {
183        let dir = tempdir().unwrap();
184        let a = touch(dir.path(), "a.fa");
185        let b = touch(dir.path(), "b.fa");
186
187        let fofn = dir.path().join("list.txt");
188        let mut f = File::create(&fofn).unwrap();
189        writeln!(f, "# a comment").unwrap();
190        writeln!(f, "").unwrap();
191        writeln!(f, "  {}  ", a.display()).unwrap();
192        writeln!(f, "   ").unwrap();
193        writeln!(f, "{}", b.display()).unwrap();
194        writeln!(f, "# trailing comment").unwrap();
195        drop(f);
196
197        let inputs = FastaInputs {
198            paths: vec![],
199            file_list: Some(fofn),
200        };
201        let out = expand_fasta_inputs(&inputs).unwrap();
202        assert_eq!(out, vec![a, b]);
203    }
204
205    #[test]
206    fn glob_expansion_is_lexicographically_ordered_and_deterministic() {
207        let dir = tempdir().unwrap();
208        // Create out of lexical order.
209        touch(dir.path(), "c.fa");
210        touch(dir.path(), "a.fa");
211        touch(dir.path(), "b.fa");
212
213        let pattern = dir.path().join("*.fa");
214        let inputs = FastaInputs {
215            paths: vec![pattern.clone()],
216            file_list: None,
217        };
218        let out1 = expand_fasta_inputs(&inputs).unwrap();
219        let names: Vec<String> = out1
220            .iter()
221            .map(|p| p.file_name().unwrap().to_str().unwrap().to_string())
222            .collect();
223        assert_eq!(names, vec!["a.fa", "b.fa", "c.fa"]);
224
225        // Repeated calls are identical.
226        let out2 = expand_fasta_inputs(&inputs).unwrap();
227        assert_eq!(out1, out2);
228    }
229
230    #[test]
231    fn directory_input_filters_by_extension_and_sorts() {
232        let dir = tempdir().unwrap();
233        touch(dir.path(), "z.fa");
234        touch(dir.path(), "a.fasta.gz");
235        touch(dir.path(), "m.fna");
236        touch(dir.path(), "decoy.txt");
237        touch(dir.path(), "readme.md");
238
239        let inputs = FastaInputs {
240            paths: vec![dir.path().to_path_buf()],
241            file_list: None,
242        };
243        let out = expand_fasta_inputs(&inputs).unwrap();
244        let names: Vec<String> = out
245            .iter()
246            .map(|p| p.file_name().unwrap().to_str().unwrap().to_string())
247            .collect();
248        assert_eq!(names, vec!["a.fasta.gz", "m.fna", "z.fa"]);
249    }
250
251    #[test]
252    fn dedup_preserves_first_seen_order() {
253        let dir = tempdir().unwrap();
254        let x = touch(dir.path(), "x.fa");
255        let y = touch(dir.path(), "y.fa");
256
257        // x explicit, then the directory (which contains x and y), then x again.
258        let inputs = FastaInputs {
259            paths: vec![x.clone(), dir.path().to_path_buf(), x.clone()],
260            file_list: None,
261        };
262        let out = expand_fasta_inputs(&inputs).unwrap();
263        // x should appear once, at its first position; y appears once (from dir).
264        let names: Vec<String> = out
265            .iter()
266            .map(|p| p.file_name().unwrap().to_str().unwrap().to_string())
267            .collect();
268        assert_eq!(names, vec!["x.fa", "y.fa"]);
269        assert_eq!(out[0], x);
270        assert!(out.contains(&y));
271    }
272
273    #[test]
274    fn glob_matching_nothing_is_error() {
275        let dir = tempdir().unwrap();
276        let pattern = dir.path().join("*.fa");
277        let inputs = FastaInputs {
278            paths: vec![pattern],
279            file_list: None,
280        };
281        assert!(expand_fasta_inputs(&inputs).is_err());
282    }
283
284    #[test]
285    fn nonexistent_explicit_path_is_error() {
286        let dir = tempdir().unwrap();
287        let missing = dir.path().join("nope.fa");
288        let inputs = FastaInputs {
289            paths: vec![missing],
290            file_list: None,
291        };
292        assert!(expand_fasta_inputs(&inputs).is_err());
293    }
294
295    #[test]
296    fn empty_result_is_error() {
297        let inputs = FastaInputs::default();
298        assert!(expand_fasta_inputs(&inputs).is_err());
299    }
300
301    #[test]
302    fn composition_explicit_then_fofn_with_glob() {
303        let dir = tempdir().unwrap();
304        let explicit = touch(dir.path(), "0explicit.fa");
305        // glob targets: created out of order
306        touch(dir.path(), "g_c.fa");
307        touch(dir.path(), "g_a.fa");
308        touch(dir.path(), "g_b.fa");
309
310        // fofn contains a glob line.
311        let fofn = dir.path().join("list.txt");
312        let mut f = File::create(&fofn).unwrap();
313        writeln!(f, "{}", dir.path().join("g_*.fa").display()).unwrap();
314        drop(f);
315
316        let inputs = FastaInputs {
317            paths: vec![explicit.clone()],
318            file_list: Some(fofn),
319        };
320        let out = expand_fasta_inputs(&inputs).unwrap();
321        let names: Vec<String> = out
322            .iter()
323            .map(|p| p.file_name().unwrap().to_str().unwrap().to_string())
324            .collect();
325        // 0explicit.fa would also match g_*.fa? No (prefix g_). But note list.txt
326        // itself is excluded by the glob (only g_*.fa). Explicit first, then
327        // glob matches sorted.
328        assert_eq!(names, vec!["0explicit.fa", "g_a.fa", "g_b.fa", "g_c.fa"]);
329    }
330}