file_operation/copy/sync/
fn.rs

1use crate::*;
2
3/// Copies a file from the source path to the destination path.
4///
5/// # Arguments
6///
7/// - `&str` - The source file path.
8/// - `&str` - The destination file path.
9///
10/// # Returns
11///
12/// - `Result<(), std::io::Error>` - Ok if the file was copied successfully, Err with error details otherwise.
13pub fn copy_file(src: &str, dest: &str) -> Result<(), Error> {
14    std::fs::copy(src, dest)?;
15    Ok(())
16}
17
18/// Copies all files from the source directory to the destination directory.
19///
20/// # Arguments
21///
22/// - `&str` - The source directory path.
23/// - `&str` - The destination directory path.
24///
25/// # Returns
26///
27/// - `Result<(), std::io::Error>` - Ok if all files were copied successfully, Err with error details otherwise.
28pub fn copy_dir_files(src_dir: &str, dest_dir: &str) -> Result<(), Error> {
29    let src_path: &Path = Path::new(src_dir);
30    let dest_path: &Path = Path::new(dest_dir);
31    if dest_path.exists()
32        && let Some(dest_path_str) = dest_path.to_str()
33    {
34        if dest_path.is_file() {
35            delete_file(dest_path_str)?;
36        }
37        if dest_path.is_dir() {
38            delete_dir(dest_path_str)?;
39        }
40    }
41    std::fs::create_dir_all(dest_path)?;
42    for entry in std::fs::read_dir(src_path)? {
43        let entry: DirEntry = entry?;
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            copy_dir_files(
50                src_file_path.to_str().unwrap(),
51                dest_file_path.to_str().unwrap(),
52            )?;
53        } else if src_file_path.is_file() {
54            std::fs::copy(&src_file_path, &dest_file_path)?;
55        }
56    }
57    Ok(())
58}