atomic_write

Function atomic_write 

Source
pub fn atomic_write(path: &Path, content: &[u8]) -> Result<()>
Expand description

Atomically writes bytes to a file using a write-then-rename strategy.

This function ensures atomic writes by:

  1. Writing content to a temporary file (.tmp extension)
  2. Syncing the temporary file to disk
  3. Atomically renaming the temporary file to the target path

This approach prevents data corruption from interrupted writes and ensures readers never see partially written files.

§Arguments

  • path - The target file path
  • content - The raw bytes to write

§Returns

  • Ok(()) if the file was written atomically
  • Err if any step of the atomic write fails

§Examples

use agpm_cli::utils::fs::atomic_write;
use std::path::Path;

let config_bytes = b"[sources]\ncommunity = \"https://example.com\"";
atomic_write(Path::new("agpm.toml"), config_bytes)?;

§Platform Notes

  • Windows: Handles long paths and provides specific error messages
  • Unix: Preserves file permissions on existing files
  • All platforms: Creates parent directories if they don’t exist

§Guarantees

  • Atomicity: File contents are never in a partial state
  • Durability: Content is synced to disk before rename
  • Safety: Parent directories are created automatically