use std::io::{self, IsTerminal as _};
use crumbkit::{Run, Yes};
use starmap::{Name, Secret};
use zeroize::Zeroizing;
pub(crate) trait Ask {
fn can_ask(&self) -> bool;
fn secret(&mut self, name: &Name) -> Option<Secret>;
fn save(&mut self, question: &str) -> bool;
}
#[derive(Debug)]
pub(crate) struct Terminal<'a> {
output: &'a mut Run,
interactive: bool,
}
impl<'a> Terminal<'a> {
pub(crate) fn new(output: &'a mut Run, interactive: bool) -> Self {
Self {
output,
interactive,
}
}
}
impl Ask for Terminal<'_> {
fn can_ask(&self) -> bool {
self.interactive
}
fn secret(&mut self, name: &Name) -> Option<Secret> {
let prompt = format!("{name} has no bind and no saved value. Type it (input is hidden): ");
let mut typed = Zeroizing::new(rpassword::prompt_password(prompt).ok()?);
if typed.is_empty() {
return None;
}
Some(Secret::new(std::mem::take(&mut *typed)))
}
fn save(&mut self, question: &str) -> bool {
self.output.confirm(Yes::default(), question).is_ok()
}
}
pub(crate) fn terminals() -> bool {
#[expect(
clippy::disallowed_methods,
reason = "starmap run asks for a secret only when a person sits at the terminal, and reads nothing here"
)]
let input = io::stdin().is_terminal();
#[expect(
clippy::disallowed_methods,
reason = "starmap run asks for a secret only when a person sits at the terminal, and writes nothing here"
)]
let error = io::stderr().is_terminal();
input && error
}