use std::io::{BufRead, Write};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Ask {
pub question: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub people: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub choices: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub back_to: Vec<String>,
}
impl Ask {
pub fn addressed(&self) -> String {
if self.people.is_empty() {
self.question.clone()
} else {
format!("For {}: {}", self.people.join(" or "), self.question)
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
Yes,
No {
points: String,
back: Vec<String>,
},
}
pub trait Person {
fn tell(&mut self, text: &str);
fn answer(&mut self, ask: &Ask) -> Option<String>;
fn approve(&mut self, ask: &Ask) -> Option<Verdict>;
fn decide(&mut self, question: &str) -> Option<bool> {
let ask = Ask {
question: question.to_owned(),
..Ask::default()
};
self.approve(&ask).map(|verdict| verdict == Verdict::Yes)
}
fn choose(&mut self, question: &str, options: &[String]) -> Option<usize> {
let ask = Ask {
question: question.to_owned(),
choices: options.to_vec(),
..Ask::default()
};
let answer = self.answer(&ask)?;
options.iter().position(|option| *option == answer.trim())
}
}
pub struct Terminal<R, W> {
input: R,
output: W,
}
impl<R: BufRead, W: Write> Terminal<R, W> {
pub fn new(input: R, output: W) -> Self {
Self { input, output }
}
fn line(&mut self, prompt: &str) -> Option<String> {
let _ = write!(self.output, "{prompt}");
let _ = self.output.flush();
let mut line = String::new();
match self.input.read_line(&mut line) {
Ok(0) | Err(_) => {
let _ = writeln!(self.output);
None
}
Ok(_) => Some(line.trim().to_owned()),
}
}
fn yes_or_no(&mut self, question: &str) -> Option<bool> {
let mut prompt = format!("{question} (yes/no) ");
loop {
let reply = self.line(&prompt)?.to_lowercase();
match reply.as_str() {
"y" | "yes" => return Some(true),
"n" | "no" => return Some(false),
_ => "Please answer yes or no: ".clone_into(&mut prompt),
}
}
}
}
impl<R: BufRead, W: Write> Person for Terminal<R, W> {
fn tell(&mut self, text: &str) {
let _ = writeln!(self.output, "{text}");
}
fn answer(&mut self, ask: &Ask) -> Option<String> {
if ask.choices.is_empty() {
return self.line(&format!("{}\n> ", ask.addressed()));
}
let choices = ask.choices.join(", ");
let mut prompt = format!("{}\nAnswer one of: {choices}\n> ", ask.addressed());
loop {
let reply = self.line(&prompt)?;
if ask.choices.contains(&reply) {
return Some(reply);
}
prompt = format!("Please answer one of: {choices}\n> ");
}
}
fn approve(&mut self, ask: &Ask) -> Option<Verdict> {
if self.yes_or_no(&ask.addressed())? {
return Some(Verdict::Yes);
}
let points = self.line("What is wrong with it?\n> ").unwrap_or_default();
let mut back = Vec::new();
if !ask.back_to.is_empty() {
let offered = ask.back_to.join(", ");
let mut prompt =
format!("Send it back to which step? ({offered}; leave empty for this one)\n> ");
loop {
let reply = self.line(&prompt).unwrap_or_default();
let named: Vec<String> = reply
.split([',', ' '])
.map(str::trim)
.filter(|id| !id.is_empty())
.map(str::to_owned)
.collect();
if named.iter().all(|id| ask.back_to.contains(id)) {
back = named;
break;
}
prompt = format!("Please name some of: {offered}, or leave it empty\n> ");
}
}
Some(Verdict::No { points, back })
}
fn decide(&mut self, question: &str) -> Option<bool> {
self.yes_or_no(question)
}
fn choose(&mut self, question: &str, options: &[String]) -> Option<usize> {
let _ = writeln!(self.output, "{question}");
for (number, option) in options.iter().enumerate() {
let _ = writeln!(self.output, " {}. {option}", number + 1);
}
let mut prompt = "> ".to_owned();
loop {
let reply = self.line(&prompt)?;
let picked = reply
.parse::<usize>()
.ok()
.and_then(|number| number.checked_sub(1))
.filter(|index| *index < options.len())
.or_else(|| options.iter().position(|option| *option == reply));
if picked.is_some() {
return picked;
}
prompt = format!("Please answer a number from 1 to {}: ", options.len());
}
}
}
#[cfg(test)]
mod tests {
use super::{Ask, Person, Terminal, Verdict};
fn ask(question: &str) -> Ask {
Ask {
question: question.to_owned(),
..Ask::default()
}
}
#[test]
fn a_terminal_person_answers_by_lines() {
let mut output = Vec::new();
let mut person = Terminal::new("Ana\nmaybe\nno\ntoo short\nYES\n".as_bytes(), &mut output);
assert_eq!(person.answer(&ask("Who?")).as_deref(), Some("Ana"));
assert_eq!(
person.approve(&ask("Good?")),
Some(Verdict::No {
points: "too short".to_owned(),
back: Vec::new()
})
);
assert_eq!(person.decide("Go on?"), Some(true));
assert_eq!(person.decide("Again?"), None);
let said = String::from_utf8(output).expect("text");
assert!(said.contains("Please answer yes or no"), "{said}");
}
#[test]
fn a_terminal_person_picks_and_sends_back() {
let mut output = Vec::new();
let input = "water\ntea\nno\nwrong\nnope\nintro, numbers\n2\n";
let mut person = Terminal::new(input.as_bytes(), &mut output);
let tea = Ask {
question: "Which?".to_owned(),
people: vec!["ana".to_owned(), "bo".to_owned()],
choices: vec!["tea".to_owned(), "coffee".to_owned()],
back_to: Vec::new(),
};
let report = Ask {
back_to: vec!["intro".to_owned(), "numbers".to_owned()],
..ask("Right?")
};
assert_eq!(person.answer(&tea).as_deref(), Some("tea"));
assert_eq!(
person.approve(&report),
Some(Verdict::No {
points: "wrong".to_owned(),
back: vec!["intro".to_owned(), "numbers".to_owned()]
})
);
let options = ["wait".to_owned(), "go on".to_owned()];
assert_eq!(person.choose("Now?", &options), Some(1));
let said = String::from_utf8(output).expect("text");
assert!(said.contains("For ana or bo: Which?"), "{said}");
assert!(said.contains("Please answer one of: tea, coffee"), "{said}");
assert!(
said.contains("Please name some of: intro, numbers"),
"{said}"
);
}
}