1use crate::error::Error;
4use std::path::{Path, PathBuf};
5use tokio::fs::{create_dir_all, read_dir, remove_dir_all, remove_file, try_exists, ReadDir};
6
7pub async fn delete_file(path: &Path) -> Result<(), Error> {
8 if try_exists(path).await? {
9 remove_file(path).await?;
10 }
11
12 Ok(())
13}
14
15pub async fn delete_directory(path: &Path) -> Result<(), Error> {
16 if try_exists(path).await? {
17 remove_dir_all(path).await?;
18 }
19
20 Ok(())
21}
22
23pub async fn create_directory(path: &Path) -> Result<(), Error> {
24 if !try_exists(path).await? {
25 create_dir_all(path).await?;
26 }
27
28 Ok(())
29}
30
31pub async fn delete_temp_files(path: &Path) -> Result<(), Error> {
32 let mut directory_iter = DirectoryIter::new(path).await?;
33 while let Some((name, path)) = directory_iter.next().await? {
34 if name.starts_with("temp") {
35 delete_file(&path).await?;
36 }
37 }
38
39 Ok(())
40}
41
42pub struct DirectoryIter {
43 read_dir: ReadDir,
44}
45
46impl DirectoryIter {
47 pub async fn new(path: &Path) -> Result<Self, Error> {
48 let read_dir = read_dir(path).await?;
49
50 Ok(Self { read_dir })
51 }
52
53 pub async fn next(&mut self) -> Result<Option<(String, PathBuf)>, Error> {
54 if let Some(entry) = self.read_dir.next_entry().await? {
55 return Ok(entry
56 .file_name()
57 .to_str()
58 .map(|s| (s.to_string(), entry.path())));
59 }
60
61 Ok(None)
62 }
63}