|
1
|
//! Interactive prompts, kept in one place so every command fails the same way |
|
2
|
//! when stdin isn't a TTY (CI, pipes) instead of hanging. |
|
3
|
|
|
4
|
use { |
|
5
|
anyhow::{anyhow, Result}, |
|
6
|
console::Term, |
|
7
|
dialoguer::{theme::ColorfulTheme, Confirm, Input, Password}, |
|
8
|
}; |
|
9
|
|
|
10
|
fn require_tty(what: &str) -> Result<()> { |
|
11
|
if Term::stdout().features().is_attended() { |
|
12
|
Ok(()) |
|
13
|
} else { |
|
14
|
Err(anyhow!( |
|
15
|
"{what} requires an interactive terminal. Provide it via a flag or environment \ |
|
16
|
variable instead when running non-interactively." |
|
17
|
)) |
|
18
|
} |
|
19
|
} |
|
20
|
|
|
21
|
pub fn text(label: &str) -> Result<String> { |
|
22
|
require_tty(label)?; |
|
23
|
Ok(Input::with_theme(&ColorfulTheme::default()) |
|
24
|
.with_prompt(label) |
|
25
|
.interact_text()?) |
|
26
|
} |
|
27
|
|
|
28
|
pub fn password(label: &str) -> Result<String> { |
|
29
|
require_tty(label)?; |
|
30
|
Ok(Password::with_theme(&ColorfulTheme::default()) |
|
31
|
.with_prompt(label) |
|
32
|
.interact()?) |
|
33
|
} |
|
34
|
|
|
35
|
/// A new password, asked for twice. |
|
36
|
pub fn new_password(label: &str) -> Result<String> { |
|
37
|
require_tty(label)?; |
|
38
|
Ok(Password::with_theme(&ColorfulTheme::default()) |
|
39
|
.with_prompt(label) |
|
40
|
.with_confirmation("Repeat the password", "The passwords do not match.") |
|
41
|
.interact()?) |
|
42
|
} |
|
43
|
|
|
44
|
/// A yes/no confirmation. Non-interactive callers should not reach this at |
|
45
|
/// all for destructive actions — check `--yes` first — but reads default to |
|
46
|
/// `default` here rather than erroring, since a TTY-less "confirm the details |
|
47
|
/// I already showed you" is reasonable to skip. |
|
48
|
pub fn confirm(label: &str, default: bool) -> Result<bool> { |
|
49
|
if !Term::stdout().features().is_attended() { |
|
50
|
return Ok(default); |
|
51
|
} |
|
52
|
Ok(Confirm::with_theme(&ColorfulTheme::default()) |
|
53
|
.with_prompt(label) |
|
54
|
.default(default) |
|
55
|
.interact()?) |
|
56
|
} |