fix: check if stdout is a tty before writing to it (#7)

This commit is contained in:
Austin Schey
2025-05-18 06:43:09 -07:00
committed by GitHub
parent b7f6c327a6
commit a302bf2b6d
2 changed files with 28 additions and 22 deletions

View File

@@ -62,16 +62,15 @@ impl io::Write for FileDescriptor {
}
fn open_pty() -> io::Result<(FileDescriptor, FileDescriptor)> {
let (read, write) = if io::stdin().is_terminal() {
(FileDescriptor::STDIN, FileDescriptor::STDOUT)
let read = if io::stdin().is_terminal() {
FileDescriptor::STDIN
} else {
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")?;
let read = FileDescriptor::Owned(file.into());
let write = read.try_clone()?;
(read, write)
open_dev_tty()?
};
let write = if io::stdout().is_terminal() {
FileDescriptor::STDOUT
} else {
open_dev_tty()?
};
// Activate non-blocking mode for the reader.
@@ -81,6 +80,14 @@ fn open_pty() -> io::Result<(FileDescriptor, FileDescriptor)> {
Ok((read, write))
}
fn open_dev_tty() -> io::Result<FileDescriptor> {
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")?;
Ok(FileDescriptor::Owned(file.into()))
}
impl From<termios::Winsize> for WindowSize {
fn from(size: termios::Winsize) -> Self {
Self {

View File

@@ -293,24 +293,23 @@ impl io::Write for OutputHandle {
}
fn open_pty() -> io::Result<(InputHandle, OutputHandle)> {
let (input, output) = if io::stdin().is_terminal() {
(Handle::stdin(), Handle::stdout())
let input = if io::stdin().is_terminal() {
Handle::stdin()
} else {
let input = fs::OpenOptions::new()
.read(true)
.write(true)
.open("CONIN$")?
.into();
let output = fs::OpenOptions::new()
.read(true)
.write(true)
.open("CONOUT$")?
.into();
(input, output)
open_file("CONIN$")?.into()
};
let output = if io::stdout().is_terminal() {
Handle::stdout()
} else {
open_file("CONOUT$")?.into()
};
Ok((InputHandle::new(input), OutputHandle::new(output)))
}
fn open_file(path: &str) -> io::Result<File> {
fs::OpenOptions::new().read(true).write(true).open(path)
}
// CREDIT: Again, like the UnixTerminal in the unix module this is mostly based on WezTerm but
// only covers the parts not related to the event source.
// <https://github.com/wezterm/wezterm/blob/a87358516004a652ad840bc1661bdf65ffc89b43/termwiz/src/terminal/windows.rs#L482-L860>