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.
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.
The following features are available:
* rustyline
, for better input.
* app
, for command line argument parsing.
* async
, for async. This can be coupled with tokio
or async_std
The following code creates a basic shell, with the added commands:
* greet
, greets the user.
* echo
, echoes the input.
* count
, increments a counter.
* cat
, it is cat.
Also, if run with arguments than the shell is run non-interactvely.
```rust use shellfish::{app, Command, Shell}; use std::convert::TryInto; use std::error::Error; use std::fmt; use std::ops::AddAssign; use async_std::prelude::*; use std::pin::Pin;
extern crate async_std;
extern crate shellfish;
async fn main() -> Result<(), Box
// Add some commands
shell.commands.insert(
"greet",
Command::new("greets you.".to_string(), greet),
);
shell.commands.insert(
"echo",
Command::new("prints the input.".to_string(), echo),
);
shell.commands.insert(
"count",
Command::new("increments a counter.".to_string(), count),
);
shell.commands.insert(
"cat",
Command::new_async(
"Displays a plaintext file.".to_string(),
async_fn!(u64, cat)
).await,
);
// Check if we have > 2 args, if so no need for interactive shell
let mut args = std::env::args();
if args.nth(1).is_some() {
// Create the app from the shell.
let mut app: app::App<u64, app::DefaultAsyncCLIHandler> =
app::App::try_from_async(shell)?;
// Set the binary name
app.handler.proj_name = Some("shellfish-example".to_string());
app.load_cache()?;
// Run it
app.run_args_async().await?;
} else {
// Run the shell
shell.run_async().await?;
}
Ok(())
}
/// Greets the user
fn greet(state: &mut u64, args: Vec
/// Echos the input
fn echo(_state: &mut u64, args: Vec
/// Acts as a counter
fn count(state: &mut u64, args: Vec
/// Asynchronously reads a file
async fn cat(state: &mut u64, args: Vec
if let Some(file) = args.get(1) {
let mut contents = String::new();
let mut file = fs::File::open(file).await?;
file.read_to_string(&mut contents).await?;
println!("{}", contents);
}
Ok(())
}
/// Greeting error
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 {} ```