From 9af99dd948e3cacc502b6d1d651ef817be93051c Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Tue, 27 Oct 2020 17:19:03 +0100 Subject: [PATCH] Re-add fallback for zero terminal width Contrary to what I assumed in #9143, shutil.get_terminal_size() doesn't actually handle a 0 width from os.get_terminal_size() - it only handles a 0 COLUMNS environment variable. Thus, this caused #8144 to regress. This change re-adds and uses DEFAULT_COLUMNS and also adds the test which was deemed unnecessary in #8145 - this regression proves that I'd have been a good idea to add it in the first place. (Test written by Anthony Sottile) Fixes https://github.com/pre-commit/mirrors-mypy/issues/29 --- mypy/test/testutil.py | 12 ++++++++++++ mypy/util.py | 5 ++++- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 mypy/test/testutil.py diff --git a/mypy/test/testutil.py b/mypy/test/testutil.py new file mode 100644 index 000000000000..6bfd364546bb --- /dev/null +++ b/mypy/test/testutil.py @@ -0,0 +1,12 @@ +import os +from unittest import mock, TestCase + +from mypy.util import get_terminal_width + + +class TestGetTerminalSize(TestCase): + def test_get_terminal_size_in_pty_defaults_to_80(self) -> None: + # when run using a pty, `os.get_terminal_size()` returns `0, 0` + ret = os.terminal_size((0, 0)) + with mock.patch.object(os, 'get_terminal_size', return_value=ret): + assert get_terminal_width() == 80 diff --git a/mypy/util.py b/mypy/util.py index 8481bab69ee9..2639cb1eeb92 100644 --- a/mypy/util.py +++ b/mypy/util.py @@ -27,6 +27,7 @@ re.compile(br'([ \t\v]*#.*(\r\n?|\n))??[ \t\v]*#.*coding[:=][ \t]*([-\w.]+)') # type: Final DEFAULT_SOURCE_OFFSET = 4 # type: Final +DEFAULT_COLUMNS = 80 # type: Final # At least this number of columns will be shown on each side of # error location when printing source code snippet. @@ -416,7 +417,9 @@ def split_words(msg: str) -> List[str]: def get_terminal_width() -> int: """Get current terminal width if possible, otherwise return the default one.""" - return int(os.getenv('MYPY_FORCE_TERMINAL_WIDTH', '0')) or shutil.get_terminal_size().columns + return (int(os.getenv('MYPY_FORCE_TERMINAL_WIDTH', '0')) + or shutil.get_terminal_size().columns + or DEFAULT_COLUMNS) def soft_wrap(msg: str, max_len: int, first_offset: int,