fs.rs (1152B)
1 use std::{fs, path::Path}; 2 3 use crate::build_control::Mode; 4 5 pub fn write_if_changed(path: &Path, contents: &str) -> Result<bool, String> { 6 if let Ok(existing) = fs::read_to_string(path) 7 && existing == contents 8 { 9 return Ok(false); 10 } 11 crate::build_control::atomic_write(path, contents.as_bytes())?; 12 Ok(true) 13 } 14 15 pub fn write_or_check(path: &Path, contents: &str, mode: Mode) -> Result<(), String> { 16 match mode { 17 Mode::Write => write_if_changed(path, contents).map(|_| ()), 18 Mode::Check => { 19 let current = fs::read_to_string(path) 20 .map_err(|error| format!("failed to read {}: {error}", path.display()))?; 21 if current == contents { 22 Ok(()) 23 } else { 24 Err(format!("stale generated SDK output: {}", path.display())) 25 } 26 } 27 } 28 } 29 30 pub fn write_bytes_if_changed(path: &Path, contents: &[u8]) -> Result<bool, String> { 31 if let Ok(existing) = fs::read(path) 32 && existing == contents 33 { 34 return Ok(false); 35 } 36 crate::build_control::atomic_write_bytes(path, contents)?; 37 Ok(true) 38 }