unifier-cli 0.4.0

Filesystem postbox for inter-process communication via a Unix tree
Documentation
//! Small filesystem helpers for text files and atomic writes.

use std::fs;
use std::path::Path;

use uuid::Uuid;

use crate::error::Result;

pub fn read_text(path: &Path) -> Result<String> {
    Ok(fs::read_to_string(path)?.trim_end().to_string())
}

pub fn write_text(path: &Path, content: &str) -> Result<()> {
    if let Some(p) = path.parent() {
        fs::create_dir_all(p)?;
    }
    fs::write(path, content)?;
    Ok(())
}

/// Write to a temp file in the same directory, then rename for atomicity.
pub fn write_text_atomic(path: &Path, content: &str) -> Result<()> {
    if let Some(p) = path.parent() {
        fs::create_dir_all(p)?;
    }
    let dir = path
        .parent()
        .ok_or_else(|| crate::Error::msg("path has no parent"))?;
    let tmp = dir.join(format!(
        ".{}.tmp.{}",
        path.file_name().and_then(|s| s.to_str()).unwrap_or("file"),
        Uuid::new_v4()
    ));
    fs::write(&tmp, content)?;
    fs::rename(&tmp, path)?;
    Ok(())
}