Skip to content

Commit

Permalink
Upgrade rich to 13.9.4
Browse files Browse the repository at this point in the history
  • Loading branch information
ichard26 committed Dec 7, 2024
1 parent c530f32 commit 0daddaf
Show file tree
Hide file tree
Showing 30 changed files with 391 additions and 194 deletions.
1 change: 1 addition & 0 deletions news/rich.vendor.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Upgrade rich to 13.9.4
2 changes: 0 additions & 2 deletions src/pip/_vendor/rich/_inspect.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import

import inspect
from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature
from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_vendor/rich/_null_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __iter__(self) -> Iterator[str]:
return iter([""])

def __enter__(self) -> IO[str]:
pass
return self

def __exit__(
self,
Expand Down
7 changes: 3 additions & 4 deletions src/pip/_vendor/rich/_win32_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
The API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions
"""

import ctypes
import sys
from typing import Any
Expand Down Expand Up @@ -380,7 +381,7 @@ def cursor_position(self) -> WindowsCoordinates:
WindowsCoordinates: The current cursor position.
"""
coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition
return WindowsCoordinates(row=cast(int, coord.Y), col=cast(int, coord.X))
return WindowsCoordinates(row=coord.Y, col=coord.X)

@property
def screen_size(self) -> WindowsCoordinates:
Expand All @@ -390,9 +391,7 @@ def screen_size(self) -> WindowsCoordinates:
WindowsCoordinates: The width and height of the screen as WindowsCoordinates.
"""
screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize
return WindowsCoordinates(
row=cast(int, screen_size.Y), col=cast(int, screen_size.X)
)
return WindowsCoordinates(row=screen_size.Y, col=screen_size.X)

def write_text(self, text: str) -> None:
"""Write text directly to the terminal without any modification of styles
Expand Down
1 change: 1 addition & 0 deletions src/pip/_vendor/rich/align.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ class VerticalCenter(JupyterMixin):
Args:
renderable (RenderableType): A renderable object.
style (StyleType, optional): An optional style to apply to the background. Defaults to None.
"""

def __init__(
Expand Down
1 change: 1 addition & 0 deletions src/pip/_vendor/rich/ansi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

re_ansi = re.compile(
r"""
(?:\x1b[0-?])|
(?:\x1b\](.*?)\x1b\\)|
(?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~]))
""",
Expand Down
53 changes: 30 additions & 23 deletions src/pip/_vendor/rich/cells.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,33 @@
from __future__ import annotations

import re
from functools import lru_cache
from typing import Callable

from ._cell_widths import CELL_WIDTHS

# Regex to match sequence of the most common character ranges
_is_single_cell_widths = re.compile("^[\u0020-\u006f\u00a0\u02ff\u0370-\u0482]*$").match
# Ranges of unicode ordinals that produce a 1-cell wide character
# This is non-exhaustive, but covers most common Western characters
_SINGLE_CELL_UNICODE_RANGES: list[tuple[int, int]] = [
(0x20, 0x7E), # Latin (excluding non-printable)
(0xA0, 0xAC),
(0xAE, 0x002FF),
(0x00370, 0x00482), # Greek / Cyrillic
(0x02500, 0x025FC), # Box drawing, box elements, geometric shapes
(0x02800, 0x028FF), # Braille
]

# A set of characters that are a single cell wide
_SINGLE_CELLS = frozenset(
[
character
for _start, _end in _SINGLE_CELL_UNICODE_RANGES
for character in map(chr, range(_start, _end + 1))
]
)

# When called with a string this will return True if all
# characters are single-cell, otherwise False
_is_single_cell_widths: Callable[[str], bool] = _SINGLE_CELLS.issuperset


@lru_cache(4096)
Expand All @@ -23,9 +43,9 @@ def cached_cell_len(text: str) -> int:
Returns:
int: Get the number of cells required to display text.
"""
_get_size = get_character_cell_size
total_size = sum(_get_size(character) for character in text)
return total_size
if _is_single_cell_widths(text):
return len(text)
return sum(map(get_character_cell_size, text))


def cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int:
Expand All @@ -39,9 +59,9 @@ def cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> in
"""
if len(text) < 512:
return _cell_len(text)
_get_size = get_character_cell_size
total_size = sum(_get_size(character) for character in text)
return total_size
if _is_single_cell_widths(text):
return len(text)
return sum(map(get_character_cell_size, text))


@lru_cache(maxsize=4096)
Expand All @@ -54,20 +74,7 @@ def get_character_cell_size(character: str) -> int:
Returns:
int: Number of cells (0, 1 or 2) occupied by that character.
"""
return _get_codepoint_cell_size(ord(character))


