Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only apply colors if stderr is a terminal #127

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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