fs.rs (1256B)
1 use std::{ 2 fs, 3 path::{Path, PathBuf}, 4 }; 5 6 pub fn workspace_root() -> Result<PathBuf, String> { 7 let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); 8 manifest_dir 9 .parent() 10 .and_then(Path::parent) 11 .map(Path::to_path_buf) 12 .ok_or_else(|| { 13 format!( 14 "cannot resolve workspace root from {}", 15 manifest_dir.display() 16 ) 17 }) 18 } 19 20 #[allow(dead_code)] 21 pub fn write_if_changed(path: &Path, contents: &str) -> Result<bool, String> { 22 if let Ok(existing) = fs::read_to_string(path) { 23 if existing == contents { 24 return Ok(false); 25 } 26 } 27 if let Some(parent) = path.parent() { 28 fs::create_dir_all(parent) 29 .map_err(|error| format!("failed to create {}: {error}", parent.display()))?; 30 } 31 fs::write(path, contents) 32 .map_err(|error| format!("failed to write {}: {error}", path.display()))?; 33 Ok(true) 34 } 35 36 #[cfg(test)] 37 mod tests { 38 use super::workspace_root; 39 40 #[test] 41 fn resolves_workspace_root() { 42 let root = workspace_root().expect("workspace root resolves"); 43 assert!(root.join("Cargo.toml").is_file()); 44 assert!(root.join("packages").is_dir()); 45 } 46 }