1use std::path::{Path, PathBuf};
10
11use anyhow::{anyhow, Context};
12
13pub const FASTA_EXTENSIONS: &[&str] = &["fa", "fasta", "fna", "fa.gz", "fasta.gz", "fna.gz"];
16
17#[derive(Debug, Default, Clone)]
22pub struct FastaInputs {
23 pub paths: Vec<PathBuf>,
26 pub file_list: Option<PathBuf>,
28}
29
30fn 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
42fn looks_like_glob(s: &str) -> bool {
45 s.contains('*') || s.contains('?') || s.contains('[')
46}
47
48fn 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 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 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 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
92fn 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
108pub fn expand_fasta_inputs(inputs: &FastaInputs) -> Result<Vec<PathBuf>, anyhow::Error> {
138 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 let mut expanded: Vec<PathBuf> = Vec::new();
146 for entry in &working {
147 expand_entry(entry, &mut expanded)?;
148 }
149
150 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 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 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 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 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 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 touch(dir.path(), "g_c.fa");
307 touch(dir.path(), "g_a.fa");
308 touch(dir.path(), "g_b.fa");
309
310 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 assert_eq!(names, vec!["0explicit.fa", "g_a.fa", "g_b.fa", "g_c.fa"]);
329 }
330}