~asayers/yason

79860d39c48e7bd867164f15705634c59e0173c4 — Alex Sayers 4 years ago de16d19
Disable colours when stdout is not a tty
1 files changed, 28 insertions(+), 13 deletions(-)

M src/main.rs
M src/main.rs => src/main.rs +28 -13
@@ 1,3 1,4 @@
use crossterm::tty::IsTty;
use crossterm::QueueableCommand;
use std::io::{BufRead, BufReader, BufWriter, Write};



@@ 25,6 26,7 @@ fn main_2() -> anyhow::Result<()> {
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let stdin = BufReader::new(stdin.lock());
    let color = stdout.is_tty();
    let mut stdout = BufWriter::new(stdout.lock());

    #[cfg(feature = "bench")]


@@ 54,23 56,36 @@ fn main_2() -> anyhow::Result<()> {

        use crossterm::style::*;
        let mut lines = yaml.lines();
        stdout
            .queue(SetAttribute(Attribute::Bold))?
            .queue(Print(lines.next().unwrap()))?
            .queue(SetAttribute(Attribute::Reset))?
            .queue(Print("\n"))?;
        for mut line in lines {
            if let Some(n) = line.find(':').or_else(|| line.find('-')) {
        if color {
            stdout
                .queue(SetAttribute(Attribute::Bold))?
                .queue(Print(lines.next().unwrap()))?
                .queue(SetAttribute(Attribute::Reset))?
                .queue(Print("\n"))?;
            for mut line in lines {
                if let Some(n) = line.find(':').or_else(|| line.find('-')) {
                    stdout
                        .queue(SetForegroundColor(Color::DarkMagenta))?
                        .queue(Print(&line[..n + 1]))?;
                    line = &line[n + 1..];
                }
                stdout
                    .queue(SetForegroundColor(Color::DarkMagenta))?
                    .queue(Print(&line[..n + 1]))?;
                line = &line[n + 1..];
                    .queue(SetForegroundColor(Color::Yellow))?
                    .queue(Print(line))?
                    .queue(ResetColor)?
                    .queue(Print("\n"))?;
            }
        } else {
            stdout
                .queue(SetForegroundColor(Color::Yellow))?
                .queue(Print(line))?
                .queue(ResetColor)?
                .queue(Print(lines.next().unwrap()))?
                .queue(Print("\n"))?;
            for mut line in lines {
                if let Some(n) = line.find(':').or_else(|| line.find('-')) {
                    stdout.queue(Print(&line[..n + 1]))?;
                    line = &line[n + 1..];
                }
                stdout.queue(Print(line))?.queue(Print("\n"))?;
            }
        }
        stdout.flush()?;
    }