1use std::io::{self, BufRead, Write};
2
3use anyhow::{Context, Result};
4
5pub fn confirm(prompt: &str) -> Result<bool> {
6 print!("{prompt}");
7 io::stdout().flush().context("failed to flush stdout")?;
8
9 let mut answer = String::new();
10 io::stdin()
11 .lock()
12 .read_line(&mut answer)
13 .context("failed to read confirmation")?;
14
15 Ok(matches!(answer.trim(), "y" | "Y" | "yes" | "Yes" | "YES"))
16}
17
18pub fn pick(title: &str, options: &[String]) -> Result<Option<usize>> {
22 anstream::eprintln!("{title}");
23 for (index, option) in options.iter().enumerate() {
24 let number = crate::style::paint(crate::style::DIM, &format!("{}.", index + 1));
25 anstream::eprintln!(" {number} {option}");
26 }
27 eprint!("pick [1-{}]: ", options.len());
28 io::stderr().flush().context("failed to flush stderr")?;
29
30 let mut answer = String::new();
31 io::stdin()
32 .lock()
33 .read_line(&mut answer)
34 .context("failed to read choice")?;
35
36 Ok(answer
37 .trim()
38 .parse::<usize>()
39 .ok()
40 .filter(|choice| (1..=options.len()).contains(choice))
41 .map(|choice| choice - 1))
42}