Skip to content

Commit

Permalink
Only apply colors if stderr is a terminal
Browse files Browse the repository at this point in the history
  • Loading branch information
smwoj committed Feb 20, 2024
1 parent 4a0e5a3 commit 5f3d564
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions pretty_assertions/src/printer.rs
@@ -1,29 +1,51 @@
#[cfg(feature = "alloc")]
use alloc::format;
use core::fmt;
use std::sync::OnceLock;

use yansi::Color::{Green, Red};
use yansi::{Paint, Style};

fn should_apply_color() -> bool {
use std::io::IsTerminal;
static IS_STDERR_TERMINAL: OnceLock<bool> = 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)*))
}
)
}

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.
Expand Down Expand Up @@ -147,7 +169,7 @@ where
fn write_with_style<T: Into<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
Expand Down

0 comments on commit 5f3d564

Please sign in to comment.