Skip to content

Commit 016e874

Browse files
joshtriplettMatt Wilkinson
and
Matt Wilkinson
committed
Add IsTerminal trait to determine if a descriptor or handle is a terminal
The UNIX and WASI implementations use `isatty`. The Windows implementation uses the same logic the `atty` crate uses, including the hack needed to detect msys terminals. Implement this trait for `File` and for `Stdin`/`Stdout`/`Stderr` and their locked counterparts on all platforms. On UNIX and WASI, implement it for `BorrowedFd`/`OwnedFd`. On Windows, implement it for `BorrowedHandle`/`OwnedHandle`. Based on rust-lang#91121 Co-authored-by: Matt Wilkinson <mattwilki17@gmail.com>
1 parent 4d45b07 commit 016e874

File tree

15 files changed

+155
-36
lines changed

15 files changed

+155
-36
lines changed

library/std/src/io/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,8 @@ pub use self::buffered::WriterPanicked;
265265
#[unstable(feature = "internal_output_capture", issue = "none")]
266266
#[doc(no_inline, hidden)]
267267
pub use self::stdio::set_output_capture;
268+
#[unstable(feature = "is_terminal", issue = "98070")]
269+
pub use self::stdio::IsTerminal;
268270
#[unstable(feature = "print_internals", issue = "none")]
269271
pub use self::stdio::{_eprint, _print};
270272
#[stable(feature = "rust1", since = "1.0.0")]

library/std/src/io/stdio.rs

+29
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::io::prelude::*;
77

88
use crate::cell::{Cell, RefCell};
99
use crate::fmt;
10+
use crate::fs::File;
1011
use crate::io::{self, BufReader, IoSlice, IoSliceMut, LineWriter, Lines};
1112
use crate::pin::Pin;
1213
use crate::sync::atomic::{AtomicBool, Ordering};
@@ -1016,6 +1017,34 @@ where
10161017
}
10171018
}
10181019

1020+
/// Trait to determine if a descriptor/handle refers to a terminal/tty.
1021+
#[unstable(feature = "is_terminal", issue = "98070")]
1022+
pub trait IsTerminal: crate::sealed::Sealed {
1023+
/// Returns `true` if the descriptor/handle refers to a terminal/tty.
1024+
///
1025+
/// On platforms where Rust does not know how to detect a terminal yet, this will return
1026+
/// `false`. This will also return `false` if an unexpected error occurred, such as from
1027+
/// passing an invalid file descriptor.
1028+
fn is_terminal(&self) -> bool;
1029+
}
1030+
1031+
macro_rules! impl_is_terminal {
1032+
($($t:ty),*$(,)?) => {$(
1033+
#[unstable(feature = "sealed", issue = "none")]
1034+
impl crate::sealed::Sealed for $t {}
1035+
1036+
#[unstable(feature = "is_terminal", issue = "98070")]
1037+
impl IsTerminal for $t {
1038+
#[inline]
1039+
fn is_terminal(&self) -> bool {
1040+
crate::sys::io::is_terminal(self)
1041+
}
1042+
}
1043+
)*}
1044+
}
1045+
1046+
impl_is_terminal!(File, Stdin, StdinLock<'_>, Stdout, StdoutLock<'_>, Stderr, StderrLock<'_>);
1047+
10191048
#[unstable(
10201049
feature = "print_internals",
10211050
reason = "implementation detail which may disappear or be replaced at any time",

library/std/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@
252252
#![feature(dropck_eyepatch)]
253253
#![feature(exhaustive_patterns)]
254254
#![feature(intra_doc_pointers)]
255+
#![feature(is_terminal)]
255256
#![cfg_attr(bootstrap, feature(label_break_value))]
256257
#![feature(lang_items)]
257258
#![feature(let_else)]

library/std/src/os/fd/owned.rs

+17
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,23 @@ impl fmt::Debug for OwnedFd {
191191
}
192192
}
193193

