use crate::escape::encode_escapes;
use crate::types::{Entry, Fstab};
use std::fmt;
use std::io;
use std::path::Path;
impl fmt::Display for Fstab {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(ref intro) = self.intro_comment {
f.write_str(intro)?;
}
for entry in &self.entries {
if let Some(ref comment) = entry.comment {
f.write_str(comment)?;
}
write!(f, "{entry}")?;
}
if let Some(ref trailing) = self.trailing_comment {
f.write_str(trailing)?;
}
Ok(())
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} {} {} {}",
encode_escapes(&self.spec.to_string()),
encode_escapes(&self.file.to_string()),
self.vfstype,
self.options,
)?;
if self.freq != 0 || self.passno != 0 {
write!(f, " {} {}", self.freq, self.passno)?;
}
writeln!(f)?;
Ok(())
}
}
impl Fstab {
pub fn write_to(&self, path: impl AsRef<Path>) -> Result<(), io::Error> {
let content = self.to_string();
std::fs::write(path, content)
}
pub fn write_atomic(&self, path: impl AsRef<Path>) -> Result<(), io::Error> {
let path = path.as_ref();
let parent = path.parent().unwrap_or(Path::new("."));
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
let content = self.to_string();
io::Write::write_all(&mut tmp, content.as_bytes())?;
tmp.as_file_mut().sync_all()?;
tmp.persist(path).map_err(|e| e.error)?;
Ok(())
}
}