sal-rhai 0.1.0

SAL Rhai - Rhai scripting integration for the System Abstraction Layer
Documentation
use rhai::{Engine, EvalAltResult, Position};
use thiserror::Error;

#[derive(Debug, Error, Clone)]
pub enum SalError {
    #[error("File system error: {0}")]
    FsError(String),
    #[error("Download error: {0}")]
    DownloadError(String),
    #[error("Package error: {0}")]
    PackageError(String),
    #[error("{0}: {1}")]
    Generic(String, String),
}

impl SalError {
    pub fn new(kind: &str, message: &str) -> Self {
        SalError::Generic(kind.to_string(), message.to_string())
    }
}

impl From<SalError> for Box<EvalAltResult> {
    fn from(err: SalError) -> Self {
        let err_msg = err.to_string();
        Box::new(EvalAltResult::ErrorRuntime(err_msg.into(), Position::NONE))
    }
}

/// A trait for converting a Result to a Rhai-compatible error
pub trait ToRhaiError<T> {
    fn to_rhai_error(self) -> Result<T, Box<EvalAltResult>>;
}

impl<T, E: std::error::Error> ToRhaiError<T> for Result<T, E> {
    fn to_rhai_error(self) -> Result<T, Box<EvalAltResult>> {
        self.map_err(|e| {
            Box::new(EvalAltResult::ErrorRuntime(
                e.to_string().into(),
                Position::NONE,
            ))
        })
    }
}

/// Register all the SalError variants with the Rhai engine
///
/// # Arguments
///
/// * `engine` - The Rhai engine to register the error types with
///
/// # Returns
///
/// * `Result<(), Box<EvalAltResult>>` - Ok if registration was successful, Err otherwise
pub fn register_error_types(engine: &mut Engine) -> Result<(), Box<EvalAltResult>> {
    engine
        .register_type_with_name::<SalError>("SalError")
        .register_fn("to_string", |err: &mut SalError| err.to_string());
    Ok(())
}