use crate::error::{Error, Result};
use crate::style as s;
use std::io::{self, BufRead, Write};
pub fn is_interactive() -> bool {
#[cfg(unix)]
{
extern "C" {
fn isatty(fd: i32) -> i32;
}
unsafe { isatty(0) == 1 }
}
#[cfg(not(unix))]
{
true
}
}
fn require_tty() -> Result<()> {
if !is_interactive() {
return Err(Error::usage(
"this action needs an interactive terminal (stdin is not a tty)",
)
.note("pass the value as a flag/argument, or run without piping stdin"));
}
Ok(())
}
pub fn confirm(question: &str, default: bool) -> Result<bool> {
require_tty()?;
let hint = if default { "[Y/n]" } else { "[y/N]" };
loop {
print!("{} {} ", question, s::dim(hint));
io::stdout().flush().ok();
let line = read_line()?;
let ans = line.trim().to_lowercase();
match ans.as_str() {
"" => return Ok(default),
"y" | "yes" => return Ok(true),
"n" | "no" => return Ok(false),
_ => {
eprintln!("{}", s::dim("please answer y or n"));
}
}
}
}
pub fn text(prompt: &str, default: Option<&str>) -> Result<String> {
require_tty()?;
match default {
Some(d) => print!("{} {} ", prompt, s::dim(format!("({})", d))),
None => print!("{} ", prompt),
}
io::stdout().flush().ok();
let line = read_line()?;
let trimmed = line.trim_end_matches(['\n', '\r']);
if trimmed.is_empty() {
if let Some(d) = default {
return Ok(d.to_string());
}
}
Ok(trimmed.to_string())
}
pub fn password(prompt: &str) -> Result<String> {
require_tty()?;
print!("{} ", prompt);
io::stdout().flush().ok();
let pw = read_hidden()?;
println!();
Ok(pw)
}
pub fn select(prompt: &str, options: &[&str]) -> Result<usize> {
require_tty()?;
if options.is_empty() {
return Err(Error::msg("select called with no options"));
}
println!("{}", prompt);
for (i, opt) in options.iter().enumerate() {
println!(" {} {}", s::cyan(format!("{})", i + 1)), opt);
}
loop {
print!("{} ", s::dim(format!("choose 1-{}:", options.len())));
io::stdout().flush().ok();
let line = read_line()?;
match line.trim().parse::<usize>() {
Ok(n) if n >= 1 && n <= options.len() => return Ok(n - 1),
_ => eprintln!("{}", s::dim("invalid choice")),
}
}
}
fn read_line() -> Result<String> {
let mut line = String::new();
let stdin = io::stdin();
let n = stdin.lock().read_line(&mut line).map_err(Error::wrap)?;
if n == 0 {
return Err(Error::cancelled("input cancelled (EOF)"));
}
Ok(line)
}
#[cfg(unix)]
fn read_hidden() -> Result<String> {
use std::os::unix::io::AsRawFd;
#[repr(C)]
#[derive(Clone)]
struct Termios {
c_iflag: u32,
c_oflag: u32,
c_cflag: u32,
c_lflag: u32,
c_line: u8,
c_cc: [u8; 32],
c_ispeed: u32,
c_ospeed: u32,
}
extern "C" {
fn tcgetattr(fd: i32, termios: *mut Termios) -> i32;
fn tcsetattr(fd: i32, optional_actions: i32, termios: *const Termios) -> i32;
}
const ECHO: u32 = 0o0000010;
const TCSANOW: i32 = 0;
let fd = io::stdin().as_raw_fd();
let mut term = Termios {
c_iflag: 0,
c_oflag: 0,
c_cflag: 0,
c_lflag: 0,
c_line: 0,
c_cc: [0; 32],
c_ispeed: 0,
c_ospeed: 0,
};
unsafe {
if tcgetattr(fd, &mut term) != 0 {
return read_line().map(|l| l.trim_end_matches(['\n', '\r']).to_string());
}
}
let saved = term.clone();
term.c_lflag &= !ECHO;
unsafe {
tcsetattr(fd, TCSANOW, &term);
}
let result = read_line().map(|l| l.trim_end_matches(['\n', '\r']).to_string());
unsafe {
tcsetattr(fd, TCSANOW, &saved);
}
result
}
#[cfg(not(unix))]
fn read_hidden() -> Result<String> {
read_line().map(|l| l.trim_end_matches(['\n', '\r']).to_string())
}
pub fn number(prompt: &str, min: Option<i64>, max: Option<i64>) -> Result<i64> {
require_tty()?;
loop {
let mut hint = String::new();
match (min, max) {
(Some(lo), Some(hi)) => hint = format!("({}-{})", lo, hi),
(Some(lo), None) => hint = format!("(>= {})", lo),
(None, Some(hi)) => hint = format!("(<= {})", hi),
(None, None) => {}
}
if hint.is_empty() {
print!("{} ", prompt);
} else {
print!("{} {} ", prompt, s::dim(&hint));
}
io::stdout().flush().ok();
let line = read_line()?;
match line.trim().parse::<i64>() {
Ok(n) => {
if let Some(lo) = min {
if n < lo {
eprintln!("{}", s::dim("too small"));
continue;
}
}
if let Some(hi) = max {
if n > hi {
eprintln!("{}", s::dim("too large"));
continue;
}
}
return Ok(n);
}
Err(_) => eprintln!("{}", s::dim("please enter a number")),
}
}
}
pub fn multiselect(prompt: &str, options: &[&str]) -> Result<Vec<usize>> {
require_tty()?;
if options.is_empty() {
return Err(Error::msg("multiselect called with no options"));
}
println!("{}", prompt);
for (i, opt) in options.iter().enumerate() {
println!(" {} {}", s::cyan(format!("{})", i + 1)), opt);
}
loop {
print!(
"{} ",
s::dim(format!("choose 1-{} (comma/space separated):", options.len()))
);
io::stdout().flush().ok();
let line = read_line()?;
let trimmed = line.trim();
if trimmed.is_empty() {
return Ok(Vec::new());
}
let parts: Vec<&str> = trimmed
.split(|c: char| c == ',' || c.is_whitespace())
.filter(|s| !s.is_empty())
.collect();
let mut chosen = Vec::new();
let mut ok = true;
for p in parts {
match p.parse::<usize>() {
Ok(n) if n >= 1 && n <= options.len() => chosen.push(n - 1),
_ => {
ok = false;
break;
}
}
}
if ok {
chosen.sort_unstable();
chosen.dedup();
return Ok(chosen);
}
eprintln!("{}", s::dim("invalid selection"));
}
}