From 42d52ebbec275389ee0458a3bf373268278bd51a Mon Sep 17 00:00:00 2001 From: Carl Meyer Date: Mon, 8 Apr 2024 15:29:29 -0600 Subject: [PATCH] Support FORCE_COLOR env var (#10839) Fixes #5499 ## Summary Add support for `FORCE_COLOR` env var, as specified at https://force-color.org/ ## Test Plan I wrote an integration test for this, and then realized that can't work, since we use a dev-dependency on `colored` with the `no-color` feature to avoid ANSI color codes in test snapshots. So this is just tested manually. `cargo run --features test-rules -- check --no-cache --isolated - --select RUF901 --diff < /dev/null` shows a colored diff. `cargo run --features test-rules -- check --no-cache --isolated - --select RUF901 --diff < /dev/null | less` does not have color, since we pipe it to `less`. `FORCE_COLOR=1 cargo run --features test-rules -- check --no-cache --isolated - --select RUF901 --diff < /dev/null | less` does have color (after this diff), even though we pipe it to `less`. --- crates/ruff/src/lib.rs | 7 +++++++ docs/faq.md | 5 +++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/ruff/src/lib.rs b/crates/ruff/src/lib.rs index 1a9a333d232b40..42d0e61185861d 100644 --- a/crates/ruff/src/lib.rs +++ b/crates/ruff/src/lib.rs @@ -149,6 +149,13 @@ pub fn run( #[cfg(windows)] assert!(colored::control::set_virtual_terminal(true).is_ok()); + // support FORCE_COLOR env var + if let Some(force_color) = std::env::var_os("FORCE_COLOR") { + if force_color.len() > 0 { + colored::control::set_override(true); + } + } + set_up_logging(global_options.log_level())?; if let Some(deprecated_alias_warning) = deprecated_alias_warning { diff --git a/docs/faq.md b/docs/faq.md index f6fff988df6504..02d2ff1663585e 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -628,11 +628,12 @@ Even still, given the dynamic nature of Python, it's difficult to have _complete making changes to code, even for seemingly trivial fixes. If a "safe" fix breaks your code, please [file an Issue](https://github.com/astral-sh/ruff/issues/new). -## How can I disable Ruff's color output? +## How can I disable/force Ruff's color output? Ruff's color output is powered by the [`colored`](https://crates.io/crates/colored) crate, which attempts to automatically detect whether the output stream supports color. However, you can force -colors off by setting the `NO_COLOR` environment variable to any value (e.g., `NO_COLOR=1`). +colors off by setting the `NO_COLOR` environment variable to any value (e.g., `NO_COLOR=1`), or +force colors on by setting `FORCE_COLOR` to any non-empty value (e.g. `FORCE_COLOR=1`). [`colored`](https://crates.io/crates/colored) also supports the `CLICOLOR` and `CLICOLOR_FORCE` environment variables (see the [spec](https://bixense.com/clicolors/)).