is_terminal_polyfill/
lib.rs

1//! > Polyfill for `is_terminal` stdlib feature for use with older MSRVs
2
3#![warn(clippy::print_stderr)]
4#![warn(clippy::print_stdout)]
5
6/// Trait to determine if a descriptor/handle refers to a terminal/tty.
7pub trait IsTerminal: sealed::Sealed {
8    /// Returns `true` if the descriptor/handle refers to a terminal/tty.
9    ///
10    /// On platforms where Rust does not know how to detect a terminal yet, this will return
11    /// `false`. This will also return `false` if an unexpected error occurred, such as from
12    /// passing an invalid file descriptor.
13    ///
14    /// # Platform-specific behavior
15    ///
16    /// On Windows, in addition to detecting consoles, this currently uses some heuristics to
17    /// detect older msys/cygwin/mingw pseudo-terminals based on device name: devices with names
18    /// starting with `msys-` or `cygwin-` and ending in `-pty` will be considered terminals.
19    /// Note that this [may change in the future][changes].
20    ///
21    /// [changes]: std::io#platform-specific-behavior
22    fn is_terminal(&self) -> bool;
23}
24
25mod sealed {
26    pub trait Sealed {}
27}
28
29macro_rules! impl_is_terminal {
30    ($($t:ty),*$(,)?) => {$(
31        impl sealed::Sealed for $t {}
32
33        impl IsTerminal for $t {
34            #[inline]
35            fn is_terminal(&self) -> bool {
36                std::io::IsTerminal::is_terminal(self)
37            }
38        }
39    )*}
40}
41
42impl_is_terminal!(
43    std::fs::File,
44    std::io::Stdin,
45    std::io::StdinLock<'_>,
46    std::io::Stdout,
47    std::io::StdoutLock<'_>,
48    std::io::Stderr,
49    std::io::StderrLock<'_>
50);