use std::ops::{Deref, DerefMut};
use crate::{Event, StepName};
use crate::server::context::RunContext;
use crate::server::error::Result;
#[derive(Debug)]
pub struct StepGuard<'a, S> {
ctx: &'a mut RunContext<S>,
name: StepName,
ended: bool,
}
impl<'a, S> StepGuard<'a, S> {
pub(crate) fn start(ctx: &'a mut RunContext<S>, name: StepName) -> Result<Self> {
ctx.emit(Event::step_started(name.clone()))?;
Ok(Self {
ctx,
name,
ended: false,
})
}
pub fn name(&self) -> &StepName {
&self.name
}
pub fn finish(mut self) -> Result<()> {
self.ended = true;
self.ctx.emit(Event::step_finished(self.name.clone()))
}
}
impl<S> Deref for StepGuard<'_, S> {
type Target = RunContext<S>;
fn deref(&self) -> &Self::Target {
self.ctx
}
}
impl<S> DerefMut for StepGuard<'_, S> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.ctx
}
}
impl<S> Drop for StepGuard<'_, S> {
fn drop(&mut self) {
if !self.ended {
let _ = self.ctx.emit(Event::step_finished(self.name.clone()));
}
}
}