ask

Function ask 

Source
pub fn ask<Q: AsRef<[u8]>, In: Read, Out: Write>(
    question: Q,
    default: Answer,
    stdin: &mut In,
    stdout: &mut Out,
) -> Result<Answer, Error>
Expand description

Ask the user a yes or no question on stdout, reading the reply from stdin.

Replies are delimited by newlines of any kind and must be one of ‘’ (maps to yes), ‘y’, ‘yes’, ‘n’, ‘no’, case-insensitive. If the reply fails to parse, the question will be asked again ad infinitum.

§Examples

use ask_cli::{ask, Answer};

assert!(matches!(
    ask(
        "Continue? [Y/n] ",
        Answer::Yes,
        &mut "y\n".as_bytes(),
        &mut io::sink()
    ),
    Ok(Answer::Yes)
));
assert!(matches!(
    ask(
        "Continue? [Y/n] ",
        Answer::Yes,
        &mut "n\n".as_bytes(),
        &mut io::sink()
    ),
    Ok(Answer::No)
));
assert!(matches!(
    ask(
        "Continue? [Y/n] ",
        Answer::Yes,
        &mut "".as_bytes(),
        &mut io::sink()
    ),
    Ok(Answer::Unknown)
));
assert!(matches!(
    ask(
        "Continue? [y/N] ",
        Answer::No,
        &mut "\n".as_bytes(),
        &mut io::sink()
    ),
    Ok(Answer::No)
));

// Here we use 3 different kinds of line endings
let mut stdout = Vec::new();
let answer = ask(
    "Continue? [Y/n] ",
    Answer::Yes,
    &mut "a\nb\rc\r\nyes\n".as_bytes(),
    &mut stdout,
)
.unwrap();
assert_eq!(
    "Continue? [Y/n] Continue? [Y/n] Continue? [Y/n] Continue? [Y/n] ",
    from_utf8(&stdout).unwrap()
);
assert!(matches!(answer, Answer::Yes));

§Errors

Underlying I/O errors are bubbled up.