use std::{
io,
path::{Path, PathBuf},
};
use rho_protocol::{ConfigRevision, ErrorCode, RpcError};
use sha2::{Digest, Sha256};
use crate::hooks::HookConfigError;
const ABSENT: &str = "absent";
pub(super) struct HooksStore {
user: PathBuf,
edits: tokio::sync::Mutex<()>,
}
pub(super) enum HooksTarget {
User(PathBuf),
Project { root: PathBuf, path: PathBuf },
}
pub(super) enum Replacement {
Text(String),
Delete,
}
pub(super) struct Snapshot {
pub(super) path: PathBuf,
pub(super) revision: ConfigRevision,
bytes: Option<Vec<u8>>,
}
impl HooksStore {
pub(super) fn new(rho_home: &Path) -> Self {
Self {
user: crate::hooks::user_hooks_path(rho_home),
edits: tokio::sync::Mutex::new(()),
}
}
pub(super) fn user(&self) -> HooksTarget {
HooksTarget::User(self.user.clone())
}
pub(super) fn project(&self, workspace: &Path) -> Result<HooksTarget, RpcError> {
let root = crate::hooks::project_root(workspace);
let path = crate::hooks::project_hooks_path(&root);
let shared = matches!(
(path.parent(), self.user.parent()),
(Some(project), Some(user)) if crate::plugins::state::same_location(project, user)
);
if shared {
return Err(RpcError::new(
ErrorCode::InvalidParams,
format!(
"{}: this project's hooks file is the user's; use scope `user`",
path.display()
),
));
}
Ok(HooksTarget::Project { root, path })
}
pub(super) fn snapshot(&self, target: &HooksTarget) -> Result<Snapshot, RpcError> {
Snapshot::read(target.path())
}
pub(super) async fn edit(
&self,
target: &HooksTarget,
expected: &ConfigRevision,
edit: impl FnOnce(&Snapshot) -> Result<Replacement, RpcError>,
) -> Result<ConfigRevision, RpcError> {
let path = target.path();
let _editing = self.edits.lock().await;
let _locked = lock(path)?;
let current = Snapshot::read(path)?;
if current.revision != *expected {
return Err(RpcError::new(
ErrorCode::ConfigConflict,
format!(
"{} changed since it was read; read it again",
current.path.display()
),
));
}
let replacement = edit(¤t)?;
let written = match &replacement {
Replacement::Text(text) => {
target
.check(text)
.map_err(|error| RpcError::new(ErrorCode::InvalidParams, error.to_string()))?;
crate::config_writer::write_bytes_atomically(path, text.as_bytes())
}
Replacement::Delete => match std::fs::remove_file(path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
removed => removed,
},
};
written.map_err(|error| {
RpcError::new(
ErrorCode::InternalError,
format!("could not write {}: {error}", path.display()),
)
})?;
Ok(revision(match &replacement {
Replacement::Text(text) => Some(text.as_bytes()),
Replacement::Delete => None,
}))
}
}
impl HooksTarget {
fn path(&self) -> &Path {
match self {
Self::User(path) | Self::Project { path, .. } => path,
}
}
fn check(&self, text: &str) -> Result<(), HookConfigError> {
match self {
Self::User(path) => crate::hooks::check_user_hooks(path, text),
Self::Project { root, .. } => crate::hooks::check_project_hooks(root, text),
}
}
}
impl Snapshot {
fn read(path: &Path) -> Result<Self, RpcError> {
let bytes = match std::fs::read(path) {
Ok(bytes) => Some(bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => {
return Err(RpcError::new(
ErrorCode::InternalError,
format!("could not read {}: {error}", path.display()),
));
}
};
Ok(Self {
path: crate::paths::without_verbatim_prefix(path.to_path_buf()),
revision: revision(bytes.as_deref()),
bytes,
})
}
pub(super) fn text(&self) -> Result<Option<&str>, RpcError> {
self.bytes
.as_deref()
.map(|bytes| {
std::str::from_utf8(bytes).map_err(|_| {
RpcError::new(
ErrorCode::ConfigInvalid,
format!("{} is not UTF-8 text", self.path.display()),
)
})
})
.transpose()
}
}
fn revision(bytes: Option<&[u8]>) -> ConfigRevision {
ConfigRevision::new(bytes.map_or_else(
|| ABSENT.to_owned(),
|bytes| hex::encode(Sha256::digest(bytes)),
))
}
fn lock(path: &Path) -> Result<crate::config_writer::edit_lock::EditFileLock, RpcError> {
crate::config_writer::edit_lock::acquire_edit_lock(path).map_err(|error| {
if error.kind() == io::ErrorKind::WouldBlock {
RpcError::new(
ErrorCode::ConfigConflict,
format!("{} is being edited; read it again", path.display()),
)
} else {
RpcError::new(
ErrorCode::InternalError,
format!("could not lock {}: {error}", path.display()),
)
}
})
}