@@ -62,32 +62,57 @@ enum State {
6262/// Ask the user a yes or no question on stdout, reading the reply from stdin.
6363///
6464/// Replies are delimited by newlines of any kind and must be one of '' (maps to
65- /// yes), 'y', 'yes', 'n', 'no', case insensitive. If the reply fails to parse,
65+ /// yes), 'y', 'yes', 'n', 'no', case- insensitive. If the reply fails to parse,
6666/// the question will be asked again ad infinitum.
6767///
6868/// # Examples
6969///
7070/// ```
71- /// # use std::{io, io::Read, str::from_utf8};
71+ /// # use std::{io, str::from_utf8};
7272/// use ask_cli::{ask, Answer};
7373///
7474/// assert!(matches!(
75- /// ask("Continue? [Y/n] ", &mut "y\n".as_bytes(), &mut io::sink()),
75+ /// ask(
76+ /// "Continue? [Y/n] ",
77+ /// Answer::Yes,
78+ /// &mut "y\n".as_bytes(),
79+ /// &mut io::sink()
80+ /// ),
7681/// Ok(Answer::Yes)
7782/// ));
7883/// assert!(matches!(
79- /// ask("Continue? [Y/n] ", &mut "n\n".as_bytes(), &mut io::sink()),
84+ /// ask(
85+ /// "Continue? [Y/n] ",
86+ /// Answer::Yes,
87+ /// &mut "n\n".as_bytes(),
88+ /// &mut io::sink()
89+ /// ),
8090/// Ok(Answer::No)
8191/// ));
8292/// assert!(matches!(
83- /// ask("Continue? [Y/n] ", &mut "".as_bytes(), &mut io::sink()),
93+ /// ask(
94+ /// "Continue? [Y/n] ",
95+ /// Answer::Yes,
96+ /// &mut "".as_bytes(),
97+ /// &mut io::sink()
98+ /// ),
8499/// Ok(Answer::Unknown)
85100/// ));
101+ /// assert!(matches!(
102+ /// ask(
103+ /// "Continue? [y/N] ",
104+ /// Answer::No,
105+ /// &mut "\n".as_bytes(),
106+ /// &mut io::sink()
107+ /// ),
108+ /// Ok(Answer::No)
109+ /// ));
86110///
87111/// // Here we use 3 different kinds of line endings
88112/// let mut stdout = Vec::new();
89- /// ask(
113+ /// let answer = ask(
90114/// "Continue? [Y/n] ",
115+ /// Answer::Yes,
91116/// &mut "a\nb\rc\r\nyes\n".as_bytes(),
92117/// &mut stdout,
93118/// )
@@ -96,13 +121,15 @@ enum State {
96121/// "Continue? [Y/n] Continue? [Y/n] Continue? [Y/n] Continue? [Y/n] ",
97122/// from_utf8(&stdout).unwrap()
98123/// );
124+ /// assert!(matches!(answer, Answer::Yes));
99125/// ```
100126///
101127/// # Errors
102128///
103129/// Underlying I/O errors are bubbled up.
104130pub fn ask < Q : AsRef < [ u8 ] > , In : Read , Out : Write > (
105131 question : Q ,
132+ default : Answer ,
106133 stdin : & mut In ,
107134 stdout : & mut Out ,
108135) -> Result < Answer , io:: Error > {
@@ -197,7 +224,8 @@ pub fn ask<Q: AsRef<[u8]>, In: Read, Out: Write>(
197224 let reply = & mut buf. filled_mut ( ) [ ..newline_index] ;
198225 reply. make_ascii_lowercase ( ) ;
199226 match & * reply {
200- b"" | b"y" | b"yes" => return Ok ( Answer :: Yes ) ,
227+ b"" => return Ok ( default) ,
228+ b"y" | b"yes" => return Ok ( Answer :: Yes ) ,
201229 b"n" | b"no" => return Ok ( Answer :: No ) ,
202230 _ => {
203231 consume_newline ! ( newline_index) ;
0 commit comments