Crate shellfish[][src]

Expand description

Shellfish

Shellfish is a library to include interactive shells within a program. This may be useful when building terminal application where a persistent state is needed, so a basic cli is not enough; but a full tui is over the scope of the project. Shellfish provides a middle way, allowing interactive command editing whilst saving a state that all commands are given access to.

The shell

By default the shell contains only 3 built-in commands:

  • help - displays help information.
  • quit - quits the shell.
  • exit - exits the shell.

The last two are identical, only the names differ.

When a command is added by the user (see bellow) the help is automatically generated and displayed. Keep in mind this help should be kept rather short, and any additional help should be through a dedicated help option.

Example

The following code creates a basic shell, with the added command of greet which requires one argument, and if not given returns an error. It is as follows:

use shellfish::Command;
use shellfish::Shell;
use std::error::Error;
use std::fmt;
 
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Define a shell
    let mut shell = Shell::new((), "<[Shellfish Example]>-$ ");
 
    // Add a command
    shell.commands.insert(
        "greet".to_string(),
        Command::new("greets you.".to_string(), greet),
    );
 
    // Run the shell
    shell.run()?;
 
    Ok(())
}
 
/// Greets the user
fn greet(_state: &mut (), args: Vec<String>) -> Result<(), Box<dyn Error>> {
    let arg = args.get(1).ok_or_else(|| Box::new(GreetingError))?;
    println!("Greetings {}, my good friend.", arg);
    Ok(())
}
 
/// Greeting error
#[derive(Debug)]
pub struct GreetingError;
 
impl fmt::Display for GreetingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "No name specified")
    }
}
 
impl Error for GreetingError {}

Re-exports

pub use command::Command;

Modules

command

Structs

Shell

A shell represents a shell for editing commands in.