Prompt

Struct Prompt 

Source
pub struct Prompt {
    pub prompt_text: String,
    pub history: Vec<String>,
    pub commands: Vec<Command>,
}
Expand description

Config struct for building command line interfaces. An example:

use shli::{Prompt,Command};

let mut p = Prompt::new("> ".to_string(), vec!(
    Command::new("print"),
    Command::new("echo"),
    Command::new("cat").arg("--help"),
    Command::new("exit")
));

Now, use the read_commandline method to let the user type a command.

It will tab complete print, echo, cat, cat --help and exit.

Fields§

§prompt_text: String§history: Vec<String>§commands: Vec<Command>

Implementations§

Source§

impl Prompt

Source

pub fn new(prompt_text: String, commands: Vec<Command>) -> Prompt

Creates a new Prompt instance.

prompt_text is the text written before the user input. commands is the list of available commands used by tab completion.

Examples found in repository?
examples/simple.rs (lines 6-14)
5fn main() {
6    let mut p = Prompt::new(
7        "> ".to_string(),
8        vec![
9            Command::new("print"),
10            Command::new("echo"),
11            Command::new("cat").arg("--help"),
12            Command::new("exit"),
13        ],
14    );
15    loop {
16        // read_commandline does all the reading and tab completion
17        match p.read_commandline() {
18            Ok(line) => {
19                println!("");
20                match line.get(0).map(|s| s.as_str()) {
21                    Some("exit") => break,
22                    Some("print") | Some("echo") => {
23                        if line.len() > 1 {
24                            let output = line[1..]
25                                .iter()
26                                .map(|s| &**s)
27                                .collect::<Vec<&str>>()
28                                .join(" ");
29                            println!("{}", output);
30                        }
31                    }
32                    Some(cmd) => println!("Did not find '{}' command!", cmd),
33                    None => {}
34                }
35            }
36            Err(Error::CtrlD) => {
37                    println!("exit");
38                    break;
39            }
40            Err(Error::CtrlC) => println!("\nCtrl+C pressed."),
41            Err(Error::IoError(e)) => println!("Reading error: {:?}", e),
42        }
43    }
44}
Source

pub fn read_commandline(&mut self) -> Result<Vec<String>, Error>

Prompt for a single command line.

This function reads and returns a command line. Line editing with backspace and ALT+backspace is supported.

If TAB is pressed by the user, the callback function completion is asked for possible argument completion. If it returns exactly 1 completion, it is used, if it returns more, they are displayed.

If Ctrl+C is pressed, this function returns Err(Error::new(ErrorKind::Other, "Ctrl-C pressed."), while an EOF of stdin or Ctrl+D will return the error type ErrorKind::UnexpectedEof.

On success, read_commandline returns a Vector of command line components (command + arguments).

For example, the following input:

> print out "example command"

will return vec!["print", "out", "example command"].

Examples found in repository?
examples/simple.rs (line 17)
5fn main() {
6    let mut p = Prompt::new(
7        "> ".to_string(),
8        vec![
9            Command::new("print"),
10            Command::new("echo"),
11            Command::new("cat").arg("--help"),
12            Command::new("exit"),
13        ],
14    );
15    loop {
16        // read_commandline does all the reading and tab completion
17        match p.read_commandline() {
18            Ok(line) => {
19                println!("");
20                match line.get(0).map(|s| s.as_str()) {
21                    Some("exit") => break,
22                    Some("print") | Some("echo") => {
23                        if line.len() > 1 {
24                            let output = line[1..]
25                                .iter()
26                                .map(|s| &**s)
27                                .collect::<Vec<&str>>()
28                                .join(" ");
29                            println!("{}", output);
30                        }
31                    }
32                    Some(cmd) => println!("Did not find '{}' command!", cmd),
33                    None => {}
34                }
35            }
36            Err(Error::CtrlD) => {
37                    println!("exit");
38                    break;
39            }
40            Err(Error::CtrlC) => println!("\nCtrl+C pressed."),
41            Err(Error::IoError(e)) => println!("Reading error: {:?}", e),
42        }
43    }
44}

Auto Trait Implementations§

§

impl Freeze for Prompt

§

impl RefUnwindSafe for Prompt

§

impl Send for Prompt

§

impl Sync for Prompt

§

impl Unpin for Prompt

§

impl UnwindSafe for Prompt

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.