use std::time::{Duration, Instant};
use shrs::prelude::*;
pub struct CommandTimerState {
start_time: Option<Instant>,
prev_command_time: Option<Duration>,
}
impl CommandTimerState {
pub fn new() -> Self {
Self {
start_time: None,
prev_command_time: None,
}
}
pub fn start(&mut self) {
self.start_time = Some(Instant::now());
}
pub fn end(&mut self) {
if let Some(start_time) = self.start_time {
self.prev_command_time = Some(Instant::now().duration_since(start_time));
}
self.start_time = None;
}
pub fn command_time(&self) -> Option<Duration> {
self.prev_command_time
}
}
pub struct CommandTimerPlugin;
impl Plugin for CommandTimerPlugin {
fn init(&self, shell: &mut ShellConfig) -> anyhow::Result<()> {
shell.hooks.insert(before_command_hook);
shell.hooks.insert(after_command_hook);
shell.states.insert(CommandTimerState::new());
Ok(())
}
fn meta(&self) -> PluginMeta {
PluginMeta::new(
"Command Timer",
"Stores the amount of time taken for the previous command to run",
None,
)
}
}
pub fn before_command_hook(
mut state: StateMut<CommandTimerState>,
_ctx: &BeforeCommandCtx,
) -> anyhow::Result<()> {
state.start();
Ok(())
}
fn after_command_hook(
mut state: StateMut<CommandTimerState>,
_ctx: &AfterCommandCtx,
) -> anyhow::Result<()> {
state.end();
Ok(())
}