Skip to content

Commit 4481898

Browse files
authored
Re-add fallback for zero terminal width (#9651)
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
1 parent 7f63b49 commit 4481898

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

mypy/test/testutil.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import os
2+
from unittest import mock, TestCase
3+
4+
from mypy.util import get_terminal_width
5+
6+
7+
class TestGetTerminalSize(TestCase):
8+
def test_get_terminal_size_in_pty_defaults_to_80(self) -> None:
9+
# when run using a pty, `os.get_terminal_size()` returns `0, 0`
10+
ret = os.terminal_size((0, 0))
11+
with mock.patch.object(os, 'get_terminal_size', return_value=ret):
12+
assert get_terminal_width() == 80

mypy/util.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
re.compile(br'([ \t\v]*#.*(\r\n?|\n))??[ \t\v]*#.*coding[:=][ \t]*([-\w.]+)') # type: Final
2828

2929
DEFAULT_SOURCE_OFFSET = 4 # type: Final
30+
DEFAULT_COLUMNS = 80 # type: Final
3031

3132
# At least this number of columns will be shown on each side of
3233
# error location when printing source code snippet.
@@ -416,7 +417,9 @@ def split_words(msg: str) -> List[str]:
416417

417418
def get_terminal_width() -> int:
418419
"""Get current terminal width if possible, otherwise return the default one."""
419-
return int(os.getenv('MYPY_FORCE_TERMINAL_WIDTH', '0')) or shutil.get_terminal_size().columns
420+
return (int(os.getenv('MYPY_FORCE_TERMINAL_WIDTH', '0'))
421+
or shutil.get_terminal_size().columns
422+
or DEFAULT_COLUMNS)
420423

421424

422425
def soft_wrap(msg: str, max_len: int, first_offset: int,

0 commit comments

Comments
 (0)