Module hooks

Source
Expand description

Shell runtime hooks

Hooks are user provided functions that are called on a variety of events that occur in the shell. Shrs defines specific events like [StartupEvent] - which runs on every boot, allowing you to create a welcome message, or [ChangeDirEvent] - which runs when the working directory is changed. It is also possible to define and emit your own custom events, which can then be subscribed to anywhere else in the shell.

An event that can be emitted at any time in the shell lifecycle, by either the shell directly, or as a custom event used in a 3rd party plugin. It is then possible to register a hook on this event to be ran every time the event occurs. To define your own event, you must satisfy the HookEventMarker trait. An easy way to do this is to use the [HookEvent] derive macro.

// Define an event
#[derive(HookEvent)]
pub struct MyEvent {
    pub foo: u32,
    pub bar: String,
}

// Define a handler that uses this event
let my_handler = |event: &MyEvent| -> anyhow::Result<()> {
    println!("my hook ran! foo: {}, bar: {}", event.foo, event.bar);
    Ok(())
};

// Register the hook during the shell initialization process
let mut hooks = Hooks::new();
hooks.insert(my_handler);
let myshell = ShellBuilder::default().with_hooks(hooks);

Then to emit the event, we can construct an instance of the event and call Shell::run_hooks on Shell. Note that we must be in a handler (insert link) to be able to query for Shell.

let my_event = MyEvent {
    foo: 42,
    bar: "eggplant".into(),
};
shell.run_hooks(my_event);

Modules§

events
Hook definitions that are emitted by the shell

Structs§

FunctionHook
Hooks
Shell state containing all registered hooks

Traits§

Hook
The handler function that can be registered to listen to an event of a given type
HookEventMarker
Marker trait a hook struct must implement
IntoHook

Type Aliases§

StoredHook