file_operation/copy/sync/
fn.rs

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