Writes content to a file, creating parent directories if needed.
(path: &Path, content: &str)
| 64 | |
| 65 | /// Writes content to a file, creating parent directories if needed. |
| 66 | pub async fn write_file(path: &Path, content: &str) -> Result<()> { |
| 67 | if let Some(parent) = path.parent() { |
| 68 | create_dir(parent).await?; |
| 69 | } |
| 70 | |
| 71 | // Generate unique temporary filename to avoid collisions |
| 72 | let temp_path = { |
| 73 | let mut temp = path.to_path_buf(); |
| 74 | let timestamp = std::time::SystemTime::now() |
| 75 | .duration_since(std::time::UNIX_EPOCH) |
| 76 | .unwrap_or_default() |
| 77 | .as_nanos(); |
| 78 | let pid = std::process::id(); |
| 79 | temp.set_file_name(format!( |
| 80 | ".{}.{}.{}.tmp", |
| 81 | path.file_name().unwrap_or_default().to_string_lossy(), |
| 82 | pid, |
| 83 | timestamp |
| 84 | )); |
| 85 | temp |
| 86 | }; |
| 87 | |
| 88 | tokio::fs::write(&temp_path, content).await?; |
| 89 | |
| 90 | match tokio::fs::rename(&temp_path, path).await { |
| 91 | Ok(()) => Ok(()), |
| 92 | Err(e) => { |
| 93 | let _ = tokio::fs::remove_file(&temp_path).await; |
| 94 | Err(e.into()) |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// Reads the contents of a file as a string. |
| 100 | pub async fn read_file(path: &Path) -> Result<String> { |