file_operation/file/move/
async.rs

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