use super::edit::editor::{Assist, Outcome, no_assist, read_line};
use super::edit::history::{History, history_path, is_sensitive};
use std::fs::File;
use std::io::{BufRead, BufReader, IsTerminal, Write};
use std::os::fd::AsFd;
use std::path::PathBuf;
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
const DUMB_TERMS: &[&str] = &["dumb", "cons25", "emacs"];
#[derive(Debug, PartialEq, Eq)]
enum Mode {
Pipe,
Plain,
Edit { raw: bool },
}
pub(crate) struct Input {
mode: Mode,
history: History,
history_file: Option<PathBuf>,
}
impl Input {
pub(crate) fn open() -> Input {
let mut input =
Input { mode: Mode::detect(), history: History::default(), history_file: None };
if input.keeps_history() {
input.history_file = history_path(|k: &str| std::env::var_os(k));
if let Some(path) = &input.history_file {
input.history.load(path);
}
}
input
}
pub(crate) fn on_a_terminal(&self) -> bool {
std::io::stdin().is_terminal()
}
pub(crate) fn read_secret(prompt: &[u8]) -> Option<Vec<u8>> {
let outcome = match Mode::detect() {
Mode::Pipe => plain_line(),
Mode::Plain => {
super::send::write_out(prompt);
plain_line()
}
Mode::Edit { raw } => {
edit_line(prompt, &History::default(), &no_assist(), raw, Echo::Masked)
}
};
match outcome {
Outcome::Line(line) => Some(line),
Outcome::Eof | Outcome::Interrupted => None,
}
}
pub(crate) fn keeps_history(&self) -> bool {
self.mode != Mode::Pipe
}
pub(crate) fn read(&mut self, prompt: &[u8], assist: &Assist<'_>) -> Outcome {
match self.mode {
Mode::Pipe => plain_line(),
Mode::Plain => {
super::send::write_out(prompt);
plain_line()
}
Mode::Edit { raw } => self.edit(prompt, assist, raw),
}
}
fn edit(&mut self, prompt: &[u8], assist: &Assist<'_>, raw: bool) -> Outcome {
edit_line(prompt, &self.history, assist, raw, Echo::Plain)
}
pub(crate) fn remember(&mut self, line: &[u8], argv: &[Vec<u8>]) {
if !self.keeps_history() {
return;
}
let sensitive = is_sensitive(argv);
self.history.add(line, sensitive);
if !sensitive && let Some(path) = &self.history_file {
let _ = self.history.save(path);
}
}
}
impl Mode {
fn detect() -> Mode {
let stdin_tty = std::io::stdin().is_terminal();
let faketty = std::env::var_os("FAKETTY_WITH_PROMPT").is_some();
let dumb = std::env::var("TERM")
.is_ok_and(|t| DUMB_TERMS.iter().any(|d| t.eq_ignore_ascii_case(d)));
match (stdin_tty || faketty, dumb) {
(false, _) => Mode::Pipe,
(true, true) => Mode::Plain,
(true, false) => Mode::Edit { raw: stdin_tty && !faketty },
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Echo {
Plain,
Masked,
}
fn edit_line(
prompt: &[u8],
history: &History,
assist: &Assist<'_>,
raw: bool,
echo: Echo,
) -> Outcome {
let _raw = raw.then(|| kevy_sys::RawMode::enable(0).ok()).flatten();
let cols = if raw { kevy_sys::terminal_columns(1).map_or(80, usize::from) } else { 80 };
let mut stdout = std::io::stdout().lock();
let mut typed = typed();
let Some(stdin) = typed.as_mut() else { return Outcome::Eof };
read_line(stdin, &mut stdout, prompt, history, assist, cols, echo == Echo::Masked)
.unwrap_or(Outcome::Eof)
}
fn plain_line() -> Outcome {
let mut line = Vec::new();
let mut typed = typed();
let Some(stdin) = typed.as_mut() else { return Outcome::Eof };
match stdin.read_until(b'\n', &mut line) {
Ok(0) | Err(_) => Outcome::Eof,
Ok(_) => {
if line.last() == Some(&b'\n') {
line.pop();
}
let _ = std::io::stdout().flush(); Outcome::Line(line)
}
}
}
static TYPED: OnceLock<Mutex<Option<BufReader<File>>>> = OnceLock::new();
fn typed() -> MutexGuard<'static, Option<BufReader<File>>> {
TYPED
.get_or_init(|| {
let fd = std::io::stdin().as_fd().try_clone_to_owned().ok();
Mutex::new(fd.map(|fd| BufReader::new(File::from(fd))))
})
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn read_all_typed() -> std::io::Result<Vec<u8>> {
let mut all = Vec::new();
if let Some(stdin) = typed().as_mut() {
std::io::Read::read_to_end(stdin, &mut all)?;
}
Ok(all)
}
pub(crate) fn typed_ahead() -> bool {
typed().as_ref().is_some_and(|r| !r.buffer().is_empty())
}