console-rs / console

A rust console and terminal abstraction
MIT License
953 stars 113 forks source link

Support of reading the `is_tty` status of `stdin` #200

Open Gordon01 opened 10 months ago

Gordon01 commented 10 months ago

This PR brings the initial support of reading piped stdin.

This issue is mentioned multiple times here and in dialoguer: https://github.com/console-rs/console/issues/76 https://github.com/console-rs/console/issues/35 https://github.com/console-rs/dialoguer/issues/296 https://github.com/console-rs/dialoguer/issues/170

Most importantly, this PR adds the Term.features().is_input_a_tty() method. I've added a new type Tty which holds the statuses of all application streams. It encompasses the logic to detect the attendance of the terminal. It also contains is_tty moved from the Term which follows the old behavior, where only the output streams were considered.

It's debatable, whether should we change the behavior of the Term.is_term() method to also check the input stream attendance.

This itself doesn't solve the problem with reading piped input, the next step would be updating dialoguer to use the new method is_input_a_tty(). I tried the following code and it works. The main drawback is that piped input can only be read once during the application's lifetime. So if the user has multiple inputs, the second and following will be an empty string.

pub fn interact_text_on(mut self, term: &Term) -> Result<T> {
    if !term.features().is_input_a_tty() {
        let mut input = String::new();
        io::stdin().read_to_string(&mut input)?;
        return input
            .trim()
            .parse::<T>()
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()).into());
    }