Skip to content

Commit

Permalink
If detect-terminal feature is enabled, only apply colors if stderr is…
Browse files Browse the repository at this point in the history
… a terminal
  • Loading branch information
smwoj committed Mar 3, 2024
1 parent 4a0e5a3 commit 5a85f26
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 11 deletions.
1 change: 1 addition & 0 deletions pretty_assertions/Cargo.toml
Expand Up @@ -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.
Expand Down
49 changes: 38 additions & 11 deletions pretty_assertions/src/printer.rs
Expand Up @@ -4,26 +4,53 @@ 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<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 +174,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 5a85f26

Please sign in to comment.