image_optimizer/file_ops/backup_manager.rs
1use anyhow::Result;
2use std::ffi::OsStr;
3use std::path::Path;
4
5/// Creates a backup file by copying the original with a .bak extension.
6///
7/// This function creates a safety backup of the original file before optimization
8/// by copying it to a new file with the same name but with `.bak` appended to the extension.
9/// For example, `image.jpg` becomes `image.jpg.bak`.
10///
11/// # Arguments
12///
13/// * `file_path` - Path to the file to backup
14///
15/// # Returns
16///
17/// Returns `Ok(())` on successful backup creation.
18///
19/// # Errors
20///
21/// Returns an error if the file copy operation fails due to:
22/// - Insufficient disk space
23/// - Permission issues
24/// - I/O errors during file copying
25///
26/// # Examples
27///
28/// ```rust
29/// use std::path::Path;
30/// use image_optimizer::file_ops::create_backup;
31///
32/// # fn example() -> anyhow::Result<()> {
33/// let file_path = Path::new("image.jpg");
34/// create_backup(file_path)?; // Creates image.jpg.bak
35/// # Ok(())
36/// # }
37/// ```
38pub fn create_backup(file_path: &Path) -> Result<()> {
39 let backup_path = file_path.with_extension(format!(
40 "{}.bak",
41 file_path.extension().and_then(OsStr::to_str).unwrap_or("")
42 ));
43 std::fs::copy(file_path, backup_path)?;
44 Ok(())
45}