Atomic write via tempfile + rename in the same directory. `notify-debouncer-full` coalesces the tmp+rename pair into a single event. `tmp_prefix` is included in the dotfile name so multiple writers in the same directory don't clobber each other's tmp files (e.g. ".trace.json.tmp" vs ".state.json.tmp").
(path: &Path, tmp_prefix: &str, bytes: &[u8])
| 9 | /// directory don't clobber each other's tmp files (e.g. ".trace.json.tmp" vs |
| 10 | /// ".state.json.tmp"). |
| 11 | pub fn atomic_write_bytes(path: &Path, tmp_prefix: &str, bytes: &[u8]) -> Result<()> { |
| 12 | let dir = path |
| 13 | .parent() |
| 14 | .ok_or_else(|| TraceError::Io(format!("path has no parent: {}", path.display())))?; |
| 15 | std::fs::create_dir_all(dir)?; |
| 16 | let file_name = path |
| 17 | .file_name() |
| 18 | .and_then(|s| s.to_str()) |
| 19 | .unwrap_or("output"); |
| 20 | let tmp = dir.join(format!(".{}.{}.tmp", tmp_prefix, file_name)); |
| 21 | { |
| 22 | let mut f = std::fs::File::create(&tmp)?; |
| 23 | f.write_all(bytes)?; |
| 24 | f.sync_all()?; |
| 25 | } |
| 26 | std::fs::rename(&tmp, path)?; |
| 27 | Ok(()) |
| 28 | } |
| 29 | |
| 30 | pub fn atomic_write_json<T: serde::Serialize>(path: &Path, tmp_prefix: &str, value: &T) -> Result<()> { |
| 31 | let bytes = serde_json::to_vec_pretty(value)?; |
no test coverage detected
searching dependent graphs…