file_io/list.rs
1use std::path::{Path, PathBuf};
2
3/// Lists the contents of a folder at the specified path.
4///
5/// # Arguments
6///
7/// * `path` - The path to the folder (can be a `&str`, [`String`], [`Path`], or [`PathBuf`]).
8///
9/// # Returns
10///
11/// Paths of the files and folders in the specified directory (in alphabetical order). Note that
12/// folders are included in the list, but their contents are not recursively listed.
13///
14/// # Panics
15///
16/// If the provided path is not a folder or if an error occurs while reading the folder.
17///
18/// # Examples
19///
20/// ## Using a string literal
21///
22/// ```
23/// use file_io::list_folder_contents;
24/// use std::path::PathBuf;
25///
26/// let contents: Vec<PathBuf> = list_folder_contents(".vscode");
27///
28/// assert_eq!(
29/// contents,
30/// vec![PathBuf::from(".vscode/extensions.json"), PathBuf::from(".vscode/settings.json")]
31/// );
32/// ```
33///
34/// ## Using a `Path` reference
35///
36/// ```
37/// use file_io::list_folder_contents;
38/// use std::path::{Path, PathBuf};
39///
40/// let contents: Vec<PathBuf> = list_folder_contents(Path::new(".vscode"));
41///
42/// assert_eq!(
43/// contents,
44/// vec![PathBuf::from(".vscode/extensions.json"), PathBuf::from(".vscode/settings.json")]
45/// );
46/// ```
47pub fn list_folder_contents<P: AsRef<Path>>(path: P) -> Vec<PathBuf> {
48 // Convert the input path to a Path reference.
49 let path = path.as_ref();
50
51 // Ensure the path is a folder.
52 if !path.is_dir() {
53 panic!("The provided path is not a folder: {path:?}");
54 }
55
56 // Read the folder entries into a vector.
57 let mut entries = match std::fs::read_dir(path) {
58 Ok(entries) => entries
59 .filter_map(Result::ok)
60 .map(|e| e.path())
61 .collect::<Vec<PathBuf>>(),
62 Err(_) => panic!("Failed to read directory: {path:?}"),
63 };
64
65 // Sort the entries alphabetically.
66 entries.sort();
67
68 entries
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74 use crate::save::save_string_to_file;
75 use crate::test_utils::get_temp_dir_path;
76 use tempfile::tempdir;
77
78 #[test]
79 fn test_list_folder_contents() {
80 // Create a temporary directory to work in.
81 let temp_dir = tempdir().unwrap();
82
83 // Get the path to the temporary directory.
84 let temp_dir_path = get_temp_dir_path(&temp_dir);
85
86 // Create some test files and folders.
87 save_string_to_file("Content 1", temp_dir_path.join("file1.txt"));
88 save_string_to_file("Content 2", temp_dir_path.join("file2.txt"));
89 save_string_to_file("Content 3", temp_dir_path.join("subfolder/file3.txt"));
90
91 // List the contents of the temporary directory.
92 let contents = list_folder_contents(&temp_dir_path);
93
94 // Check that the contents are as expected.
95 assert_eq!(
96 contents,
97 vec![
98 temp_dir_path.join("file1.txt"),
99 temp_dir_path.join("file2.txt"),
100 temp_dir_path.join("subfolder")
101 ]
102 );
103 }
104}