file_operation/file/copy/
sync.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/// - `src`: The source file path.
12/// - `dest`: The destination file path.
13///
14/// - Returns: `Ok(())` if the file was copied successfully, or an `Err` with the error details.
15pub fn copy_file(src: &str, dest: &str) -> Result<(), Error> {
16    copy(src, dest)?;
17    Ok(())
18}
19
20/// Copies all files from the source directory to the destination directory.
21///
22/// - `src_dir`: The source directory path.
23/// - `dest_dir`: The destination directory path.
24///
25/// - Returns: `Ok(())` if all files were copied successfully, or an `Err` with the error details.
26/// Copies a directory and all its contents to another location.
27///
28/// - `src_dir`: The source directory path.
29/// - `dest_dir`: The destination directory path.
30///
31/// - Returns: `Ok(())` if the directory and its contents were copied successfully, or an `Err` with the error details.
32pub fn copy_dir_files(src_dir: &str, dest_dir: &str) -> Result<(), Error> {
33    let src_path: &Path = Path::new(src_dir);
34    let dest_path: &Path = Path::new(dest_dir);
35    if dest_path.exists() {
36        if let Some(dest_path_str) = dest_path.to_str() {
37            if dest_path.is_file() {
38                delete_file(dest_path_str)?;
39            }
40            if dest_path.is_dir() {
41                delete_dir(dest_path_str)?;
42            }
43        }
44    }
45    create_dir_all(dest_path)?;
46    for entry in read_dir(src_path)? {
47        let entry: DirEntry = entry?;
48        let file_name: OsString = entry.file_name();
49        let src_file_path: PathBuf = entry.path();
50        let mut dest_file_path: PathBuf = PathBuf::from(dest_path);
51        dest_file_path.push(file_name);
52        if src_file_path.is_dir() {
53            copy_dir_files(
54                src_file_path.to_str().unwrap(),
55                dest_file_path.to_str().unwrap(),
56            )?;
57        } else if src_file_path.is_file() {
58            copy(&src_file_path, &dest_file_path)?;
59        }
60    }
61    Ok(())
62}