From 0cab54432a1df91a9b71637b773bcbb9772a6b59 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 4 Oct 2022 14:31:14 -0700 Subject: [PATCH] Fall back to FORCE_COLOR environment variable if MYPY_FORCE_COLOR is not present (#13814) Fixes #13806 This PR adds support for a FORCE_COLOR environment variable. If both MYPY_FORCE_COLOR and FORCE_COLOR are present, mypy will continue to use MYPY_FORCE_COLOR over FORCE_COLOR. However, if only FORCE_COLOR is set, mypy will use that environment variable in much the same way it currently uses MYPY_FORCE_COLOR. MYPY_FORCE_COLOR appears to be undocumented and untested currently, so this PR doesn't add any tests. However, @hugovk has tested this change manually and using GitHub Actions, and reports that it appears to work as expected. --- mypy/dmypy/client.py | 4 ++-- mypy/util.py | 7 +++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/mypy/dmypy/client.py b/mypy/dmypy/client.py index 25951befccda..efa1b5f01288 100644 --- a/mypy/dmypy/client.py +++ b/mypy/dmypy/client.py @@ -19,7 +19,7 @@ from mypy.dmypy_os import alive, kill from mypy.dmypy_util import DEFAULT_STATUS_FILE, receive from mypy.ipc import IPCClient, IPCException -from mypy.util import check_python_version, get_terminal_width +from mypy.util import check_python_version, get_terminal_width, should_force_color from mypy.version import __version__ # Argument parser. Subparsers are tied to action functions by the @@ -653,7 +653,7 @@ def request( args["command"] = command # Tell the server whether this request was initiated from a human-facing terminal, # so that it can format the type checking output accordingly. - args["is_tty"] = sys.stdout.isatty() or int(os.getenv("MYPY_FORCE_COLOR", "0")) > 0 + args["is_tty"] = sys.stdout.isatty() or should_force_color() args["terminal_width"] = get_terminal_width() bdata = json.dumps(args).encode("utf8") _, name = get_status(status_file) diff --git a/mypy/util.py b/mypy/util.py index d889d3d9340f..e836aefb3c7e 100644 --- a/mypy/util.py +++ b/mypy/util.py @@ -519,6 +519,10 @@ def parse_gray_color(cup: bytes) -> str: return gray +def should_force_color() -> bool: + return bool(int(os.getenv("MYPY_FORCE_COLOR", os.getenv("FORCE_COLOR", "0")))) + + class FancyFormatter: """Apply color and bold font to terminal output. @@ -531,8 +535,7 @@ def __init__(self, f_out: IO[str], f_err: IO[str], hide_error_codes: bool) -> No if sys.platform not in ("linux", "darwin", "win32", "emscripten"): self.dummy_term = True return - force_color = int(os.getenv("MYPY_FORCE_COLOR", "0")) - if not force_color and (not f_out.isatty() or not f_err.isatty()): + if not should_force_color() and (not f_out.isatty() or not f_err.isatty()): self.dummy_term = True return if sys.platform == "win32":