194+
macro_rules! impl_is_terminal {
195+
($($t:ty),*$(,)?) => {$(
196+
#[unstable(feature = "sealed", issue = "none")]
197+
impl crate::sealed::Sealed for $t {}
198+
199+
#[unstable(feature = "is_terminal", issue = "98070")]
200+
impl crate::io::IsTerminal for $t {
201+
#[inline]
202+
fn is_terminal(&self) -> bool {
203+
crate::sys::io::is_terminal(self)
204+
}
205+
}
206+
)*}
207+
}
208+
209+
impl_is_terminal!(BorrowedFd<'_>, OwnedFd);
210+
194211
/// A trait to borrow the file descriptor from an underlying object.
195212
///
196213
/// This is only available on unix platforms and must be imported in order to

library/std/src/os/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,4 @@ pub mod solid;
147147
pub mod vxworks;
148148

149149
#[cfg(any(unix, target_os = "wasi", doc))]
150-
mod fd;
150+
pub(crate) mod fd;

library/std/src/os/windows/io/handle.rs

+17
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,23 @@ impl fmt::Debug for OwnedHandle {
384384
}
385385
}
386386

387+
macro_rules! impl_is_terminal {
388+
($($t:ty),*$(,)?) => {$(
389+
#[unstable(feature = "sealed", issue = "none")]
390+
impl crate::sealed::Sealed for $t {}
391+
392+
#[unstable(feature = "is_terminal", issue = "98070")]
393+
impl crate::io::IsTerminal for $t {
394+
#[inline]
395+
fn is_terminal(&self) -> bool {
396+
crate::sys::io::is_terminal(self)
397+
}
398+
}
399+
)*}
400+
}
401+
402+
impl_is_terminal!(BorrowedHandle<'_>, OwnedHandle);
403+
387404
/// A trait to borrow the handle from an underlying object.
388405
#[stable(feature = "io_safety", since = "1.63.0")]
389406
pub trait AsHandle {

library/std/src/sys/unix/io.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use crate::marker::PhantomData;
2+
use crate::os::fd::owned::AsFd;
3+
use crate::os::fd::raw::AsRawFd;
24
use crate::slice;
35

46
use libc::{c_void, iovec};
@@ -74,3 +76,8 @@ impl<'a> IoSliceMut<'a> {
7476
unsafe { slice::from_raw_parts_mut(self.vec.iov_base as *mut u8, self.vec.iov_len) }
7577
}
7678
}
79+
80+
pub fn is_terminal(fd: &impl AsFd) -> bool {
81+
let fd = fd.as_fd();
82+
unsafe { libc::isatty(fd.as_raw_fd()) != 0 }
83+
}

library/std/src/sys/unsupported/io.rs

+4
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,7 @@ impl<'a> IoSliceMut<'a> {
4545
self.0
4646
}
4747
}
48+
49+
pub fn is_terminal<T>(_: &T) -> bool {
50+
false
51+
}

library/std/src/sys/wasi/io.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#![deny(unsafe_op_in_unsafe_fn)]
22

33
use crate::marker::PhantomData;
4+
use crate::os::fd::owned::AsFd;
5+
use crate::os::fd::raw::AsRawFd;
46
use crate::slice;
57

68
#[derive(Copy, Clone)]
@@ -71,3 +73,8 @@ impl<'a> IoSliceMut<'a> {
7173
unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.buf_len) }
7274
}
7375
}
76+
77+
pub fn is_terminal(fd: &impl AsFd) -> bool {
78+
let fd = fd.as_fd();
79+
unsafe { libc::isatty(fd.as_raw_fd()) != 0 }
80+
}

library/std/src/sys/windows/c.rs

+8
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ pub const SECURITY_SQOS_PRESENT: DWORD = 0x00100000;
125125

126126
pub const FIONBIO: c_ulong = 0x8004667e;
127127

