file_operation/move/async/
fn.rs

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