use crate::error::{Error, Result};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
pub fn read_toml<T: DeserializeOwned>(path: &Path, label: &str) -> Result<T> {
let content = fs::read_to_string(path)
.map_err(|e| Error::State(format!("Failed to read {label}: {e}")))?;
toml::from_str(&content).map_err(|e| Error::State(format!("Failed to parse {label}: {e}")))
}
pub fn write_toml_atomic<T: Serialize>(path: &Path, value: &T, label: &str) -> Result<()> {
let content = toml::to_string(value)
.map_err(|e| Error::State(format!("Failed to serialize {label}: {e}")))?;
write_atomic(path, &content, label)
}
pub fn parent_or_dot(path: &Path) -> &Path {
path.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."))
}
pub fn write_atomic(path: &Path, content: &str, label: &str) -> Result<()> {
let dir = parent_or_dot(path);
let mut tmp = tempfile::Builder::new()
.prefix(".blackship-")
.suffix(".tmp")
.permissions(fs::Permissions::from_mode(0o644))
.tempfile_in(dir)
.map_err(|e| Error::State(format!("Failed to create {label} temp file: {e}")))?;
tmp.write_all(content.as_bytes())
.map_err(|e| Error::State(format!("Failed to write {label}: {e}")))?;
tmp.persist(path)
.map_err(|e| Error::State(format!("Failed to finalize {label}: {}", e.error)))?;
Ok(())
}
#[cfg(test)]
mod tests;