From 9694e6b233425d1e225402d7c7aa1b53d4fc6837 Mon Sep 17 00:00:00 2001 From: Branch Vincent Date: Sat, 15 Jul 2023 16:16:04 -0700 Subject: [PATCH] feat(stream_output): respect `FORCE_COLOR` --- news/343.feat.md | 1 + src/cleo/io/outputs/stream_output.py | 2 ++ tests/io/outputs/test_stream_output.py | 35 ++++++++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 news/343.feat.md create mode 100644 tests/io/outputs/test_stream_output.py diff --git a/news/343.feat.md b/news/343.feat.md new file mode 100644 index 00000000..2f07ae71 --- /dev/null +++ b/news/343.feat.md @@ -0,0 +1 @@ +ANSI coloring detection now respects a `FORCE_COLOR` environment variable. diff --git a/src/cleo/io/outputs/stream_output.py b/src/cleo/io/outputs/stream_output.py index 0d021a89..13c2f3cc 100644 --- a/src/cleo/io/outputs/stream_output.py +++ b/src/cleo/io/outputs/stream_output.py @@ -83,6 +83,8 @@ def _has_color_support(self) -> bool: # Follow https://no-color.org/ if "NO_COLOR" in os.environ: return False + if "FORCE_COLOR" in os.environ: + return True if os.getenv("TERM_PROGRAM") == "Hyper": return True diff --git a/tests/io/outputs/test_stream_output.py b/tests/io/outputs/test_stream_output.py new file mode 100644 index 00000000..15228865 --- /dev/null +++ b/tests/io/outputs/test_stream_output.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +import os + +from io import StringIO + +import pytest + +from cleo.io.outputs.stream_output import StreamOutput + + +@pytest.fixture() +def stream() -> StringIO: + return StringIO() + + +@pytest.mark.parametrize( + ["env", "is_decorated"], + [ + ({"NO_COLOR": "1"}, False), + ({"FORCE_COLOR": "1"}, True), + ], +) +def test_is_decorated_respects_environment( + stream: StringIO, environ: None, env: dict[str, str], is_decorated: bool +) -> None: + os.environ.update(env) + + output = StreamOutput(stream) + output.write_line("FooBar") + stream.seek(0) + + assert output.is_decorated() == is_decorated + expected = "\x1b[34mFooBar\x1b[39m\n" if is_decorated else "FooBar\n" + assert stream.read() == expected