1use std::io::{BufRead, Write};
4
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
9pub struct Ask {
10 pub question: String,
12 #[serde(default, skip_serializing_if = "Vec::is_empty")]
14 pub people: Vec<String>,
15 #[serde(default, skip_serializing_if = "Vec::is_empty")]
17 pub choices: Vec<String>,
18 #[serde(default, skip_serializing_if = "Vec::is_empty")]
20 pub back_to: Vec<String>,
21}
22
23impl Ask {
24 pub fn addressed(&self) -> String {
26 if self.people.is_empty() {
27 self.question.clone()
28 } else {
29 format!("For {}: {}", self.people.join(" or "), self.question)
30 }
31 }
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
36pub enum Verdict {
37 Yes,
39 No {
41 points: String,
43 back: Vec<String>,
46 },
47}
48
49pub trait Person {
51 fn tell(&mut self, text: &str);
53
54 fn answer(&mut self, ask: &Ask) -> Option<String>;
56
57 fn approve(&mut self, ask: &Ask) -> Option<Verdict>;
59
60 fn decide(&mut self, question: &str) -> Option<bool> {
62 let ask = Ask {
63 question: question.to_owned(),
64 ..Ask::default()
65 };
66 self.approve(&ask).map(|verdict| verdict == Verdict::Yes)
67 }
68
69 fn choose(&mut self, question: &str, options: &[String]) -> Option<usize> {
71 let ask = Ask {
72 question: question.to_owned(),
73 choices: options.to_vec(),
74 ..Ask::default()
75 };
76 let answer = self.answer(&ask)?;
77 options.iter().position(|option| *option == answer.trim())
78 }
79}
80
81pub struct Terminal<R, W> {
83 input: R,
84 output: W,
85}
86
87impl<R: BufRead, W: Write> Terminal<R, W> {
88 pub fn new(input: R, output: W) -> Self {
90 Self { input, output }
91 }
92
93 fn line(&mut self, prompt: &str) -> Option<String> {
94 let _ = write!(self.output, "{prompt}");
95 let _ = self.output.flush();
96 let mut line = String::new();
97 match self.input.read_line(&mut line) {
98 Ok(0) | Err(_) => {
99 let _ = writeln!(self.output);
100 None
101 }
102 Ok(_) => Some(line.trim().to_owned()),
103 }
104 }
105
106 fn yes_or_no(&mut self, question: &str) -> Option<bool> {
107 let mut prompt = format!("{question} (yes/no) ");
108 loop {
109 let reply = self.line(&prompt)?.to_lowercase();
110 match reply.as_str() {
111 "y" | "yes" => return Some(true),
112 "n" | "no" => return Some(false),
113 _ => "Please answer yes or no: ".clone_into(&mut prompt),
114 }
115 }
116 }
117}
118
119impl<R: BufRead, W: Write> Person for Terminal<R, W> {
120 fn tell(&mut self, text: &str) {
121 let _ = writeln!(self.output, "{text}");
122 }
123
124 fn answer(&mut self, ask: &Ask) -> Option<String> {
125 if ask.choices.is_empty() {
126 return self.line(&format!("{}\n> ", ask.addressed()));
127 }
128 let choices = ask.choices.join(", ");
129 let mut prompt = format!("{}\nAnswer one of: {choices}\n> ", ask.addressed());
130 loop {
131 let reply = self.line(&prompt)?;
132 if ask.choices.contains(&reply) {
133 return Some(reply);
134 }
135 prompt = format!("Please answer one of: {choices}\n> ");
136 }
137 }
138
139 fn approve(&mut self, ask: &Ask) -> Option<Verdict> {
140 if self.yes_or_no(&ask.addressed())? {
141 return Some(Verdict::Yes);
142 }
143 let points = self.line("What is wrong with it?\n> ").unwrap_or_default();
144 let mut back = Vec::new();
145 if !ask.back_to.is_empty() {
146 let offered = ask.back_to.join(", ");
147 let mut prompt =
148 format!("Send it back to which step? ({offered}; leave empty for this one)\n> ");
149 loop {
150 let reply = self.line(&prompt).unwrap_or_default();
151 let named: Vec<String> = reply
152 .split([',', ' '])
153 .map(str::trim)
154 .filter(|id| !id.is_empty())
155 .map(str::to_owned)
156 .collect();
157 if named.iter().all(|id| ask.back_to.contains(id)) {
158 back = named;
159 break;
160 }
161 prompt = format!("Please name some of: {offered}, or leave it empty\n> ");
162 }
163 }
164 Some(Verdict::No { points, back })
165 }
166
167 fn decide(&mut self, question: &str) -> Option<bool> {
168 self.yes_or_no(question)
169 }
170
171 fn choose(&mut self, question: &str, options: &[String]) -> Option<usize> {
172 let _ = writeln!(self.output, "{question}");
173 for (number, option) in options.iter().enumerate() {
174 let _ = writeln!(self.output, " {}. {option}", number + 1);
175 }
176 let mut prompt = "> ".to_owned();
177 loop {
178 let reply = self.line(&prompt)?;
179 let picked = reply
180 .parse::<usize>()
181 .ok()
182 .and_then(|number| number.checked_sub(1))
183 .filter(|index| *index < options.len())
184 .or_else(|| options.iter().position(|option| *option == reply));
185 if picked.is_some() {
186 return picked;
187 }
188 prompt = format!("Please answer a number from 1 to {}: ", options.len());
189 }
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use super::{Ask, Person, Terminal, Verdict};
196
197 fn ask(question: &str) -> Ask {
198 Ask {
199 question: question.to_owned(),
200 ..Ask::default()
201 }
202 }
203
204 #[test]
205 fn a_terminal_person_answers_by_lines() {
206 let mut output = Vec::new();
207 let mut person = Terminal::new("Ana\nmaybe\nno\ntoo short\nYES\n".as_bytes(), &mut output);
208
209 assert_eq!(person.answer(&ask("Who?")).as_deref(), Some("Ana"));
210 assert_eq!(
211 person.approve(&ask("Good?")),
212 Some(Verdict::No {
213 points: "too short".to_owned(),
214 back: Vec::new()
215 })
216 );
217 assert_eq!(person.decide("Go on?"), Some(true));
218 assert_eq!(person.decide("Again?"), None);
219 let said = String::from_utf8(output).expect("text");
220 assert!(said.contains("Please answer yes or no"), "{said}");
221 }
222
223 #[test]
224 fn a_terminal_person_picks_and_sends_back() {
225 let mut output = Vec::new();
226 let input = "water\ntea\nno\nwrong\nnope\nintro, numbers\n2\n";
227 let mut person = Terminal::new(input.as_bytes(), &mut output);
228 let tea = Ask {
229 question: "Which?".to_owned(),
230 people: vec!["ana".to_owned(), "bo".to_owned()],
231 choices: vec!["tea".to_owned(), "coffee".to_owned()],
232 back_to: Vec::new(),
233 };
234 let report = Ask {
235 back_to: vec!["intro".to_owned(), "numbers".to_owned()],
236 ..ask("Right?")
237 };
238
239 assert_eq!(person.answer(&tea).as_deref(), Some("tea"));
240 assert_eq!(
241 person.approve(&report),
242 Some(Verdict::No {
243 points: "wrong".to_owned(),
244 back: vec!["intro".to_owned(), "numbers".to_owned()]
245 })
246 );
247 let options = ["wait".to_owned(), "go on".to_owned()];
248 assert_eq!(person.choose("Now?", &options), Some(1));
249 let said = String::from_utf8(output).expect("text");
250 assert!(said.contains("For ana or bo: Which?"), "{said}");
251 assert!(said.contains("Please answer one of: tea, coffee"), "{said}");
252 assert!(
253 said.contains("Please name some of: intro, numbers"),
254 "{said}"
255 );
256 }
257}