use std::{
collections::BTreeMap,
io,
path::{Path, PathBuf},
};
use rho_protocol::{ConfigRevision, ErrorCode, RpcError, SettingEntry, SettingKey};
use sha2::{Digest, Sha256};
use crate::{
config::ConfigDocument,
config_writer::edit_lock::{acquire_edit_lock, EditFileLock},
daemon::FileIdentity,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Stat {
Missing,
File(FileIdentity),
Unreadable,
}
impl Stat {
pub(super) fn of(path: &Path) -> Self {
match std::fs::metadata(path) {
Ok(metadata) => Self::File(FileIdentity::of(&metadata)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Self::Missing,
Err(_) => Self::Unreadable,
}
}
}
#[derive(Debug)]
pub(super) enum ReadError {
Io(io::Error),
Parse(String),
}
impl ReadError {
pub(super) fn message(&self, path: &Path) -> String {
match self {
Self::Io(error) => format!("could not read {}: {error}", path.display()),
Self::Parse(error) => format!("{} is not valid TOML: {error}", path.display()),
}
}
}
pub(super) fn read(path: &Path) -> Result<ConfigDocument, ReadError> {
match std::fs::read_to_string(path) {
Ok(text) => ConfigDocument::parse(&text)
.map_err(|error| ReadError::Parse(error.to_string().trim_end().to_owned())),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(ConfigDocument::default()),
Err(error) => Err(ReadError::Io(error)),
}
}
pub(super) struct Edit {
_lock: EditFileLock,
path: PathBuf,
original: String,
pub(super) doc: ConfigDocument,
}
impl Edit {
pub(super) fn open(path: &Path) -> Result<Self, RpcError> {
let lock = acquire_edit_lock(path).map_err(|error| {
if error.kind() == io::ErrorKind::WouldBlock {
RpcError::new(
ErrorCode::ConfigConflict,
format!(
"{} is being edited; read the settings again",
path.display()
),
)
} else {
RpcError::new(
ErrorCode::InternalError,
format!("could not lock {}: {error}", path.display()),
)
}
})?;
let doc = read(path).map_err(|error| match error {
ReadError::Parse(_) => RpcError::new(ErrorCode::ConfigInvalid, error.message(path)),
ReadError::Io(_) => RpcError::new(ErrorCode::InternalError, error.message(path)),
})?;
Ok(Self {
_lock: lock,
path: path.to_owned(),
original: doc.text(),
doc,
})
}
pub(super) fn save(self) -> Result<(Stat, ConfigDocument), RpcError> {
if self.doc.text() != self.original {
self.doc
.write(&self.path)
.map_err(|error| RpcError::new(ErrorCode::InternalError, format!("{error:#}")))?;
}
Ok((Stat::of(&self.path), self.doc))
}
}
pub(super) fn revision(values: &BTreeMap<SettingKey, SettingEntry>) -> ConfigRevision {
let json = serde_json::to_vec(values).expect("setting values encode as JSON");
ConfigRevision::new(hex::encode(Sha256::digest(json)))
}