1 //! Making it a little more convenient and safe to query whether
2 //! something is a terminal teletype or not.
3 //! This module defines the IsTty trait and the is_tty method to
4 //! return true if the item represents a terminal.
5 
6 #[cfg(unix)]
7 use std::os::unix::io::AsRawFd;
8 #[cfg(windows)]
9 use std::os::windows::io::AsRawHandle;
10 #[cfg(windows)]
11 use winapi::um::consoleapi::GetConsoleMode;
12 
13 /// Adds the `is_tty` method to types that might represent a terminal
14 pub trait IsTty {
15     /// Returns true when an instance is a terminal teletype, otherwise false.
is_tty(&self) -> bool16     fn is_tty(&self) -> bool;
17 }
18 
19 /// On unix, the `isatty()` function returns true if a file
20 /// descriptor is a terminal.
21 #[cfg(unix)]
22 impl<S: AsRawFd> IsTty for S {
is_tty(&self) -> bool23     fn is_tty(&self) -> bool {
24         let fd = self.as_raw_fd();
25         unsafe { libc::isatty(fd) == 1 }
26     }
27 }
28 
29 /// On windows, `GetConsoleMode` will return true if we are in a terminal.
30 /// Otherwise false.
31 #[cfg(windows)]
32 impl<S: AsRawHandle> IsTty for S {
is_tty(&self) -> bool33     fn is_tty(&self) -> bool {
34         let mut mode = 0;
35         let ok = unsafe { GetConsoleMode(self.as_raw_handle() as *mut _, &mut mode) };
36         ok == 1
37     }
38 }
39