128+
pub const MAX_PATH: usize = 260;
129+
128130
#[repr(C)]
129131
#[derive(Copy)]
130132
pub struct WIN32_FIND_DATAW {
@@ -521,6 +523,12 @@ pub struct SYMBOLIC_LINK_REPARSE_BUFFER {
521523
pub PathBuffer: WCHAR,
522524
}
523525

526+
#[repr(C)]
527+
pub struct FILE_NAME_INFO {
528+
pub FileNameLength: DWORD,
529+
pub FileName: [WCHAR; 1],
530+
}
531+
524532
#[repr(C)]
525533
pub struct MOUNT_POINT_REPARSE_BUFFER {
526534
pub SubstituteNameOffset: c_ushort,

library/std/src/sys/windows/io.rs

+59
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
use crate::marker::PhantomData;
2+
use crate::mem::size_of;
3+
use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle};
24
use crate::slice;
35
use crate::sys::c;
6+
use core;
7+
use libc;
48

59
#[derive(Copy, Clone)]
610
#[repr(transparent)]
@@ -78,3 +82,58 @@ impl<'a> IoSliceMut<'a> {
7882
unsafe { slice::from_raw_parts_mut(self.vec.buf as *mut u8, self.vec.len as usize) }
7983
}
8084
}
85+
86+
pub fn is_terminal(h: &impl AsHandle) -> bool {
87+
unsafe { handle_is_console(h.as_handle()) }
88+
}
89+
90+
unsafe fn handle_is_console(handle: BorrowedHandle<'_>) -> bool {
91+
let handle = handle.as_raw_handle();
92+
93+
let mut out = 0;
94+
if c::GetConsoleMode(handle, &mut out) != 0 {
95+
// False positives aren't possible. If we got a console then we definitely have a console.
96+
return true;
97+
}
98+
99+
// At this point, we *could* have a false negative. We can determine that this is a true
100+
// negative if we can detect the presence of a console on any of the standard I/O streams. If
101+
// another stream has a console, then we know we're in a Windows console and can therefore
102+
// trust the negative.
103+
for std_handle in [c::STD_INPUT_HANDLE, c::STD_OUTPUT_HANDLE, c::STD_ERROR_HANDLE] {
104+
let std_handle = c::GetStdHandle(std_handle);
105+
if std_handle != handle && c::GetConsoleMode(std_handle, &mut out) != 0 {
106+
return false;
107+
}
108+
}
109+
110+
// Otherwise, we fall back to an msys hack to see if we can detect the presence of a pty.
111+
msys_tty_on(handle)
112+
}
113+
114+
unsafe fn msys_tty_on(handle: c::HANDLE) -> bool {
115+
let size = size_of::<c::FILE_NAME_INFO>() + c::MAX_PATH * size_of::<c::WCHAR>();
116+
let mut name_info_bytes = vec![0u8; size];
117+
let res = c::GetFileInformationByHandleEx(
118+
handle,
119+
c::FileNameInfo,
120+
name_info_bytes.as_mut_ptr() as *mut libc::c_void,
121+
size as u32,
122+
);
123+
if res == 0 {
124+
return false;
125+
}
126+
let name_info: &c::FILE_NAME_INFO = &*(name_info_bytes.as_ptr() as *const c::FILE_NAME_INFO);
127+
let s = core::slice::from_raw_parts(
128+
name_info.FileName.as_ptr(),
129+
name_info.FileNameLength as usize / 2,
130+
);
131+
let name = String::from_utf16_lossy(s);
132+
// This checks whether 'pty' exists in the file name, which indicates that
133+
// a pseudo-terminal is attached. To mitigate against false positives
134+
// (e.g., an actual file name that contains 'pty'), we also require that
135+
// either the strings 'msys-' or 'cygwin-' are in the file name as well.)
136+
let is_msys = name.contains("msys-") || name.contains("cygwin-");
137+
let is_pty = name.contains("-pty");
138+
is_msys && is_pty
139+
}

library/test/src/cli.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
use std::env;
44
use std::path::PathBuf;
55

6-
use super::helpers::isatty;
76
use super::options::{ColorConfig, Options, OutputFormat, RunIgnored};
87
use super::time::TestTimeOptions;
8+
use std::io::{self, IsTerminal};
99

1010
#[derive(Debug)]
1111
pub struct TestOpts {
@@ -32,7 +32,7 @@ pub struct TestOpts {
3232
impl TestOpts {
3333
pub fn use_color(&self) -> bool {
3434
match self.color {
35-
ColorConfig::AutoColor => !self.nocapture && isatty::stdout_isatty(),
35+
ColorConfig::AutoColor => !self.nocapture && io::stdout().is_terminal(),
3636
ColorConfig::AlwaysColor => true,
3737
ColorConfig::NeverColor => false,
3838
}

library/test/src/helpers/isatty.rs

-32
This file was deleted.

library/test/src/helpers/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,5 @@
33
44
pub mod concurrency;
55
pub mod exit_code;
6-
pub mod isatty;
76
pub mod metrics;
87
pub mod shuffle;

library/test/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#![doc(test(attr(deny(warnings))))]
1818
#![feature(bench_black_box)]
1919
#![feature(internal_output_capture)]
20+
#![feature(is_terminal)]
2021
#![feature(staged_api)]
2122
#![feature(process_exitcode_internals)]
2223
#![feature(test)]

0 commit comments

Comments
 (0)