Skip to content

Conversation

rtbo
Copy link

@rtbo rtbo commented Aug 28, 2024

New API to disable ANSI escape code emission on redirected outputs.
see #921

Example of code provided by this feature:

fn print_diagnostic() {
    let _guard = style::disable_ansi(!io::stderr().is_terminal());

    // styling stderr output is now only active if stderr is not redirected
    eprintln!("{}: {}", "error".red().bold(), "something went wrong".bold());
}

A nice thing is that the code that prints doesn't need to be aware of the feature and can use the fmt API and be in a different crate.

fn write_diagnostic<W: io::Write>(out: &mut W, err: &Error) -> io::Result<()> {
    writeln!(out, "{}: {}", "error".red().bold(), err.to_string().bold());
}

fn print_diagnostic(err: &Error, force_color: bool) -> io::Result<()> {
    let stderr = io::stderr().lock();
    let _guard = style::disable_ansi(!force_color && !stderr.is_terminal());

    let mut out = BufWriter::new(stderr);
    write_diagnostic(&mut out, err)?;
    out.flush()
}

New API is behind a cargo feature because there is a runtime check for each escape code emitted.
Not everyone wants to pay this cost.

Without this PR, managing redirected output is tedious and generally requires to double the print code. (with and without style)

@rtbo rtbo requested a review from TimonPost as a code owner August 28, 2024 05:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant