### Example Help String Source: https://docs.rs/shellfish/latest/shellfish/command/struct.Command.html An example of a help string for a command, illustrating the character limit. ```rust prints the arguments to the output. ``` -------------------------------- ### Example Usage of clap_command Macro Source: https://docs.rs/shellfish/latest/shellfish/macro.clap_command.html Demonstrates how to use the clap_command macro to register synchronous and asynchronous commands with a shell. Requires the 'clap' feature flag. ```rust #[derive(Parser, Debug)] #[clap(author, version, about)] struct Args { // - snip } shell.commands.insert("greet", clap_command!((), Args, greet)); shell.commands.insert("greet-async", clap_command!((), Args, async greet_async)); fn greet(_state: &mut (), args: Args) -> Result<(), Box> { // - snip } async fn greet_async(_state: &mut (), args: Args) -> Result<(), Box> { // - snip } ``` -------------------------------- ### Create New Painted Instance Source: https://docs.rs/shellfish/latest/shellfish/input_handler/enum.InputResult.html Creates a new `Painted` instance with a default style. This is the starting point for applying various text styles. ```rust fn new(self) -> Painted where Self: Sized, Create a new `Painted` with a default `Style`. Read more ``` -------------------------------- ### Shell::run Source: https://docs.rs/shellfish/latest/shellfish/shell/struct.Shell.html Starts running the synchronous shell, processing commands and events until completion. Returns a Result indicating success or failure. ```APIDOC ## Shell::run ### Description Starts running the shell. ### Method Instance Method ### Signature `pub fn run(&mut self) -> Result<()>` ### Returns `Result<()>` - Ok(()) on success, or an error if the shell fails to run. ``` -------------------------------- ### Shell::run_async Source: https://docs.rs/shellfish/latest/shellfish/shell/struct.Shell.html Starts running the asynchronous shell, processing commands and events until completion. This method is `async` and requires an `await`. Available only when the `async` crate feature is enabled. ```APIDOC ## Shell::run_async ### Description Starts running the shell. Available on `async` crate feature only. ### Method Instance Method ### Signature `pub async fn run_async(&mut self) -> Result<()>` ### Returns `Result<()>` - Ok(()) on success, or an error if the shell fails to run. ``` -------------------------------- ### Shellfish with Clap Argument Parsing Source: https://docs.rs/shellfish/latest/shellfish/command/index.html Integrates Shellfish with the 'clap' crate for robust command-line argument parsing. This example shows a 'greet' command that accepts 'name', 'age', and 'formal' options. ```rust // ... imports ... /// Simple command to greet a person /// /// This command will greet the person based of a multitide /// of option flags, see below. #[derive(Parser, Debug)] #[clap(author, version, about)] struct GreetArgs { /// Name of the person to greet name: String, /// Age of the person to greet #[clap(short, long)] age: Option, /// Whether to be formal or note #[clap(short, long)] formal: bool, } #[async_std::main] async fn main() -> Result<(), Box> { // Define a shell let mut shell = Shell::new_with_async_handler( (), "<[Shellfish Example]>-$ ", DefaultAsyncHandler::default(), DefaultEditor::new()?, ); shell .commands .insert("greet", clap_command!((), GreetArgs, greet)); shell.run_async().await?; Ok(()) } fn greet( _state: &mut (), args: GreetArgs, ) -> Result<(), Box> { // .. snip .. / Ok(()) } ``` -------------------------------- ### Shellfish clap_command! Macro Usage Example Source: https://docs.rs/shellfish/latest/src/shellfish/clap_command.rs.html Demonstrates how to define a clap parser and use the clap_command! macro to register both synchronous and asynchronous commands with Shellfish. Requires the 'async' feature for async commands. ```rust use shellfish::clap_command; use clap::Parser; use std::error::Error; #[derive(Parser, Debug)] #[clap(author, version, about)] struct Args { // - snip } // Example for synchronous command // shell.commands.insert("greet", clap_command!((), Args, greet)); // Example for asynchronous command // shell.commands.insert("greet-async", clap_command!((), Args, async greet_async)); fn greet(_state: &mut (), args: Args) -> Result<(), Box> { // - snip Ok(()) } async fn greet_async(_state: &mut (), args: Args) -> Result<(), Box> { // - snip Ok(()) } ``` -------------------------------- ### fn type_id(&self) -> TypeId Source: https://docs.rs/shellfish/latest/shellfish/shell/struct.Shell.html Gets the TypeId of the current object. This is part of the Any trait implementation. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. This method is part of the `Any` trait implementation. ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### App::new Source: https://docs.rs/shellfish/latest/shellfish/app/struct.App.html Creates a new App instance with initial state and project name. ```rust pub fn new(state: T, project_name: String) -> Result> ``` -------------------------------- ### App::new Source: https://docs.rs/shellfish/latest/shellfish/app/struct.App.html Creates a new App instance with a given state and project name. This is a constructor for the App struct. ```APIDOC ## pub fn new(state: T, project_name: String) -> Result> ### Description Creates a new shell. ### Parameters * **state** (T) - The initial state of the application. * **project_name** (String) - The name of the project. ``` -------------------------------- ### Create a new App with default handler Source: https://docs.rs/shellfish/latest/src/shellfish/app.rs.html Initializes a new App instance with a default command-line handler. The project name is used for cache file naming. State is loaded from the cache if available. ```rust impl Deserialize<'a>> App<'_, T, DefaultCommandLineHandler> { /// Creates a new shell pub fn new(state: T, project_name: String) -> Result> { let mut this = Self { commands: HashMap::new(), state, handler: DefaultCommandLineHandler { proj_name: Some(project_name), }, description: String::new(), }; this.load_cache()?; Ok(this) } } ``` -------------------------------- ### new Source: https://docs.rs/shellfish/latest/shellfish/handler/app/struct.DefaultCommandLineHandler.html Create a new `Painted` with a default `Style`. Read more. ```APIDOC ## new ### Description Create a new `Painted` with a default `Style`. ### Method `new()` ### Constraints `Self: Sized` ``` -------------------------------- ### Conditionally Apply Styling Source: https://docs.rs/shellfish/latest/shellfish/input_handler/struct.IO.html Conditionally applies styling based on a `Condition`. This method replaces any previous condition. Example shows styling only when stdout and stderr are TTYs. ```rust use yansi::{Paint, Condition}; painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY); ``` -------------------------------- ### new Source: https://docs.rs/shellfish/latest/shellfish/handler/asynchronous/struct.DefaultAsyncHandler.html Create a new `Painted` with a default `Style`. Read more. ```APIDOC ## new ### Description Create a new `Painted` with a default `Style`. ### Method `new()` ### Parameters None ### Response Returns a new `Painted`. ### Request Example ``` let painted = Painted::new(); ``` ``` -------------------------------- ### Creating a Synchronous Command Source: https://docs.rs/shellfish/latest/shellfish/command/struct.Command.html Demonstrates how to create and insert a synchronous command into a Shell instance. ```rust use shellfish::* use std::error::Error; fn greet(_state: &mut (), args: Vec) -> Result<(), Box> { //--snip-- } fn main() { // Creates a shell let mut shell = Shell::new((), "[Shell]-$"); // Creates a command shell.commands.insert( "greet", Command::new("greets_you".to_string(), greet), ); } ``` -------------------------------- ### Get Cache Path Source: https://docs.rs/shellfish/latest/src/shellfish/handler/app.rs.html Determines the cache file path based on the operating system (Linux, Windows, MacOS). Returns None if the home directory cannot be found. ```rust fn get_cache(&self) -> Option { let mut path = home::home_dir()?; #[cfg(target_os = "windows")] { path.push("AppData"); path.push("Local"); } #[cfg(target_os = "linux")] { path.push(".cache"); } #[cfg(target_os = "macos")] { path.push("Library Support"); } path.push(self.proj_name.as_ref().unwrap_or(&env::args().next()?)); path.push("shellfish.json"); Some(path) } ``` -------------------------------- ### new Source: https://docs.rs/shellfish/latest/shellfish/command/enum.CommandType.html Create a new Painted with a default Style. ```APIDOC ## new ### Description Create a new `Painted` with a default `Style`. Read more ### Method `new(self) -> Painted` ### Constraints `where Self: Sized` ``` -------------------------------- ### Run Shell Asynchronously Source: https://docs.rs/shellfish/latest/src/shellfish/shell.rs.html Starts the shell's main loop, reading and processing commands asynchronously. Handles input, command execution, and exit conditions. ```rust pub async fn run_async(&mut self) -> io::Result<()> { '_shell: loop { // Read a line let line = match self.input_handler.read(&self.prompt.to_string())? { InputResult::S(line) => line, InputResult::Interrupted => continue '_shell, InputResult::EOF => break '_shell, }; // Runs the line match Self::unescape(line.trim()) { Ok(line) => { if self .handler .handle_async( line, &self.commands, &mut self.state, &self.description, ) .await { break '_shell; } } Err(e) => eprintln!("{}", Paint::red(&e.to_string())), } } Ok(()) } ``` -------------------------------- ### Creating an Asynchronous Command Source: https://docs.rs/shellfish/latest/shellfish/command/struct.Command.html Shows how to create and insert an asynchronous command using `Command::new_async` and `async_fn!`. ```rust use shellfish::* use std::error::Error; async fn greet(_state: &mut (), args: Vec) -> Result<(), Box> { //--snip-- } async fn async_main() { // Creates a shell let mut shell = Shell::new((), "[Shell]-$"); // Creates a command shell.commands.insert( "greet", Command::new_async("greets_you".to_string(), async_fn!((), greet)), ); } ``` -------------------------------- ### Command::new Source: https://docs.rs/shellfish/latest/shellfish/command/struct.Command.html Creates a new synchronous `Command` instance. This method takes a help string and a command function pointer as arguments. ```APIDOC ## Command::new ### Description Creates a new synchronous `Command`. ### Method `pub fn new(help: String, command: CommandFn) -> Self` ### Parameters * **help** (String) - Description for the command. * **command** (CommandFn) - The function pointer for the command. ### Example ```rust use shellfish::* use std::error::Error; fn greet(_state: &mut (), args: Vec) -> Result<(), Box> { //--snip-- Ok(()) } fn main() { let mut shell = Shell::new((), "[Shell]-$"); shell.commands.insert( "greet", Command::new("greets_you".to_string(), greet), ); } ``` ``` -------------------------------- ### new Source: https://docs.rs/shellfish/latest/shellfish/input_handler/enum.InputResult.html Creates a new `Painted` object with a default style. ```APIDOC ## new ### Description Create a new `Painted` with a default `Style`. ### Method `new()` ### Parameters None ### Response Returns a new `Painted` object. ### Request Example ``` let painted = Painted::new(); ``` ``` -------------------------------- ### new Source: https://docs.rs/shellfish/latest/shellfish/handler/async_app/struct.DefaultAsyncCLIHandler.html Creates a new `Painted` object with a default style. ```APIDOC ## new ### Description Create a new `Painted` with a default `Style`. Read more ### Method This is a constructor method. ### Endpoint N/A ### Parameters * **self** - The object to create a `Painted` version of. ### Request Example ``` // Assuming 'value' is of a type that can be converted into Painted let painted_value = value.new(); ``` ### Response #### Success Response Returns a new `Painted` object. #### Response Example ``` // A new Painted object ``` ``` -------------------------------- ### Create a new App with a custom handler Source: https://docs.rs/shellfish/latest/src/shellfish/app.rs.html Initializes a new App instance with a provided command-line handler. This is useful when a custom handler is needed that can manage CLI arguments, as the first argument is expected to be the binary name. ```rust impl Deserialize<'a>, H: CommandLineHandler> App<'_, T, H> { /// Creates a new shell with the given handler. /// /// **Note that this should be a handler which can deal with cli /// arguments, as in the FIRST ARGUMENT is the BINARY name.** pub fn new_with_handler( state: T, handler: H, ) -> Result> { let mut this = Self { commands: HashMap::new(), state, handler, description: String::new(), }; this.load_cache()?; Ok(this) } } ``` -------------------------------- ### new Source: https://docs.rs/shellfish/latest/shellfish/shell/enum.UnescapeError.html Create a new `Painted` with a default `Style`. ```APIDOC ## new ### Description Create a new `Painted` with a default `Style`. ### Method `new()` ### Parameters * **self** - The object to create a new `Painted` from. ### Response Returns a new `Painted` object. ### Example (No example provided in source) ``` -------------------------------- ### new Source: https://docs.rs/shellfish/latest/shellfish/handler/default/struct.DefaultHandler.html Create a new `Painted` with a default `Style`. ```APIDOC ## new ### Description Create a new `Painted` with a default `Style`. ### Method This is a constructor method, not an HTTP endpoint. ### Endpoint N/A ### Parameters N/A ### Request Example ``` Painted::new() ``` ### Response #### Success Response Returns a new `Painted` object. #### Response Example N/A ``` -------------------------------- ### Enable Wrapping using wrap() Source: https://docs.rs/shellfish/latest/shellfish/input_handler/struct.IO.html Demonstrates the preferred method for enabling text wrapping using the `.wrap()` builder method. ```rust use yansi::Paint; painted.wrap(); ``` -------------------------------- ### Set Background Color using bg() and on_red() Source: https://docs.rs/shellfish/latest/shellfish/input_handler/struct.IO.html Demonstrates setting the background color. The `bg()` method is rarely used; prefer specific methods like `on_red()` for clarity and conciseness. ```rust use yansi::{Paint, Color}; painted.bg(Color::Red); ``` ```rust use yansi::Paint; painted.on_red(); ``` -------------------------------- ### App::try_from_async Source: https://docs.rs/shellfish/latest/shellfish/app/struct.App.html Creates an App instance from a Shell for asynchronous command handling. Requires `async` feature. ```rust pub fn try_from_async, I: InputHandler>( shell: Shell<'f, T, M, H, I>, ) -> Result> ``` -------------------------------- ### Basic Shellfish Commands Source: https://docs.rs/shellfish/latest/shellfish/command/index.html Creates a Shellfish instance with custom commands: greet, echo, count, and cat. Supports both interactive and non-interactive modes based on command-line arguments. ```rust use std::error::Error; use std::fmt; use std::ops::AddAssign; use async_std::prelude::*; use rustyline::DefaultEditor; use shellfish::{app, handler::DefaultAsyncHandler, Command, Shell}; #[macro_use] extern crate shellfish; #[async_std::main] async fn main() -> Result<(), Box> { // Define a shell let mut shell = Shell::new_with_async_handler( 0_u64, "<[Shellfish Example]>-$ ", DefaultAsyncHandler::default(), DefaultEditor::new()?, ); // 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), ), ); // 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::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) -> Result<(), Box> { let arg = args.get(1).ok_or_else(|| Box::new(GreetingError))?; println!("Greetings {}, my good friend.", arg); Ok(()) } /// Echos the input fn echo(_state: &mut u64, args: Vec) -> Result<(), Box> { let mut args = args.iter(); args.next(); for arg in args { print!("{} ", arg); } println!(); Ok(()) } /// Acts as a counter fn count(state: &mut u64, _args: Vec) -> Result<(), Box> { state.add_assign(1); println!("You have used this counter {} times", state); Ok(()) } /// Asynchronously reads a file async fn cat( _state: &mut u64, args: Vec, ) -> Result<(), Box> { use async_std::fs; 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 #[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 {} ``` -------------------------------- ### App::new_with_handler Source: https://docs.rs/shellfish/latest/shellfish/app/struct.App.html Creates a new App instance with a given state and a command line handler. The handler must be capable of processing CLI arguments. ```APIDOC ## pub fn new_with_handler(state: T, handler: H) -> Result> ### Description Creates a new shell with the given handler. ### Parameters * **state** (T) - The initial state of the application. * **handler** (H) - The command line handler. ``` -------------------------------- ### Creating a Synchronous Shellfish Command Source: https://docs.rs/shellfish/latest/src/shellfish/command.rs.html Demonstrates how to create a new synchronous command for a Shellfish shell. This involves defining a function that matches the `CommandFn` signature and then using `Command::new` to register it. ```rust use shellfish::* use std::error::Error; fn greet(_state: &mut (), args: Vec) -> Result<(), Box> { //--snip-- # Ok(()) } fn main() { // Creates a shell let mut shell = Shell::new((), "[Shell]-$"); // Creates a command shell.commands.insert( "greet", Command::new("greets_you".to_string(), greet), ); } ``` -------------------------------- ### paint Source: https://docs.rs/shellfish/latest/shellfish/shell/enum.UnescapeError.html Apply a style wholesale to `self`. Any previous style is replaced. ```APIDOC ## paint ### Description Apply a style wholesale to `self`. Any previous style is replaced. ### Method (Implicitly called on an object) ### Parameters * **style** (S: Into