Skip to main content

luxid_cli/
prompt.rs

1//! Terminal questions for `luxid new`.
2//!
3//! Hand-rolled rather than pulling in a prompt crate. The questions are two
4//! short multiple-choice lists, and rolling them means full control over the
5//! part that actually matters: what happens when there is no terminal.
6//!
7//! A scaffolding tool that blocks on stdin inside a CI job, a Docker build or
8//! a shell pipeline is a scaffolding tool people stop trusting. Every prompt
9//! here is reachable only when [`is_interactive`] is true; otherwise the caller
10//! takes the default.
11
12use std::io::{self, BufRead, IsTerminal, Write};
13
14/// Whether there is a human at both ends.
15///
16/// Both streams are checked: stdout redirected to a file means the question
17/// would never be seen, even though stdin could still be answered.
18pub fn is_interactive() -> bool {
19    io::stdin().is_terminal() && io::stdout().is_terminal()
20}
21
22/// Ask a multiple-choice question, returning the index of the chosen option.
23///
24/// `options` is `(label, description)`. `default` is the index used when the
25/// answer is empty, which is what pressing Enter does.
26///
27/// Numbered rather than arrow-key driven: it works over ssh, in a dumb
28/// terminal, and inside editors that do not forward key events — and it can be
29/// answered by piping a number in, which arrow keys cannot.
30pub fn choose(question: &str, options: &[(&str, &str)], default: usize) -> usize {
31    let width = options
32        .iter()
33        .map(|(label, _)| label.len())
34        .max()
35        .unwrap_or(0);
36
37    loop {
38        println!();
39        println!("{question}");
40        println!();
41
42        for (index, (label, description)) in options.iter().enumerate() {
43            let marker = if index == default { " (default)" } else { "" };
44
45            println!("  {}) {label:width$}  {description}{marker}", index + 1);
46        }
47
48        println!();
49        print!("  [1-{}] ", options.len());
50        let _ = io::stdout().flush();
51
52        let mut answer = String::new();
53
54        // A closed stdin cannot be recovered from by asking again, which would
55        // spin forever. Take the default and move on.
56        if io::stdin().lock().read_line(&mut answer).unwrap_or(0) == 0 {
57            println!();
58            return default;
59        }
60
61        let answer = answer.trim();
62
63        if answer.is_empty() {
64            return default;
65        }
66
67        match answer.parse::<usize>() {
68            Ok(choice) if choice >= 1 && choice <= options.len() => return choice - 1,
69            _ => println!("\n  `{answer}` is not one of the options."),
70        }
71    }
72}