|
| 1 | +use fd_lock::RwLock; |
| 2 | +use miette::{miette, IntoDiagnostic, Result}; |
| 3 | +use std::fs; |
| 4 | +use std::io::Write; |
| 5 | +use std::path::Path; |
| 6 | + |
| 7 | +/// Safely write a file with locking, avoiding writing if the content hasn't changed. |
| 8 | +/// |
| 9 | +/// Returns Ok(true) if the file was written, Ok(false) if no write was needed. |
| 10 | +pub fn write_file_with_lock<P: AsRef<Path>>(path: P, content: &str) -> Result<bool> { |
| 11 | + let path = path.as_ref(); |
| 12 | + |
| 13 | + // Create parent directories if they don't exist |
| 14 | + if let Some(parent) = path.parent() { |
| 15 | + if !parent.exists() { |
| 16 | + fs::create_dir_all(parent) |
| 17 | + .into_diagnostic() |
| 18 | + .map_err(|e| miette!("Failed to create directory {}: {}", parent.display(), e))?; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + // Open or create the file with locking |
| 23 | + let file = fs::OpenOptions::new() |
| 24 | + .read(true) |
| 25 | + .write(true) |
| 26 | + .create(true) |
| 27 | + .open(path) |
| 28 | + .into_diagnostic() |
| 29 | + .map_err(|e| miette!("Failed to open file {}: {}", path.display(), e))?; |
| 30 | + |
| 31 | + // Acquire an exclusive lock on the file |
| 32 | + let mut file_lock = RwLock::new(file); |
| 33 | + let mut file_handle = file_lock |
| 34 | + .write() |
| 35 | + .into_diagnostic() |
| 36 | + .map_err(|e| miette!("Failed to lock file {}: {}", path.display(), e))?; |
| 37 | + |
| 38 | + // Read existing content |
| 39 | + let existing_content = fs::read_to_string(path).unwrap_or_default(); |
| 40 | + |
| 41 | + // Compare and write only if different |
| 42 | + if content != existing_content { |
| 43 | + file_handle |
| 44 | + .set_len(0) |
| 45 | + .into_diagnostic() |
| 46 | + .map_err(|e| miette!("Failed to truncate file {}: {}", path.display(), e))?; |
| 47 | + |
| 48 | + file_handle |
| 49 | + .write_all(content.as_bytes()) |
| 50 | + .into_diagnostic() |
| 51 | + .map_err(|e| miette!("Failed to write to file {}: {}", path.display(), e))?; |
| 52 | + |
| 53 | + // File was written |
| 54 | + Ok(true) |
| 55 | + } else { |
| 56 | + // No write needed |
| 57 | + Ok(false) |
| 58 | + } |
| 59 | +} |
0 commit comments