use crate::forest::{Processor, Tree};
use std::{error, fmt, sync::Arc};
#[derive(Debug)]
pub struct Error {
pub tree: Tree,
source: gix_error::Error,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.source, f)
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(&self.source)
}
}
pub fn error(tree: Tree, source: gix_error::Error) -> Error {
Error { tree, source }
}
pub type Result = std::result::Result<(), Error>;
#[derive(Debug)]
pub struct WithFallback<P, F> {
pub(super) primary: P,
pub(super) fallback: F,
}
#[derive(Debug)]
pub struct Sink;
#[derive(Debug)]
pub struct FromFn<F>(F);
pub fn from_fn<F>(f: F) -> FromFn<F>
where
F: 'static + Fn(Tree) -> Result,
{
FromFn(f)
}
impl<P, F> Processor for WithFallback<P, F>
where
P: Processor,
F: Processor,
{
fn process(&self, tree: Tree) -> Result {
self.primary.process(tree).or_else(|err| {
eprintln!("{err}, using fallback processor...");
self.fallback.process(err.tree)
})
}
}
impl Processor for Sink {
fn process(&self, _tree: Tree) -> Result {
Ok(())
}
}
impl<F> Processor for FromFn<F>
where
F: 'static + Fn(Tree) -> Result,
{
fn process(&self, tree: Tree) -> Result {
(self.0)(tree)
}
}
impl<P: Processor> Processor for Box<P> {
fn process(&self, tree: Tree) -> Result {
self.as_ref().process(tree)
}
}
impl<P: Processor> Processor for Arc<P> {
fn process(&self, tree: Tree) -> Result {
self.as_ref().process(tree)
}
}