Skip to content

Commit 0a8967c

Browse files
authored
Clean up terminal width handling (#9143)
* Remove fixed_terminal_width from utils.colorize docstring This was added by 91adf61, yet colorize() doesn't actually have a fixed_terminal_width argument. * Move MYPY_FORCE_TERMINAL_WIDTH handling into get_terminal_width() Those two callers are the only two, and both check MYPY_FORCE_TERMINAL_WIDTH before calling get_terminal_width(). * Use shutil.get_terminal_size() The documentation for Python's os.get_terminal_size() says: shutil.get_terminal_size() is the high-level function which should normally be used, os.get_terminal_size is the low-level implementation. https://docs.python.org/3/library/os.html#os.get_terminal_size shutil.get_terminal_size() already takes care of various corner cases such as: - Providing a fallback (to 80 columns, like the current DEFAULT_COLUMNS) - Returning that fallback if os.get_terminal_size() raises OSError - Doing the same if it returns a size of 0 In addition to that: - It takes care of some more corner cases ("stdout is None, closed, detached, or not a terminal, or os.get_terminal_size() is unsupported") - It adds support for the COLUMNS environment variable (rather than the non-standard MYPY_FORCE_TERMINAL_WIDTH) https://github.com/python/cpython/blob/v3.8.3/Lib/shutil.py#L1298-L1341
1 parent 03815d6 commit 0a8967c

File tree

2 files changed

+5
-18
lines changed

2 files changed

+5
-18
lines changed

mypy/dmypy/client.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -475,8 +475,7 @@ def request(status_file: str, command: str, *, timeout: Optional[int] = None,
475475
# Tell the server whether this request was initiated from a human-facing terminal,
476476
# so that it can format the type checking output accordingly.
477477
args['is_tty'] = sys.stdout.isatty() or int(os.getenv('MYPY_FORCE_COLOR', '0')) > 0
478-
args['terminal_width'] = (int(os.getenv('MYPY_FORCE_TERMINAL_WIDTH', '0')) or
479-
get_terminal_width())
478+
args['terminal_width'] = get_terminal_width()
480479
bdata = json.dumps(args).encode('utf8')
481480
_, name = get_status(status_file)
482481
try:

mypy/util.py

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import sys
88
import hashlib
99
import io
10+
import shutil
1011

1112
from typing import (
1213
TypeVar, List, Tuple, Optional, Dict, Sequence, Iterable, Container, IO, Callable
@@ -34,7 +35,6 @@
3435
PLAIN_ANSI_DIM = '\x1b[2m' # type: Final
3536

3637
DEFAULT_SOURCE_OFFSET = 4 # type: Final
37-
DEFAULT_COLUMNS = 80 # type: Final
3838

3939
# At least this number of columns will be shown on each side of
4040
# error location when printing source code snippet.
@@ -424,14 +424,7 @@ def split_words(msg: str) -> List[str]:
424424

425425
def get_terminal_width() -> int:
426426
"""Get current terminal width if possible, otherwise return the default one."""
427-
try:
428-
cols, _ = os.get_terminal_size()
429-
except OSError:
430-
return DEFAULT_COLUMNS
431-
else:
432-
if cols == 0:
433-
return DEFAULT_COLUMNS
434-
return cols
427+
return int(os.getenv('MYPY_FORCE_TERMINAL_WIDTH', '0')) or shutil.get_terminal_size().columns
435428

436429

437430
def soft_wrap(msg: str, max_len: int, first_offset: int,
@@ -594,8 +587,7 @@ def style(self, text: str, color: Literal['red', 'green', 'blue', 'yellow', 'non
594587
def fit_in_terminal(self, messages: List[str],
595588
fixed_terminal_width: Optional[int] = None) -> List[str]:
596589
"""Improve readability by wrapping error messages and trimming source code."""
597-
width = (fixed_terminal_width or int(os.getenv('MYPY_FORCE_TERMINAL_WIDTH', '0')) or
598-
get_terminal_width())
590+
width = fixed_terminal_width or get_terminal_width()
599591
new_messages = messages.copy()
600592
for i, error in enumerate(messages):
601593
if ': error:' in error:
@@ -619,11 +611,7 @@ def fit_in_terminal(self, messages: List[str],
619611
return new_messages
620612

621613
def colorize(self, error: str) -> str:
622-
"""Colorize an output line by highlighting the status and error code.
623-
624-
If fixed_terminal_width is given, use it instead of calling get_terminal_width()
625-
(used by the daemon).
626-
"""
614+
"""Colorize an output line by highlighting the status and error code."""
627615
if ': error:' in error:
628616
loc, msg = error.split('error:', maxsplit=1)
629617
if not self.show_error_codes:

0 commit comments

Comments
 (0)