use griz_core::Op;
use griz_store::{PathResolver, Store, StoreError};
use incurs::command::TypedResult;
use std::path::{Component, Path, PathBuf};
#[derive(Debug)]
pub struct CmdError {
pub code: &'static str,
pub message: String,
}
impl CmdError {
pub fn invalid(message: impl Into<String>) -> Self {
Self {
code: "VALIDATION_ERROR",
message: message.into(),
}
}
pub fn result<T>(self) -> TypedResult<T> {
TypedResult::error(self.code, self.message)
}
}
impl From<StoreError> for CmdError {
fn from(error: StoreError) -> Self {
let code = match error {
StoreError::NotFound(_) => "NOT_FOUND",
StoreError::Invalid(_) => "VALIDATION_ERROR",
_ => "STORE_ERROR",
};
Self {
code,
message: error.to_string(),
}
}
}
pub fn root(explicit: Option<&str>) -> Result<PathBuf, CmdError> {
griz_store::directory_path(&normalize(&input_root(explicit)?)?)
.map_err(|error| CmdError::invalid(error.to_string()))
}
pub fn input_root(explicit: Option<&str>) -> Result<PathBuf, CmdError> {
let cwd = crate::request_scope::current_dir().map_err(|e| CmdError::invalid(e.to_string()))?;
Ok(match explicit {
Some(root) => input_path(&cwd, Path::new(root)),
None => cwd,
})
}
#[must_use]
pub fn input_path(root: &Path, path: &Path) -> PathBuf {
root.join(path).components().collect()
}
pub fn resolve_paths(paths: &[PathBuf]) -> Result<Vec<PathBuf>, CmdError> {
let mut resolver = PathResolver::default();
paths
.iter()
.map(|path| normalize_with(&mut resolver, path))
.collect()
}
pub fn resolve(root: &Path, path: &Path) -> Result<PathBuf, CmdError> {
normalize(&root.join(path))
}
fn normalize(path: &Path) -> Result<PathBuf, CmdError> {
normalize_with(&mut PathResolver::default(), path)
}
fn normalize_with(resolver: &mut PathResolver, path: &Path) -> Result<PathBuf, CmdError> {
let mut out = PathBuf::new();
for part in path.components() {
match part {
Component::CurDir => {}
Component::ParentDir => out = parent_directory(&out)?,
other => out.push(other),
}
}
resolver
.resolve_file(&out)
.map_err(|error| CmdError::invalid(error.to_string()))
}
fn parent_directory(path: &Path) -> Result<PathBuf, CmdError> {
let invalid =
|error| CmdError::invalid(format!("resolving parent of {}: {error}", path.display()));
let mut directory = std::fs::canonicalize(path).map_err(invalid)?;
if !std::fs::metadata(&directory).map_err(invalid)?.is_dir() {
return Err(CmdError::invalid(format!(
"parent traversal requires a directory: {}",
path.display()
)));
}
directory.pop();
Ok(directory)
}
pub fn resolve_ops(root: &Path, ops: Vec<Op>) -> Result<Vec<Op>, CmdError> {
let mut resolver = PathResolver::default();
ops.into_iter()
.map(|op| resolve_op(&mut resolver, root, op))
.collect()
}
fn resolve_op(resolver: &mut PathResolver, root: &Path, mut op: Op) -> Result<Op, CmdError> {
match &mut op {
Op::Replace { path, .. }
| Op::Insert { path, .. }
| Op::Create { path, .. }
| Op::Delete { path, .. } => *path = normalize_with(resolver, &root.join(&*path))?,
Op::Move { path, to, .. } => {
*path = normalize_with(resolver, &root.join(&*path))?;
*to = normalize_with(resolver, &root.join(&*to))?;
}
}
Ok(op)
}
pub async fn with_store<T: Send + 'static>(
work: impl FnOnce(&Store) -> Result<T, CmdError> + Send + 'static,
) -> Result<T, CmdError> {
with_blocking(move || work(&Store::open_default()?)).await
}
pub async fn with_blocking<T: Send + 'static>(
work: impl FnOnce() -> Result<T, CmdError> + Send + 'static,
) -> Result<T, CmdError> {
let directory = crate::request_scope::DIRECTORY.try_with(Clone::clone).ok();
tokio::task::spawn_blocking(move || crate::request_scope::blocking(directory, work))
.await
.map_err(|error| CmdError {
code: "INTERNAL_ERROR",
message: error.to_string(),
})?
}