file_operation/move/async/
fn.rs

1use crate::*;
2
3/// Moves a file from the source path to the destination path asynchronously.
4///
5/// # Arguments
6///
7/// - `&str` - The source file path.
8/// - `&str` - The destination file path.
9///
10/// # Returns
11///
12/// - `Result<(), std::io::Error>` - Ok if the file was moved successfully, Err with error details otherwise.
13pub async fn async_move_file(src: &str, dest: &str) -> Result<(), Error> {
14    tokio::fs::rename(src, dest).await?;
15    Ok(())
16}
17
18/// Moves a directory and all its contents to another location asynchronously.
19///
20/// # Arguments
21///
22/// - `&str` - The source directory path.
23/// - `&str` - The destination directory path.
24///
25/// # Returns
26///
27/// - `Pin<Box<dyn Future<Output = Result<(), std::io::Error>> + 'a>>` - A pinned boxed future that resolves to the move operation result.
28pub fn async_move_dir<'a>(
29    src_dir: &'a str,
30    dest_dir: &'a str,
31) -> Pin<Box<dyn Future<Output = Result<(), Error>> + 'a>> {
32    Box::pin(async move {
33        let src_path: &Path = Path::new(src_dir);
34        let dest_path: &Path = Path::new(dest_dir);
35        if dest_path.exists() {
36            tokio::fs::remove_dir_all(dest_path).await?;
37        }
38        tokio::fs::create_dir_all(dest_path).await?;
39        let mut entries: ReadDir = tokio::fs::read_dir(src_path).await?;
40        while let Some(entry) = entries.next_entry().await? {
41            let file_name: OsString = entry.file_name();
42            let src_file_path: PathBuf = entry.path();
43            let mut dest_file_path: PathBuf = PathBuf::from(dest_path);
44            dest_file_path.push(file_name);
45            if src_file_path.is_dir() {
46                async_move_dir(
47                    src_file_path.to_str().unwrap(),
48                    dest_file_path.to_str().unwrap(),
49                )
50                .await?;
51            } else if src_file_path.is_file() {
52                tokio::fs::rename(&src_file_path, &dest_file_path).await?;
53            }
54        }
55        tokio::fs::remove_dir(src_path).await?;
56        Ok(())
57    })
58}