use std::{
io::{BufRead, IsTerminal},
os::fd::RawFd,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NoTerminal {
Stdin,
Stderr,
Stdout,
}
impl std::fmt::Display for NoTerminal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Stdin => "there is no terminal to ask on",
Self::Stderr => "stderr, where haest asks, is not a terminal",
Self::Stdout => "stdout, where haest asks with --json, is a file",
})
}
}
pub(crate) fn interactive(json: bool) -> Result<(), NoTerminal> {
if !std::io::stdin().is_terminal() {
Err(NoTerminal::Stdin)
} else if json && crate::render::is_a_file(&std::io::stdout()) {
Err(NoTerminal::Stdout)
} else if !json && !std::io::stderr().is_terminal() {
Err(NoTerminal::Stderr)
} else {
Ok(())
}
}
struct Withdraw(Arc<AtomicBool>);
impl Drop for Withdraw {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
pub(crate) async fn read_answer() -> Option<String> {
drop_typed_ahead();
let stop = Arc::new(AtomicBool::new(false));
let _withdraw = Withdraw(stop.clone());
tokio::task::spawn_blocking(move || read_line_until(&stop))
.await
.ok()
.flatten()
}
fn read_one() -> Option<String> {
let mut line = String::new();
match std::io::stdin().lock().read_line(&mut line) {
Ok(0) | Err(_) => None,
Ok(_) => Some(line),
}
}
fn read_line_until(stop: &AtomicBool) -> Option<String> {
if std::io::stdin().is_terminal() {
terminal_line(libc::STDIN_FILENO, stop)
} else if readable(libc::STDIN_FILENO, stop) {
read_one()
} else {
None
}
}
fn readable(fd: RawFd, stop: &AtomicBool) -> bool {
let mut pollfd = libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
};
while !stop.load(Ordering::Relaxed) {
#[expect(unsafe_code, reason = "poll(2) waits on stdin without taking it")]
let ready = unsafe { libc::poll(&raw mut pollfd, 1, 100) };
if ready > 0 {
return true;
}
let interrupted = std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted;
if ready < 0 && !interrupted {
return false;
}
}
false
}
fn terminal_line(fd: RawFd, stop: &AtomicBool) -> Option<String> {
let mut line = Vec::new();
while line.last() != Some(&b'\n') {
if !readable(fd, stop) {
return None;
}
let mut byte = 0_u8;
#[expect(
unsafe_code,
reason = "read(2) of one byte; std's Stdin would buffer what follows"
)]
let n = unsafe { libc::read(fd, (&raw mut byte).cast(), 1) };
match n {
1 => line.push(byte),
0 if line.is_empty() => return None,
0 => break,
_ => {
let kind = std::io::Error::last_os_error().kind();
if !matches!(
kind,
std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock
) {
return None;
}
}
}
}
Some(String::from_utf8_lossy(&line).into_owned())
}
fn drop_typed_ahead() {
if std::io::stdin().is_terminal() {
drop_typed_ahead_on(libc::STDIN_FILENO);
}
}
fn drop_typed_ahead_on(fd: RawFd) {
#[expect(unsafe_code, reason = "tcflush(3) drops a terminal's unread input")]
unsafe {
libc::tcflush(fd, libc::TCIFLUSH);
}
}
#[cfg(test)]
mod tests;