Struct Trompt

Source
pub struct Trompt<R: Read, W: Write> { /* private fields */ }
Expand description

The state of the prompt that we send to the user. It is general on any input and output that implement Read and Write respectively.

§Examples

Create prompter that prompts for a username on stdout awaiting a response on stdin:

use trompt::Trompt;
let username = Trompt::stdout().prompt("username: ");

Similarly create a prompter that writes to stderr instead, and doesn’t echo the user input:

use trompt::Trompt;
let password = Trompt::stderr().silent().prompt("password: ");

Implementations§

Source§

impl<R: Read, W: Write> Trompt<R, W>

Source

pub fn new(input: R, output: W) -> Trompt<R, W>

Start a new prompter with default values.

§Examples
use std::io::Cursor;
use trompt::Trompt;

let input = Cursor::new(vec![]);
let output = Cursor::new(vec![]);

let prompter = Trompt::new(input, output);
Source

pub fn message(&mut self, message: &str) -> &mut Trompt<R, W>

Set the message before the input.

§Examples
use trompt::Trompt;

let response = Trompt::stdout().message("Some prompt: ").send();
Source

pub fn silent(&mut self) -> &mut Trompt<R, W>

Set to true if you want to hide the user input. For example for passwords.

§Examples
use trompt::Trompt;

let password = Trompt::stdout().silent().prompt("password: ");
Source

pub fn validate<F>(&mut self, validator: F) -> &mut Trompt<R, W>
where F: 'static + Fn(&str) -> Result<(), ValidationError>,

Adds a validator to the input.

Note calling this multiple times will call each validator in order.

§Examples
use std::io::Cursor;
use trompt::{Error, Trompt};
use trompt::ValidationError::{Other, UnexpectedInput};

let output = Cursor::new(vec![]);
let input = Cursor::new(b"\
    Jack & Jill\n\
    Went up the hill\n\
    To have fun @mordor\n\
".to_vec());

let mut prompter = Trompt::new(input, output);

prompter
    .validate(move |s| if s.contains("&") {
        Err(UnexpectedInput("&".into()))
    } else {
        Ok(())
    })
    .validate(move |s| if !s.contains("@") {
        Err(Other("No @ present".into()))
    } else {
        Ok(())
    });

assert_eq!(prompter.send(), Err(Error::Validation(UnexpectedInput("&".to_string()))));
assert_eq!(prompter.send(), Err(Error::Validation(Other("No @ present".to_string()))));
assert_eq!(prompter.send(), Ok("To have fun @mordor".to_string()));
Source

pub fn max_len(&mut self, max: usize) -> &mut Trompt<R, W>

Set a limit on the maximum number of characters in the response.

§Examples
use trompt::{Error, Trompt, ValidationError};

let input = std::io::Cursor::new(b"This is too long");
let output = std::io::Cursor::new(Vec::new());

let too_long = Trompt::new(input, output)
    .max_len(5)
    .prompt("Be precise (max 5): ");

assert_eq!(
    too_long.unwrap_err(),
    Error::Validation(ValidationError::TooLong)
);
Source

pub fn min_len(&mut self, min: usize) -> &mut Trompt<R, W>

Set a limit on the minimum number of characters in the response.

§Examples
use trompt::{Error, Trompt, ValidationError};

let mut input = std::io::Cursor::new(b"too short\n");
let mut output = std::io::Cursor::new(Vec::new());

let too_short = Trompt::new(&mut input, &mut output)
    .min_len(12)
    .prompt("Be explicit (min 12): ");

assert_eq!(
    too_short.unwrap_err(),
    Error::Validation(ValidationError::TooShort)
);
Source

pub fn required(&mut self) -> &mut Trompt<R, W>

Disallow responding with an empty string.

§Examples
use trompt::{Error, Trompt, ValidationError};

let mut input = std::io::Cursor::new(b"\n");
let mut output = std::io::Cursor::new(Vec::new());

let too_short = Trompt::new(&mut input, &mut output)
    .required()
    .prompt("Say something (required): ");

assert_eq!(
    too_short.unwrap_err(),
    Error::Validation(ValidationError::Absent)
);
Source

pub fn send(&mut self) -> Result<String>

Send the request to the user, and get the response.

Halts exeution until input receives a new line character or an EOF.

§Examples
use trompt::Trompt;

let input = std::io::Cursor::new(b"bar");
let mut output = std::io::Cursor::new(Vec::new());

let response = Trompt::new(input, &mut output).message("foo").send();

assert_eq!(output.into_inner(), b"foo");
assert_eq!(response, Ok("bar".to_string()));
Source

pub fn prompt(&mut self, message: &str) -> Result<String>

A helper. Same as .message(message).send().

§Examples
use trompt::Trompt;

let input = std::io::Cursor::new(b"bar");
let mut output = std::io::Cursor::new(Vec::new());

let response = Trompt::new(input, &mut output).prompt("foo");

assert_eq!(output.into_inner(), b"foo");
assert_eq!(response, Ok("bar".to_string()));
Source

pub fn confirm(&mut self, message: &str) -> Result<bool>

A helper for retrieving confirmation from the user. Maps y and yes case insensitively to true and n and no to false.

§Examples
use trompt::Trompt;

let input = std::io::Cursor::new(b"YES");
let output = std::io::Cursor::new(Vec::new());

let result = Trompt::new(input, output).confirm("should I?");

assert_eq!(result.unwrap(), true);
Source§

impl Trompt<Stdin, Stdout>

Source

pub fn stdout() -> Trompt<Stdin, Stdout>

Start a new prompter from stdin that writes to stdout.

§Examples
use trompt::Trompt;

let _ = Trompt::stdout().prompt("This is stdout speaking: ");
Source§

impl Trompt<Stdin, Stderr>

Source

pub fn stderr() -> Trompt<Stdin, Stderr>

Start a new prompter from stdin that writes to stderr.

§Examples
use trompt::Trompt;

let _ = Trompt::stderr().prompt("This is stderr speaking: ");

Auto Trait Implementations§

§

impl<R, W> Freeze for Trompt<R, W>
where R: Freeze, W: Freeze,

§

impl<R, W> !RefUnwindSafe for Trompt<R, W>

§

impl<R, W> !Send for Trompt<R, W>

§

impl<R, W> !Sync for Trompt<R, W>

§

impl<R, W> Unpin for Trompt<R, W>
where R: Unpin, W: Unpin,

§

impl<R, W> !UnwindSafe for Trompt<R, W>

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.