@lru_cache(maxsize=4096)
def _get_codepoint_cell_size(codepoint: int) -> int:
"""Get the cell size of a character.
Args:
codepoint (int): Codepoint of a character.
Returns:
int: Number of cells (0, 1 or 2) occupied by that character.
"""

codepoint = ord(character)
_table = CELL_WIDTHS
lower_bound = 0
upper_bound = len(_table) - 1
Expand Down
4 changes: 2 additions & 2 deletions src/pip/_vendor/rich/color.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import platform
import re
import sys
from colorsys import rgb_to_hls
from enum import IntEnum
from functools import lru_cache
Expand All @@ -15,7 +15,7 @@
from .text import Text


WINDOWS = platform.system() == "Windows"
WINDOWS = sys.platform == "win32"


class ColorSystem(IntEnum):
Expand Down
82 changes: 55 additions & 27 deletions src/pip/_vendor/rich/console.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import inspect
import os
import platform
import sys
import threading
import zlib
Expand Down Expand Up @@ -76,7 +75,7 @@

JUPYTER_DEFAULT_COLUMNS = 115
JUPYTER_DEFAULT_LINES = 100
WINDOWS = platform.system() == "Windows"
WINDOWS = sys.platform == "win32"

HighlighterType = Callable[[Union[str, "Text"]], "Text"]
JustifyMethod = Literal["default", "left", "center", "right", "full"]
Expand All @@ -90,15 +89,15 @@ class NoChange:
NO_CHANGE = NoChange()

try:
_STDIN_FILENO = sys.__stdin__.fileno()
_STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr]
except Exception:
_STDIN_FILENO = 0
try:
_STDOUT_FILENO = sys.__stdout__.fileno()
_STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr]
except Exception:
_STDOUT_FILENO = 1
try:
_STDERR_FILENO = sys.__stderr__.fileno()
_STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr]
except Exception:
_STDERR_FILENO = 2

Expand Down Expand Up @@ -1006,19 +1005,14 @@ def size(self) -> ConsoleDimensions:
width: Optional[int] = None
height: Optional[int] = None

if WINDOWS: # pragma: no cover
streams = _STD_STREAMS_OUTPUT if WINDOWS else _STD_STREAMS
for file_descriptor in streams:
try:
width, height = os.get_terminal_size()
width, height = os.get_terminal_size(file_descriptor)
except (AttributeError, ValueError, OSError): # Probably not a terminal
pass
else:
for file_descriptor in _STD_STREAMS:
try:
width, height = os.get_terminal_size(file_descriptor)
except (AttributeError, ValueError, OSError):
pass
else:
break
else:
break

