Command trait with static spec, enabled check and run; Registry rejects duplicate ids; Engine::execute runs every command inside the guard, which turns panics into EngineError::Internal and keeps the engine usable. Effects (Quit) are applied by the host. Theme tokens for Lutra Dark and Lutra Light render as --lt-* CSS variables and a webview init script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
59 lines
2 KiB
Rust
59 lines
2 KiB
Rust
//! The last line of defence against bugs: turns a panic at an entry point
|
|
//! into [`EngineError::Internal`] so that the process, and the user's unsaved
|
|
//! work, survive.
|
|
//!
|
|
//! The guard is for bugs. Expected failures are `Result`s and never reach it.
|
|
//! Release builds keep `panic = "unwind"`, which this module relies on.
|
|
|
|
use std::any::Any;
|
|
use std::panic::{AssertUnwindSafe, catch_unwind};
|
|
|
|
use crate::EngineError;
|
|
|
|
/// Runs `f` and converts a panic inside it into [`EngineError::Internal`].
|
|
///
|
|
/// The closure is treated as unwind safe: after a panic the engine state may
|
|
/// hold a half-finished change from the failed command, which is preferable to
|
|
/// losing every open buffer.
|
|
///
|
|
/// # Errors
|
|
/// Returns the closure's own error, or [`EngineError::Internal`] with the
|
|
/// panic message if it panicked.
|
|
pub fn run<T>(f: impl FnOnce() -> Result<T, EngineError>) -> Result<T, EngineError> {
|
|
catch_unwind(AssertUnwindSafe(f))
|
|
.unwrap_or_else(|payload| Err(EngineError::Internal(panic_message(payload.as_ref()))))
|
|
}
|
|
|
|
/// Extracts the message of a panic payload, which is a `&str` or a `String`
|
|
/// for `panic!` with a literal or a format string.
|
|
fn panic_message(payload: &(dyn Any + Send)) -> String {
|
|
if let Some(s) = payload.downcast_ref::<&str>() {
|
|
(*s).to_string()
|
|
} else if let Some(s) = payload.downcast_ref::<String>() {
|
|
s.clone()
|
|
} else {
|
|
"a command panicked".to_string()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn passes_results_through() {
|
|
assert_eq!(run(|| Ok(3)), Ok(3));
|
|
assert_eq!(
|
|
run::<()>(|| Err(EngineError::Failed("no".into()))),
|
|
Err(EngineError::Failed("no".into()))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn converts_panics() {
|
|
let r = run::<()>(|| panic!("boom {}", 42));
|
|
assert_eq!(r, Err(EngineError::Internal("boom 42".into())));
|
|
let r = run::<()>(|| std::panic::panic_any(7_u8));
|
|
assert_eq!(r, Err(EngineError::Internal("a command panicked".into())));
|
|
}
|
|
}
|