Skip to main content

Module shell_init

Module shell_init 

Source
Available on crate feature shell-init only.
Expand description

Shell integration: one init <SHELL> verb that hooks a CLI into the user’s shell.

The verb prints a script that runs one command of the CLI in the foreground, before the shell draws its first prompt. It never runs again in that shell. The CLI declares the command once as a Hook, and ctl-core writes every line of shell syntax from it.

The hook runs only when its variable is set to a non-empty value and the binary is on PATH. A startup file that loads the script therefore stays safe on a machine without the CLI, or outside the context the variable marks. Loading the script twice installs the hook once.

A CLI flattens InitCommand into its subcommands, routes the verb to shell::view, and returns the script. The example needs clap with its derive feature, as the crate quick start shows:

use ctl_core::prelude::*;
use ctl_core::shell;
use ctl_core::shell_init::{Hook, InitCommand};

#[derive(Parser)]
struct Cli {
    #[command(flatten)]
    output: OutputArgs,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    #[command(flatten)]
    Init(InitCommand),
}

fn main() -> ExitCode {
    App::<Cli>::new("toy")
        .view(|cli| match cli.command {
            Command::Init(_) => shell::view(cli.output.format),
        })
        .run(|cli| match cli.command {
            Command::Init(command) => {
                let hook = Hook::new("toy", "pick", "TOY_BLOCK")?;
                Ok(command.script(&hook))
            }
        })
}

A user loads the script from a startup file. Each script names its line in its first comment:

ShellStartup fileLine
bash~/.bashrceval "$(toy init bash)"
zsh~/.zshrceval "$(toy init zsh)"
fish~/.config/fish/config.fishtoy init fish | source

The script calls the binary by name and carries no path or setting read at init time, so a saved copy keeps working across upgrades.

Structs§

Hook
A command of the CLI that the shell runs once, in the foreground, before its first prompt.
InitArgs
The arguments of the init verb.

Enums§

HookError
A Hook part that is not a word the shell reads without quoting.
InitCommand
The init verb, flattened into a CLI’s subcommands with #[command(flatten)], so its name, help, and argument read the same in every CLI built on ctl-core.