file_operation/copy/async/
fn.rs1use 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
13pub async fn async_copy_file(src: &str, dest: &str) -> Result<(), Error> {
24 copy(src, dest).await?;
25 Ok(())
26}
27
28pub 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}