file_operation/move/sync/
fn.rs

1use std::ffi::OsString;
2use std::path::Path;
3use std::path::PathBuf;
4
5/// Moves a file from the source path to the destination path.
6///
7/// # Arguments
8///
9/// - `&str` - The source file path.
10/// - `&str` - The destination file path.
11///
12/// # Returns
13///
14/// - `Result<(), std::io::Error>` - Ok if the file was moved successfully, Err with error details otherwise.
15pub fn move_file(src: &str, dest: &str) -> Result<(), std::io::Error> {
16    std::fs::rename(src, dest)?;
17    Ok(())
18}
19
20/// Moves a directory and all its contents to another location.
21///
22/// # Arguments
23///
24/// - `&str` - The source directory path.
25/// - `&str` - The destination directory path.
26///
27/// # Returns
28///
29/// - `Result<(), std::io::Error>` - Ok if the directory was moved successfully, Err with error details otherwise.
30pub fn move_dir(src_dir: &str, dest_dir: &str) -> Result<(), std::io::Error> {
31    let src_path: &Path = Path::new(src_dir);
32    let dest_path: &Path = Path::new(dest_dir);
33    if dest_path.exists() {
34        std::fs::remove_dir_all(dest_path)?;
35    }
36    std::fs::create_dir_all(dest_path)?;
37    for entry in std::fs::read_dir(src_path)? {
38        let entry: std::fs::DirEntry = entry?;
39        let file_name: OsString = entry.file_name();
40        let src_file_path: PathBuf = entry.path();
41        let mut dest_file_path: PathBuf = PathBuf::from(dest_path);
42        dest_file_path.push(file_name);
43        if src_file_path.is_dir() {
44            move_dir(
45                src_file_path.to_str().unwrap(),
46                dest_file_path.to_str().unwrap(),
47            )?;
48        } else if src_file_path.is_file() {
49            std::fs::rename(&src_file_path, &dest_file_path)?;
50        }
51    }
52    std::fs::remove_dir(src_path)?;
53    Ok(())
54}