file_operation/copy/async/
fn.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/// # Arguments
16///
17/// - `&str` - The source file path.
18/// - `&str` - The destination file path.
19///
20/// # Returns
21///
22/// - `Result<(), std::io::Error>` - Ok if the file was copied successfully, Err with error details otherwise.
23pub async fn async_copy_file(src: &str, dest: &str) -> Result<(), Error> {
24    copy(src, dest).await?;
25    Ok(())
26}
27
28/// Asynchronously copies all files from the source directory to the destination directory.
29///
30/// # Arguments
31///
32/// - `&str` - The source directory path.
33/// - `&str` - The destination directory path.
34///
35/// # Returns
36///
37/// - `Result<(), std::io::Error>` - Ok if all files were copied successfully, Err with error details otherwise.
38pub async fn async_copy_dir_files(src_dir: &str, dest_dir: &str) -> Result<(), Error> {
39    let src_path: &Path = Path::new(src_dir);
40    let dest_path: &Path = Path::new(dest_dir);
41    if dest_path.exists() {
42        if let Some(dest_path_str) = dest_path.to_str() {
43            if dest_path.is_file() {
44                delete_file(dest_path_str)?;
45            }
46            if dest_path.is_dir() {
47                delete_dir(dest_path_str)?;
48            }
49        }
50    }
51    create_dir_all(dest_path).await?;
52    let mut tasks: Vec<JoinHandle<Result<(), Error>>> = Vec::new();
53    let mut read_dir: ReadDir = read_dir(src_path).await?;
54    while let Some(entry) = read_dir.next_entry().await? {
55        let file_name: OsString = entry.file_name();
56        let src_file_path: PathBuf = entry.path();
57        let mut dest_file_path: PathBuf = PathBuf::from(dest_path);
58        dest_file_path.push(file_name);
59        if src_file_path.is_dir() {
60            let src_file_path_str: String = src_file_path.to_str().unwrap().to_string();
61            let dest_file_path_str: String = dest_file_path.to_str().unwrap().to_string();
62            tasks.push(spawn(async move {
63                async_copy_file(&src_file_path_str, &dest_file_path_str).await
64            }));
65        } else if src_file_path.is_file() {
66            let src_file_path_str: String = src_file_path.to_str().unwrap().to_string();
67            let dest_file_path_str: String = dest_file_path.to_str().unwrap().to_string();
68            tasks.push(spawn(async move {
69                async_copy_file(&src_file_path_str, &dest_file_path_str).await
70            }));
71        }
72    }
73    for task in tasks {
74        task.await??;
75    }
76    Ok(())
77}