Line data Source code
1 : /// Extensions to `std::fs` types.
2 : use std::{fs, io, path::Path};
3 :
4 : use anyhow::Context;
5 :
6 : mod rename_noreplace;
7 : pub use rename_noreplace::rename_noreplace;
8 :
9 : pub trait PathExt {
10 : /// Returns an error if `self` is not a directory.
11 : fn is_empty_dir(&self) -> io::Result<bool>;
12 : }
13 :
14 : impl<P> PathExt for P
15 : where
16 : P: AsRef<Path>,
17 : {
18 3 : fn is_empty_dir(&self) -> io::Result<bool> {
19 3 : Ok(fs::read_dir(self)?.next().is_none())
20 3 : }
21 : }
22 :
23 3 : pub async fn is_directory_empty(path: impl AsRef<Path>) -> anyhow::Result<bool> {
24 3 : let mut dir = tokio::fs::read_dir(&path)
25 3 : .await
26 3 : .context(format!("read_dir({})", path.as_ref().display()))?;
27 1 : Ok(dir.next_entry().await?.is_none())
28 3 : }
29 :
30 3 : pub async fn list_dir(path: impl AsRef<Path>) -> anyhow::Result<Vec<String>> {
31 3 : let mut dir = tokio::fs::read_dir(&path)
32 3 : .await
33 3 : .context(format!("read_dir({})", path.as_ref().display()))?;
34 :
35 3 : let mut content = vec![];
36 6 : while let Some(next) = dir.next_entry().await? {
37 3 : let file_name = next.file_name();
38 3 : content.push(file_name.to_string_lossy().to_string());
39 3 : }
40 :
41 3 : Ok(content)
42 3 : }
43 :
44 53 : pub fn ignore_not_found(e: io::Error) -> io::Result<()> {
45 53 : if e.kind() == io::ErrorKind::NotFound {
46 53 : Ok(())
47 : } else {
48 0 : Err(e)
49 : }
50 53 : }
51 :
52 14 : pub fn ignore_absent_files<F>(fs_operation: F) -> io::Result<()>
53 14 : where
54 14 : F: Fn() -> io::Result<()>,
55 14 : {
56 14 : fs_operation().or_else(ignore_not_found)
57 14 : }
58 :
59 : #[cfg(test)]
60 : mod test {
61 : use super::ignore_absent_files;
62 : use crate::fs_ext::{is_directory_empty, list_dir};
63 :
64 : #[test]
65 1 : fn is_empty_dir() {
66 : use super::PathExt;
67 :
68 1 : let dir = camino_tempfile::tempdir().unwrap();
69 1 : let dir_path = dir.path();
70 1 :
71 1 : // test positive case
72 1 : assert!(
73 1 : dir_path.is_empty_dir().expect("test failure"),
74 0 : "new tempdir should be empty"
75 : );
76 :
77 : // invoke on a file to ensure it returns an error
78 1 : let file_path = dir_path.join("testfile");
79 1 : let f = std::fs::File::create(&file_path).unwrap();
80 1 : drop(f);
81 1 : assert!(file_path.is_empty_dir().is_err());
82 :
83 : // do it again on a path, we know to be nonexistent
84 1 : std::fs::remove_file(&file_path).unwrap();
85 1 : assert!(file_path.is_empty_dir().is_err());
86 1 : }
87 :
88 : #[tokio::test]
89 1 : async fn is_empty_dir_async() {
90 1 : let dir = camino_tempfile::tempdir().unwrap();
91 1 : let dir_path = dir.path();
92 1 :
93 1 : // test positive case
94 1 : assert!(
95 1 : is_directory_empty(dir_path).await.expect("test failure"),
96 1 : "new tempdir should be empty"
97 1 : );
98 1 :
99 1 : // invoke on a file to ensure it returns an error
100 1 : let file_path = dir_path.join("testfile");
101 1 : let f = std::fs::File::create(&file_path).unwrap();
102 1 : drop(f);
103 1 : assert!(is_directory_empty(&file_path).await.is_err());
104 1 :
105 1 : // do it again on a path, we know to be nonexistent
106 1 : std::fs::remove_file(&file_path).unwrap();
107 1 : assert!(is_directory_empty(file_path).await.is_err());
108 1 : }
109 :
110 : #[test]
111 1 : fn ignore_absent_files_works() {
112 1 : let dir = camino_tempfile::tempdir().unwrap();
113 1 :
114 1 : let file_path = dir.path().join("testfile");
115 1 :
116 1 : ignore_absent_files(|| std::fs::remove_file(&file_path)).expect("should execute normally");
117 1 :
118 1 : let f = std::fs::File::create(&file_path).unwrap();
119 1 : drop(f);
120 1 :
121 1 : ignore_absent_files(|| std::fs::remove_file(&file_path)).expect("should execute normally");
122 1 :
123 1 : assert!(!file_path.exists());
124 1 : }
125 :
126 : #[tokio::test]
127 1 : async fn list_dir_works() {
128 1 : let dir = camino_tempfile::tempdir().unwrap();
129 1 : let dir_path = dir.path();
130 1 :
131 1 : assert!(list_dir(dir_path).await.unwrap().is_empty());
132 1 :
133 1 : let file_path = dir_path.join("testfile");
134 1 : let _ = std::fs::File::create(&file_path).unwrap();
135 1 :
136 1 : assert_eq!(&list_dir(dir_path).await.unwrap(), &["testfile"]);
137 1 :
138 1 : let another_dir_path = dir_path.join("testdir");
139 1 : std::fs::create_dir(another_dir_path).unwrap();
140 1 :
141 1 : let expected = &["testdir", "testfile"];
142 1 : let mut actual = list_dir(dir_path).await.unwrap();
143 1 : actual.sort();
144 1 : assert_eq!(actual, expected);
145 1 : }
146 : }
|