From 5a85f26828f4d3992ab53c4f00872ea9a5dfcd60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Smo=C5=82ka?= Date: Mon, 5 Feb 2024 16:55:38 +0100 Subject: [PATCH] If detect-terminal feature is enabled, only apply colors if stderr is a terminal --- pretty_assertions/Cargo.toml | 1 + pretty_assertions/src/printer.rs | 49 +++++++++++++++++++++++++------- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/pretty_assertions/Cargo.toml b/pretty_assertions/Cargo.toml index 1a53741..44e62d0 100644 --- a/pretty_assertions/Cargo.toml +++ b/pretty_assertions/Cargo.toml @@ -19,6 +19,7 @@ readme = "README.md" [features] default = ["std"] +detect-terminal = ["std"] # Use the Rust standard library. # Exactly one of `std` and `alloc` is required. diff --git a/pretty_assertions/src/printer.rs b/pretty_assertions/src/printer.rs index e1bd84b..5f0b264 100644 --- a/pretty_assertions/src/printer.rs +++ b/pretty_assertions/src/printer.rs @@ -4,9 +4,27 @@ use core::fmt; use yansi::Color::{Green, Red}; use yansi::{Paint, Style}; +#[cfg(not(feature = "detect-terminal"))] +fn should_apply_color() -> bool { + true +} + +#[cfg(feature = "detect-terminal")] +fn should_apply_color() -> bool { + use std::io::IsTerminal; + use std::sync::OnceLock; + static IS_STDERR_TERMINAL: OnceLock = OnceLock::new(); + + *IS_STDERR_TERMINAL.get_or_init(|| std::io::stderr().is_terminal()) +} + macro_rules! paint { ($f:expr, $style:expr, $fmt:expr, $($args:tt)*) => ( - write!($f, "{}", format!($fmt, $($args)*).paint($style)) + if should_apply_color() { + write!($f, "{}", format!($fmt, $($args)*).paint($style)) + } else{ + write!($f, "{}", format!($fmt, $($args)*)) + } ) } @@ -14,16 +32,25 @@ const SIGN_RIGHT: char = '>'; // + > → const SIGN_LEFT: char = '<'; // - < ← /// Present the diff output for two mutliline strings in a pretty, colorised manner. +#[allow(clippy::write_literal)] pub(crate) fn write_header(f: &mut fmt::Formatter) -> fmt::Result { - writeln!( - f, - "{} {} {} / {} {} :", - "Diff".bold(), - SIGN_LEFT.red().linger(), - "left".clear(), - "right".green().linger(), - SIGN_RIGHT.clear(), - ) + if should_apply_color() { + writeln!( + f, + "{} {} {} / {} {} :", + "Diff".bold(), + SIGN_LEFT.red().linger(), + "left".clear(), + "right".green().linger(), + SIGN_RIGHT.clear(), + ) + } else { + writeln!( + f, + "{} {} {} / {} {} :", + "", SIGN_LEFT, "left", "right", SIGN_RIGHT, + ) + } } /// Delay formatting this deleted chunk until later. @@ -147,7 +174,7 @@ where fn write_with_style>(&mut self, c: &char, style: T) -> fmt::Result { // If the style is the same as previously, just write character let style = style.into(); - if style == self.style { + if style == self.style || !should_apply_color() { write!(self.f, "{}", c)?; } else { // Close out previous style