1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::io;
use std::path::{Path, PathBuf};
use tokio::fs;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LocalDirEntry {
    pub path: PathBuf,
    pub is_file: bool,
    pub is_dir: bool,
    pub is_symlink: bool,
}

impl LocalDirEntry {
    pub fn path_to_string(&self) -> String {
        self.path.to_string_lossy().to_string()
    }
}

pub async fn entries(path: impl AsRef<Path>) -> io::Result<Vec<LocalDirEntry>> {
    let mut entries = Vec::new();
    let mut dir_stream = fs::read_dir(path).await?;
    while let Some(entry) = dir_stream.next_entry().await? {
        let file_type = entry.file_type().await?;
        entries.push(LocalDirEntry {
            path: entry.path(),
            is_file: file_type.is_file(),
            is_dir: file_type.is_dir(),
            is_symlink: file_type.is_symlink(),
        });
    }
    Ok(entries)
}

pub async fn rename(
    from: impl AsRef<Path>,
    to: impl AsRef<Path>,
) -> io::Result<()> {
    let metadata = fs::metadata(from.as_ref()).await?;

    if metadata.is_dir() {
        fs::rename(from, to).await
    } else {
        Err(io::Error::new(io::ErrorKind::Other, "Not a directory"))
    }
}

pub async fn create(
    path: impl AsRef<Path>,
    create_components: bool,
) -> io::Result<()> {
    if create_components {
        fs::create_dir_all(path).await
    } else {
        fs::create_dir(path).await
    }
}

pub async fn remove(path: impl AsRef<Path>, non_empty: bool) -> io::Result<()> {
    if non_empty {
        fs::remove_dir_all(path).await
    } else {
        fs::remove_dir(path).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn entries_should_yield_error_if_not_a_directory() {
        let result = {
            let file = tempfile::NamedTempFile::new().unwrap();
            entries(file.as_ref()).await
        };

        match result {
            Err(x) if x.kind() == io::ErrorKind::Other => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[tokio::test]
    async fn entries_should_return_immediate_entries_within_dir() {
        let (dir_path, result) = {
            let dir = tempfile::tempdir().unwrap();

            fs::File::create(dir.as_ref().join("test-file"))
                .await
                .expect("Failed to create file");

            fs::create_dir(dir.as_ref().join("test-dir"))
                .await
                .expect("Failed to create dir");

            let result = entries(dir.as_ref()).await;

            (dir.into_path(), result)
        };

        match result {
            Ok(entries) => {
                assert_eq!(entries.len(), 2, "Unexpected number of entries");

                assert!(
                    entries.contains(&LocalDirEntry {
                        path: dir_path.join("test-file"),
                        is_file: true,
                        is_dir: false,
                        is_symlink: false,
                    }),
                    "No test-file found"
                );

                assert!(
                    entries.contains(&LocalDirEntry {
                        path: dir_path.join("test-dir"),
                        is_file: false,
                        is_dir: true,
                        is_symlink: false,
                    }),
                    "No test-dir found"
                );
            }
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[tokio::test]
    async fn rename_should_yield_error_if_not_a_directory() {
        let result = {
            let from_file = tempfile::NamedTempFile::new().unwrap();
            let from = from_file.as_ref();
            let to_dir = tempfile::tempdir().unwrap();
            let to = to_dir.as_ref();

            rename(from, to).await
        };

        match result {
            Err(x) if x.kind() == io::ErrorKind::Other => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[tokio::test]
    async fn rename_should_return_success_if_able_to_rename_directory() {
        let result = {
            let from_dir = tempfile::tempdir().unwrap();
            let from = from_dir.as_ref();
            let to_dir = tempfile::tempdir().unwrap();
            let to = to_dir.as_ref();

            rename(from, to).await
        };

        match result {
            Ok(_) => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[tokio::test]
    async fn create_should_return_success_if_able_to_make_an_empty_directory() {
        let result = {
            let parent_dir = tempfile::tempdir().unwrap();

            create(parent_dir.as_ref().join("test-dir"), false).await
        };

        assert!(result.is_ok(), "Failed unexpectedly: {:?}", result);

        let result = {
            let parent_dir = tempfile::tempdir().unwrap();

            create(parent_dir.as_ref().join("test-dir"), true).await
        };

        assert!(result.is_ok(), "Failed unexpectedly: {:?}", result);
    }

    #[tokio::test]
    async fn create_should_yield_error_if_some_components_dont_exist_and_flag_not_set(
    ) {
        let result = {
            let parent_dir = tempfile::tempdir().unwrap();
            let new_dir = parent_dir.as_ref().join(
                ["does", "not", "exist"]
                    .iter()
                    .collect::<PathBuf>()
                    .as_path(),
            );

            create(new_dir, false).await
        };

        assert!(result.is_err(), "Unexpectedly succeeded: {:?}", result);
    }

    #[tokio::test]
    async fn create_should_return_success_if_able_to_make_nested_empty_directory(
    ) {
        let parent_dir = tempfile::tempdir().unwrap();

        create(parent_dir.as_ref().join("test-dir"), false)
            .await
            .expect("Failed to create directory");

        create(parent_dir.as_ref().join("test-dir"), true)
            .await
            .expect("Failed to create directory");
    }

    #[tokio::test]
    async fn remove_should_yield_error_if_not_a_directory() {
        let result = {
            let file = tempfile::NamedTempFile::new().unwrap();
            remove(file.as_ref(), false).await
        };

        match result {
            Err(x) if x.kind() == io::ErrorKind::Other => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[tokio::test]
    async fn remove_should_return_success_if_able_to_remove_empty_directory() {
        // Remove an empty directory with non-empty flag not set
        let result = {
            let dir = tempfile::tempdir().unwrap();
            remove(dir.as_ref(), false).await
        };

        match result {
            Ok(_) => (),
            x => panic!("Unexpected result: {:?}", x),
        }

        // Remove an empty directory with non-empty flag set
        let result = {
            let dir = tempfile::tempdir().unwrap();
            remove(dir.as_ref(), true).await
        };

        match result {
            Ok(_) => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[tokio::test]
    async fn remove_should_yield_error_if_removing_nonempty_directory_and_flag_not_set(
    ) {
        let result = {
            let dir = tempfile::tempdir().unwrap();

            fs::File::create(dir.as_ref().join("test-file"))
                .await
                .expect("Failed to create file");

            remove(dir.as_ref(), false).await
        };

        match result {
            Err(x) if x.kind() == io::ErrorKind::Other => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }

    #[tokio::test]
    async fn remove_should_return_success_if_able_to_remove_nonempty_directory_if_flag_set(
    ) {
        let result = {
            let dir = tempfile::tempdir().unwrap();

            fs::File::create(dir.as_ref().join("test-file"))
                .await
                .expect("Failed to create file");

            remove(dir.as_ref(), true).await
        };

        match result {
            Ok(_) => (),
            x => panic!("Unexpected result: {:?}", x),
        }
    }
}