use std::path::Path;
use rho_protocol::{
ErrorCode, HooksConfigGetParams, HooksConfigGetResponse, HooksConfigScope,
HooksConfigSetParams, HooksConfigSetResponse, RpcError,
};
use super::{
hooks_store::{HooksStore, HooksTarget, Replacement},
sessions::Workspace,
};
use crate::hooks::HookEditError;
pub(super) fn get(
store: &HooksStore,
params: HooksConfigGetParams,
) -> Result<HooksConfigGetResponse, RpcError> {
let snapshot = store.snapshot(&target_of(store, ¶ms.scope)?)?;
let hooks = match snapshot.text()? {
None => Vec::new(),
Some(text) => {
crate::hooks::hook_entries(text).map_err(|error| refused(&snapshot.path, error))?
}
};
Ok(HooksConfigGetResponse::new(
snapshot.path,
snapshot.revision,
hooks,
))
}
pub(super) async fn set(
store: &HooksStore,
params: HooksConfigSetParams,
) -> Result<HooksConfigSetResponse, RpcError> {
let target = target_of(store, ¶ms.scope)?;
let revision = store
.edit(&target, ¶ms.revision, |current| {
crate::hooks::apply_hook_changes(current.text()?, ¶ms.changes)
.map(Replacement::Text)
.map_err(|error| refused(¤t.path, error))
})
.await?;
Ok(HooksConfigSetResponse::new(revision))
}
fn target_of(store: &HooksStore, scope: &HooksConfigScope) -> Result<HooksTarget, RpcError> {
match scope {
HooksConfigScope::User => Ok(store.user()),
HooksConfigScope::Project { workspace } => {
store.project(Workspace::parse("workspace", workspace)?.path())
}
}
}
fn refused(path: &Path, error: HookEditError) -> RpcError {
let code = match &error {
HookEditError::FileInvalid(_) => ErrorCode::ConfigInvalid,
HookEditError::Missing { .. }
| HookEditError::NotTable { .. }
| HookEditError::HoldsId { .. }
| HookEditError::Field { .. } => ErrorCode::InvalidParams,
};
RpcError::new(code, format!("{}: {error}", path.display()))
}