oxedyne/fe2o3/fe2o3_syntax/src/cli/interactive.rs
5.2 KiB, 1 run
created by r1870400018:65722, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Whether the process has an interactive terminal to ask on, and a yes/no question that |
| 2 | //! honours the answer: no tty means no prompt, ever, rather than a question nobody can see. |
| 3 | |
| 4 | use oxedyne_fe2o3_core::prelude::*; |
| 5 | |
| 6 | use std::io::{BufRead, IsTerminal, Write}; |
| 7 | |
| 8 | /// A yes/no answer. |
| 9 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 10 | pub enum Answer { Yes, No } |
| 11 | |
| 12 | /// Is stdin a terminal a person could type an answer into? |
| 13 | pub fn stdin_is_tty() -> bool { std::io::stdin().is_terminal() } |
| 14 | |
| 15 | /// Is stdout a terminal worth printing a prompt or colour to? |
| 16 | pub fn stdout_is_tty() -> bool { std::io::stdout().is_terminal() } |
| 17 | |
| 18 | /// Can the terminal actually be used interactively: a tty, and `$TERM` not `"dumb"`? This is |
| 19 | /// the same test git applies before trusting `$VISUAL`. |
| 20 | pub fn terminal_capable(tty: bool, term: Option<&str>) -> bool { |
| 21 | tty && term.map_or(true, |t| t != "dumb") |
| 22 | } |
| 23 | |
| 24 | /// Asks `question` on `output` with a `[Y/n]`/`[y/N]` hint for `default`, and reads one line of |
| 25 | /// an answer from `input`. |
| 26 | /// |
| 27 | /// Returns `Ok(None)` without writing anything when `is_tty` is false: there is nobody to |
| 28 | /// answer, so the caller decides what "could not ask" means for it -- refuse outright, or take |
| 29 | /// the default silently. An empty line (Enter alone) or a closed input takes the default; an |
| 30 | /// unrecognised word re-prompts up to `retries` times before falling back to the default too, so |
| 31 | /// a script feeding nonsense on a claimed tty cannot hang the caller forever. |
| 32 | pub fn ask_yes_no<R, W>( |
| 33 | question: &str, |
| 34 | default: Answer, |
| 35 | is_tty: bool, |
| 36 | retries: u8, |
| 37 | input: &mut R, |
| 38 | output: &mut W, |
| 39 | ) -> Outcome<Option<Answer>> |
| 40 | where |
| 41 | R: BufRead, |
| 42 | W: Write, |
| 43 | { |
| 44 | if !is_tty { |
| 45 | return Ok(None); |
| 46 | } |
| 47 | let hint = match default { |
| 48 | Answer::Yes => "[Y/n]", |
| 49 | Answer::No => "[y/N]", |
| 50 | }; |
| 51 | for _ in 0..=retries { |
| 52 | res!(write!(output, "{} {} ", question, hint), IO, Write); |
| 53 | res!(output.flush(), IO, Write); |
| 54 | let mut line = String::new(); |
| 55 | let n = res!(input.read_line(&mut line), IO, Read); |
| 56 | if n == 0 { |
| 57 | return Ok(Some(default)); // input closed; nothing more will ever arrive |
| 58 | } |
| 59 | let word = line.trim(); |
| 60 | if word.is_empty() { |
| 61 | return Ok(Some(default)); |
| 62 | } |
| 63 | match parse_yes_no(word) { |
| 64 | Some(answer) => return Ok(Some(answer)), |
| 65 | None => res!(writeln!(output, "Please answer y or n."), IO, Write), |
| 66 | } |
| 67 | } |
| 68 | Ok(Some(default)) |
| 69 | } |
| 70 | |
| 71 | fn parse_yes_no(word: &str) -> Option<Answer> { |
| 72 | match word.to_ascii_lowercase().as_str() { |
| 73 | "y" | "yes" => Some(Answer::Yes), |
| 74 | "n" | "no" => Some(Answer::No), |
| 75 | _ => None, |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | #[cfg(test)] |
| 80 | mod tests { |
| 81 | use super::*; |
| 82 | |
| 83 | use std::io::Cursor; |
| 84 | |
| 85 | #[test] |
| 86 | fn no_tty_never_prompts_and_returns_none_00() -> Outcome<()> { |
| 87 | let mut input = Cursor::new(b"y\n".to_vec()); |
| 88 | let mut output = Vec::new(); |
| 89 | let answer = res!(ask_yes_no("Proceed?", Answer::No, false, 2, &mut input, &mut output)); |
| 90 | req!(answer.is_none(), true); |
| 91 | req!(output.len(), 0); // nothing printed: nobody could have read it |
| 92 | Ok(()) |
| 93 | } |
| 94 | |
| 95 | #[test] |
| 96 | fn tty_reads_y_as_yes_00() -> Outcome<()> { |
| 97 | let mut input = Cursor::new(b"y\n".to_vec()); |
| 98 | let mut output = Vec::new(); |
| 99 | let answer = res!(ask_yes_no("Proceed?", Answer::No, true, 2, &mut input, &mut output)); |
| 100 | req!(answer, Some(Answer::Yes)); |
| 101 | Ok(()) |
| 102 | } |
| 103 | |
| 104 | #[test] |
| 105 | fn tty_reads_full_words_case_insensitively_01() -> Outcome<()> { |
| 106 | let mut input = Cursor::new(b"NO\n".to_vec()); |
| 107 | let mut output = Vec::new(); |
| 108 | let answer = res!(ask_yes_no("Proceed?", Answer::Yes, true, 2, &mut input, &mut output)); |
| 109 | req!(answer, Some(Answer::No)); |
| 110 | Ok(()) |
| 111 | } |
| 112 | |
| 113 | #[test] |
| 114 | fn tty_empty_line_takes_the_default_02() -> Outcome<()> { |
| 115 | let mut input = Cursor::new(b"\n".to_vec()); |
| 116 | let mut output = Vec::new(); |
| 117 | let answer = res!(ask_yes_no("Proceed?", Answer::No, true, 2, &mut input, &mut output)); |
| 118 | req!(answer, Some(Answer::No)); |
| 119 | let printed = String::from_utf8_lossy(&output); |
| 120 | req!(printed.contains("[y/N]"), true); |
| 121 | Ok(()) |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn tty_closed_input_takes_the_default_03() -> Outcome<()> { |
| 126 | let mut input = Cursor::new(Vec::new()); // EOF straight away |
| 127 | let mut output = Vec::new(); |
| 128 | let answer = res!(ask_yes_no("Proceed?", Answer::Yes, true, 2, &mut input, &mut output)); |
| 129 | req!(answer, Some(Answer::Yes)); |
| 130 | Ok(()) |
| 131 | } |
| 132 | |
| 133 | #[test] |
| 134 | fn tty_reprompts_on_nonsense_then_reads_the_next_line_04() -> Outcome<()> { |
| 135 | let mut input = Cursor::new(b"maybe\nyes\n".to_vec()); |
| 136 | let mut output = Vec::new(); |
| 137 | let answer = res!(ask_yes_no("Proceed?", Answer::No, true, 2, &mut input, &mut output)); |
| 138 | req!(answer, Some(Answer::Yes)); |
| 139 | let printed = String::from_utf8_lossy(&output); |
| 140 | req!(printed.contains("Please answer y or n."), true); |
| 141 | Ok(()) |
| 142 | } |
| 143 | |
| 144 | #[test] |
| 145 | fn tty_exhausted_retries_on_nonsense_takes_the_default_05() -> Outcome<()> { |
| 146 | let mut input = Cursor::new(b"maybe\nnope-not-that-either\nstill-no\n".to_vec()); |
| 147 | let mut output = Vec::new(); |
| 148 | let answer = res!(ask_yes_no("Proceed?", Answer::No, true, 2, &mut input, &mut output)); |
| 149 | req!(answer, Some(Answer::No)); |
| 150 | Ok(()) |
| 151 | } |
| 152 | |
| 153 | #[test] |
| 154 | fn terminal_capable_rejects_dumb_and_no_tty_06() -> Outcome<()> { |
| 155 | req!(terminal_capable(true, None), true); |
| 156 | req!(terminal_capable(true, Some("xterm-256color")), true); |
| 157 | req!(terminal_capable(true, Some("dumb")), false); |
| 158 | req!(terminal_capable(false, Some("xterm-256color")), false); |
| 159 | Ok(()) |
| 160 | } |
| 161 | } |