columns = self._environ.get("COLUMNS")
if columns is not None and columns.isdigit():
Expand Down Expand Up @@ -1309,7 +1303,7 @@ def render(

renderable = rich_cast(renderable)
if hasattr(renderable, "__rich_console__") and not isclass(renderable):
render_iterable = renderable.__rich_console__(self, _options) # type: ignore[union-attr]
render_iterable = renderable.__rich_console__(self, _options)
elif isinstance(renderable, str):
text_renderable = self.render_str(
renderable, highlight=_options.highlight, markup=_options.markup
Expand Down Expand Up @@ -1386,9 +1380,14 @@ def render_lines(
extra_lines = render_options.height - len(lines)
if extra_lines > 0:
pad_line = [
[Segment(" " * render_options.max_width, style), Segment("\n")]
if new_lines
else [Segment(" " * render_options.max_width, style)]
(
[
Segment(" " * render_options.max_width, style),
Segment("\n"),
]
if new_lines
else [Segment(" " * render_options.max_width, style)]
)
]
lines.extend(pad_line * extra_lines)

Expand Down Expand Up @@ -1437,9 +1436,11 @@ def render_str(
rich_text.overflow = overflow
else:
rich_text = Text(
_emoji_replace(text, default_variant=self._emoji_variant)
if emoji_enabled
else text,
(
_emoji_replace(text, default_variant=self._emoji_variant)
if emoji_enabled
else text
),
justify=justify,
overflow=overflow,
style=style,
Expand Down Expand Up @@ -1536,7 +1537,11 @@ def check_text() -> None:
if isinstance(renderable, str):
append_text(
self.render_str(
renderable, emoji=emoji, markup=markup, highlighter=_highlighter
renderable,
emoji=emoji,
markup=markup,
highlight=highlight,
highlighter=_highlighter,
)
)
elif isinstance(renderable, Text):
Expand Down Expand Up @@ -1986,6 +1991,20 @@ def log(
):
buffer_extend(line)

def on_broken_pipe(self) -> None:
"""This function is called when a `BrokenPipeError` is raised.
This can occur when piping Textual output in Linux and macOS.
The default implementation is to exit the app, but you could implement
this method in a subclass to change the behavior.
See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details.
"""
self.quiet = True
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
raise SystemExit(1)

def _check_buffer(self) -> None:
"""Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False)
Rendering is supported on Windows, Unix and Jupyter environments. For
Expand All @@ -1995,8 +2014,17 @@ def _check_buffer(self) -> None:
if self.quiet:
del self._buffer[:]
return

try:
self._write_buffer()
except BrokenPipeError:
self.on_broken_pipe()

def _write_buffer(self) -> None:
"""Write the buffer to the output file."""

with self._lock:
if self.record:
if self.record and not self._buffer_index:
with self._record_buffer_lock:
self._record_buffer.extend(self._buffer[:])

Expand Down Expand Up @@ -2166,7 +2194,7 @@ def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> N
"""
text = self.export_text(clear=clear, styles=styles)
with open(path, "wt", encoding="utf-8") as write_file:
with open(path, "w", encoding="utf-8") as write_file:
write_file.write(text)

def export_html(
Expand Down Expand Up @@ -2272,7 +2300,7 @@ def save_html(
code_format=code_format,
inline_styles=inline_styles,
)
with open(path, "wt", encoding="utf-8") as write_file:
with open(path, "w", encoding="utf-8") as write_file:
write_file.write(html)

def export_svg(
Expand Down Expand Up @@ -2561,7 +2589,7 @@ def save_svg(
font_aspect_ratio=font_aspect_ratio,
unique_id=unique_id,
)
with open(path, "wt", encoding="utf-8") as write_file:
with open(path, "w", encoding="utf-8") as write_file:
write_file.write(svg)


Expand Down
3 changes: 2 additions & 1 deletion src/pip/_vendor/rich/default_styles.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"logging.level.notset": Style(dim=True),
"logging.level.debug": Style(color="green"),
"logging.level.info": Style(color="blue"),
"logging.level.warning": Style(color="red"),
"logging.level.warning": Style(color="yellow"),
"logging.level.error": Style(color="red", bold=True),
"logging.level.critical": Style(color="red", bold=True, reverse=True),
"log.level": Style.null(),
Expand Down Expand Up @@ -120,6 +120,7 @@
"traceback.exc_type": Style(color="bright_red", bold=True),
"traceback.exc_value": Style.null(),
"traceback.offset": Style(color="bright_red", bold=True),
"traceback.error_range": Style(underline=True, bold=True, dim=False),
"bar.back": Style(color="grey23"),
"bar.complete": Style(color="rgb(249,38,114)"),
"bar.finished": Style(color="rgb(114,156,31)"),
Expand Down
3 changes: 1 addition & 2 deletions src/pip/_vendor/rich/filesize.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2
The functions declared in this module should cover the different
Expand Down Expand Up @@ -27,7 +26,7 @@ def _to_str(
if size == 1:
return "1 byte"
elif size < base:
return "{:,} bytes".format(size)
return f"{size:,} bytes"

for i, suffix in enumerate(suffixes, 2): # noqa: B007
unit = base**i
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_vendor/rich/highlighter.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class ReprHighlighter(RegexHighlighter):
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[-+]?\d+?)?\b|0x[0-9a-fA-F]*)",
r"(?P<path>\B(/[-\w._+]+)*\/)(?P<filename>[-\w._+]*)?",
r"(?<![\\\w])(?P<str>b?'''.*?(?<!\\)'''|b?'.*?(?<!\\)'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
r"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~]*)",
r"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)",
),
]

Expand Down
2 changes: 1 addition & 1 deletion src/pip/_vendor/rich/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class Live(JupyterMixin, RenderHook):
Args:
renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.
console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.
console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.
screen (bool, optional): Enable alternate screen mode. Defaults to False.
auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True
refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4.
Expand Down
Loading

0 comments on commit 0daddaf

Please sign in to comment.