sunbeam_build/files_in_dir.rs
1use std::path::{Path, PathBuf};
2
3/// Get all of the files in a directory or any of its subdirectories that end with a given pattern.
4///
5/// We sort the files before returning them in order to ensure consistency for operations that
6/// use the files to generate other files.
7///
8/// # Examples
9///
10/// ```no_run
11/// # use std::path::PathBuf;
12/// # use sunbeam_build::files_in_dir_recursive_ending_with;
13///
14/// // Get all of the files that end in `_view.rs`, such as
15/// // `login_form_view.rs`.
16/// let files = files_in_dir_recursive_ending_with(
17/// PathBuf::from("/path/to/dir"),
18/// "_view.rs"
19/// );
20/// ```
21pub fn files_in_dir_recursive_ending_with<P: AsRef<Path>>(
22 source_dir: P,
23 ending_with: &str,
24) -> Vec<PathBuf> {
25 let mut files_with_ending = vec![];
26
27 for entry in std::fs::read_dir(source_dir).unwrap() {
28 let entry = entry.unwrap();
29 let path = entry.path();
30
31 if path.is_dir() {
32 files_with_ending.extend(files_in_dir_recursive_ending_with(&path, ending_with));
33 } else {
34 if path.to_str().unwrap().ends_with(ending_with) {
35 files_with_ending.push(path)
36 }
37 }
38 }
39
40 files_with_ending
41}