duplicates/paths.rs
1//! Convenience functions for working with paths.
2
3use std::{
4 fs,
5 path::{Path, PathBuf},
6};
7
8/// Recursively finds all of the descendants of a file.
9///
10/// ## Example:
11/// ```no_run
12/// let paths = vec![
13/// Path::from("files/a.txt"),
14/// Path::from("files/b.txt"),
15/// Path::from("files/more_files/c.txt"),
16/// Path::from("files/more_files/d.txt"),
17/// Path::from("files/more_files/even_more_files/e.txt"),
18/// Path::from("files/more_files/even_more_files/f.txt")
19/// ];
20///
21/// let descendants = get_descendants(Path::from("files/more_files"));
22/// let expected = vec![
23/// Path::from("files/more_files/c.txt"),
24/// Path::from("files/more_files/d.txt"),
25/// Path::from("files/more_files/even_more_files/e.txt"),
26/// Path::from("files/more_files/even_more_files/f.txt")
27/// ];
28/// assert!(descendants == expected);
29///
30/// let descendants = get_descendants(Path::from("files"));
31/// assert!(descendants == paths);
32/// ```
33pub fn get_descendants(base_path: &Path) -> Vec<PathBuf> {
34 if base_path.is_dir() {
35 match fs::read_dir(base_path) {
36 Ok(dir_iter) => {
37 let mut result = Vec::new();
38 for dir_entry in dir_iter {
39 if let Ok(dir_entry) = dir_entry {
40 result.extend(get_descendants(&dir_entry.path()));
41 }
42 }
43 result
44 }
45 _ => Vec::new(),
46 }
47 } else {
48 vec![PathBuf::from(base_path)]
49 }
50}