file_operation/file/copy/
async.rs

1use crate::{delete_dir, delete_file};
2use std::{
3    ffi::OsString,
4    io::Error,
5    path::{Path, PathBuf},
6};
7use tokio::{
8    fs::{ReadDir, copy, create_dir_all, read_dir},
9    spawn,
10    task::JoinHandle,
11};
12
13/// Asynchronously copies a file from the source path to the destination path.
14///
15/// - `src`: The source file path.
16/// - `dest`: The destination file path.
17///
18/// - Returns: `Ok(())` if the file was copied successfully, or an `Err` with the error details.
19pub async fn async_copy_file(src: &str, dest: &str) -> Result<(), Error> {
20    copy(src, dest).await?;
21    Ok(())
22}
23
24/// Asynchronously copies all files from the source directory to the destination directory.
25///
26/// - `src_dir`: The source directory path.
27/// - `dest_dir`: The destination directory path.
28///
29/// - Returns: `Ok(())` if all files were copied successfully, or an `Err` with the error details.
30pub async fn async_copy_dir_files(src_dir: &str, dest_dir: &str) -> Result<(), Error> {
31    let src_path: &Path = Path::new(src_dir);
32    let dest_path: &Path = Path::new(dest_dir);
33    if dest_path.exists() {
34        if let Some(dest_path_str) = dest_path.to_str() {
35            if dest_path.is_file() {
36                delete_file(dest_path_str)?;
37            }
38            if dest_path.is_dir() {
39                delete_dir(dest_path_str)?;
40            }
41        }
42    }
43    create_dir_all(dest_path).await?;
44    let mut tasks: Vec<JoinHandle<Result<(), Error>>> = Vec::new();
45    let mut read_dir: ReadDir = read_dir(src_path).await?;
46    while let Some(entry) = read_dir.next_entry().await? {
47        let file_name: OsString = entry.file_name();
48        let src_file_path: PathBuf = entry.path();
49        let mut dest_file_path: PathBuf = PathBuf::from(dest_path);
50        dest_file_path.push(file_name);
51        if src_file_path.is_dir() {
52            let src_file_path_str: String = src_file_path.to_str().unwrap().to_string();
53            let dest_file_path_str: String = dest_file_path.to_str().unwrap().to_string();
54            tasks.push(spawn(async move {
55                async_copy_file(&src_file_path_str, &dest_file_path_str).await
56            }));
57        } else if src_file_path.is_file() {
58            let src_file_path_str: String = src_file_path.to_str().unwrap().to_string();
59            let dest_file_path_str: String = dest_file_path.to_str().unwrap().to_string();
60            tasks.push(spawn(async move {
61                async_copy_file(&src_file_path_str, &dest_file_path_str).await
62            }));
63        }
64    }
65    for task in tasks {
66        task.await??;
67    }
68    Ok(())
69}