Skip to content

Commit

Permalink
Merge pull request #11672 from pradyunsg/update-rich
Browse files Browse the repository at this point in the history
Update `rich` to 12.6.0
  • Loading branch information
pradyunsg authored Dec 28, 2022
2 parents 8dbb8b9 + 1b33f4b commit cecd346
Show file tree
Hide file tree
Showing 25 changed files with 342 additions and 101 deletions.
5 changes: 0 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@ on:
schedule:
- cron: 0 0 * * MON # Run every Monday at 00:00 UTC

env:
# The "FORCE_COLOR" variable, when set to 1,
# tells Nox to colorize itself.
FORCE_COLOR: "1"

concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: true
Expand Down
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 12.6.0
7 changes: 4 additions & 3 deletions src/pip/_vendor/rich/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from ._extension import load_ipython_extension # noqa: F401

__all__ = ["get_console", "reconfigure", "print", "inspect"]
__all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"]

if TYPE_CHECKING:
from .console import Console
Expand Down Expand Up @@ -40,7 +40,8 @@ def reconfigure(*args: Any, **kwargs: Any) -> None:
"""Reconfigures the global console by replacing it with another.
Args:
console (Console): Replacement console instance.
*args (Any): Positional arguments for the replacement :class:`~rich.console.Console`.
**kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`.
"""
from pip._vendor.rich.console import Console

Expand Down Expand Up @@ -80,7 +81,7 @@ def print_json(
indent: Union[None, int, str] = 2,
highlight: bool = True,
skip_keys: bool = False,
ensure_ascii: bool = True,
ensure_ascii: bool = False,
check_circular: bool = True,
allow_nan: bool = True,
default: Optional[Callable[[Any], Any]] = None,
Expand Down
8 changes: 0 additions & 8 deletions src/pip/_vendor/rich/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,6 @@ def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:

c = Console(record=True)
c.print(test_card)
# c.save_svg(
# path="/Users/darrenburns/Library/Application Support/JetBrains/PyCharm2021.3/scratches/svg_export.svg",
# title="Rich can export to SVG",
# )

print(f"rendered in {pre_cache_taken}ms (cold cache)")
print(f"rendered in {taken}ms (warm cache)")
Expand All @@ -247,10 +243,6 @@ def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
"Textualize",
"[u blue link=https://github.com/textualize]https://github.com/textualize",
)
sponsor_message.add_row(
"Buy devs a :coffee:",
"[u blue link=https://ko-fi.com/textualize]https://ko-fi.com/textualize",
)
sponsor_message.add_row(
"Twitter",
"[u blue link=https://twitter.com/willmcgugan]https://twitter.com/willmcgugan",
Expand Down
83 changes: 83 additions & 0 deletions src/pip/_vendor/rich/_null_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from types import TracebackType
from typing import IO, Iterable, Iterator, List, Optional, Type


class NullFile(IO[str]):

# TODO: "mode", "name" and "closed" are only required for Python 3.6.

@property
def mode(self) -> str:
return ""

@property
def name(self) -> str:
return "NullFile"

def closed(self) -> bool:
return False

def close(self) -> None:
pass

def isatty(self) -> bool:
return False

def read(self, __n: int = 1) -> str:
return ""

def readable(self) -> bool:
return False

def readline(self, __limit: int = 1) -> str:
return ""

def readlines(self, __hint: int = 1) -> List[str]:
return []

def seek(self, __offset: int, __whence: int = 1) -> int:
return 0

def seekable(self) -> bool:
return False

def tell(self) -> int:
return 0

def truncate(self, __size: Optional[int] = 1) -> int:
return 0

def writable(self) -> bool:
return False

def writelines(self, __lines: Iterable[str]) -> None:
pass

def __next__(self) -> str:
return ""

def __iter__(self) -> Iterator[str]:
return iter([""])

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

def __exit__(
self,
__t: Optional[Type[BaseException]],
__value: Optional[BaseException],
__traceback: Optional[TracebackType],
) -> None:
pass

def write(self, text: str) -> int:
return 0

def flush(self) -> None:
pass

def fileno(self) -> int:
return -1


NULL_FILE = NullFile()
2 changes: 1 addition & 1 deletion src/pip/_vendor/rich/ansi.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def __init__(self) -> None:
self.style = Style.null()

def decode(self, terminal_text: str) -> Iterable[Text]:
"""Decode ANSI codes in an interable of lines.
"""Decode ANSI codes in an iterable of lines.
Args:
lines (Iterable[str]): An iterable of lines of terminal output.
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_vendor/rich/box.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,4 +514,4 @@ def get_bottom(self, widths: Iterable[int]) -> str:
columns.add_renderable(table)
console.print(columns)

# console.save_html("box.html", inline_styles=True)
# console.save_svg("box.svg")
5 changes: 4 additions & 1 deletion src/pip/_vendor/rich/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ class ColorSystem(IntEnum):
def __repr__(self) -> str:
return f"ColorSystem.{self.name}"

def __str__(self) -> str:
return repr(self)


class ColorType(IntEnum):
"""Type of color stored in Color class."""
Expand Down Expand Up @@ -310,7 +313,7 @@ class Color(NamedTuple):
"""A triplet of color components, if an RGB color."""

def __rich__(self) -> "Text":
"""Dispays the actual color if Rich printed."""
"""Displays the actual color if Rich printed."""
from .style import Style
from .text import Text

Expand Down
78 changes: 59 additions & 19 deletions src/pip/_vendor/rich/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
cast,
)

from pip._vendor.rich._null_file import NULL_FILE

if sys.version_info >= (3, 8):
from typing import Literal, Protocol, runtime_checkable
else:
Expand Down Expand Up @@ -104,7 +106,11 @@ class NoChange:
_STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO)


_TERM_COLORS = {"256color": ColorSystem.EIGHT_BIT, "16color": ColorSystem.STANDARD}
_TERM_COLORS = {
"kitty": ColorSystem.EIGHT_BIT,
"256color": ColorSystem.EIGHT_BIT,
"16color": ColorSystem.STANDARD,
}


class ConsoleDimensions(NamedTuple):
Expand Down Expand Up @@ -516,7 +522,11 @@ def _is_jupyter() -> bool: # pragma: no cover
return False
ipython = get_ipython() # type: ignore[name-defined]
shell = ipython.__class__.__name__
if "google.colab" in str(ipython.__class__) or shell == "ZMQInteractiveShell":
if (
"google.colab" in str(ipython.__class__)
or os.getenv("DATABRICKS_RUNTIME_VERSION")
or shell == "ZMQInteractiveShell"
):
return True # Jupyter notebook or qtconsole
elif shell == "TerminalInteractiveShell":
return False # Terminal running IPython
Expand Down Expand Up @@ -697,7 +707,16 @@ def __init__(
self._height = height

self._color_system: Optional[ColorSystem]
self._force_terminal = force_terminal

self._force_terminal = None
if force_terminal is not None:
self._force_terminal = force_terminal
else:
# If FORCE_COLOR env var has any value at all, we force terminal.
force_color = self._environ.get("FORCE_COLOR")
if force_color is not None:
self._force_terminal = True

self._file = file
self.quiet = quiet
self.stderr = stderr
Expand Down Expand Up @@ -746,6 +765,8 @@ def file(self) -> IO[str]:
"""Get the file object to write to."""
file = self._file or (sys.stderr if self.stderr else sys.stdout)
file = getattr(file, "rich_proxied_file", file)
if file is None:
file = NULL_FILE
return file

@file.setter
Expand Down Expand Up @@ -1701,7 +1722,7 @@ def print_json(
indent: Union[None, int, str] = 2,
highlight: bool = True,
skip_keys: bool = False,
ensure_ascii: bool = True,
ensure_ascii: bool = False,
check_circular: bool = True,
allow_nan: bool = True,
default: Optional[Callable[[Any], Any]] = None,
Expand Down Expand Up @@ -1996,9 +2017,11 @@ def _check_buffer(self) -> None:
from pip._vendor.rich._win32_console import LegacyWindowsTerm
from pip._vendor.rich._windows_renderer import legacy_windows_render

legacy_windows_render(
self._buffer[:], LegacyWindowsTerm(self.file)
)
buffer = self._buffer[:]
if self.no_color and self._color_system:
buffer = list(Segment.remove_color(buffer))

legacy_windows_render(buffer, LegacyWindowsTerm(self.file))
else:
# Either a non-std stream on legacy Windows, or modern Windows.
text = self._render_buffer(self._buffer[:])
Expand Down Expand Up @@ -2238,18 +2261,24 @@ def export_svg(
theme: Optional[TerminalTheme] = None,
clear: bool = True,
code_format: str = CONSOLE_SVG_FORMAT,
font_aspect_ratio: float = 0.61,
unique_id: Optional[str] = None,
) -> str:
"""
Generate an SVG from the console contents (requires record=True in Console constructor).
Args:
path (str): The path to write the SVG to.
title (str): The title of the tab in the output image
title (str, optional): The title of the tab in the output image
theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
code_format (str): Format string used to generate the SVG. Rich will inject a number of variables
code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
into the string in order to form the final SVG output. The default template used and the variables
injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
If you aren't specifying a different font inside ``code_format``, you probably don't need this.
unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
ids). If not set, this defaults to a computed value based on the recorded content.
"""

from pip._vendor.rich.cells import cell_len
Expand Down Expand Up @@ -2293,7 +2322,7 @@ def get_svg_style(style: Style) -> str:

width = self.width
char_height = 20
char_width = char_height * 0.61
char_width = char_height * font_aspect_ratio
line_height = char_height * 1.22

margin_top = 1
Expand Down Expand Up @@ -2345,14 +2374,16 @@ def stringify(value: object) -> str:
if clear:
self._record_buffer.clear()

unique_id = "terminal-" + str(
zlib.adler32(
("".join(segment.text for segment in segments)).encode(
"utf-8", "ignore"
if unique_id is None:
unique_id = "terminal-" + str(
zlib.adler32(
("".join(repr(segment) for segment in segments)).encode(
"utf-8",
"ignore",
)
+ title.encode("utf-8", "ignore")
)
+ title.encode("utf-8", "ignore")
)
)
y = 0
for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)):
x = 0
Expand Down Expand Up @@ -2482,23 +2513,32 @@ def save_svg(
theme: Optional[TerminalTheme] = None,
clear: bool = True,
code_format: str = CONSOLE_SVG_FORMAT,
font_aspect_ratio: float = 0.61,
unique_id: Optional[str] = None,
) -> None:
"""Generate an SVG file from the console contents (requires record=True in Console constructor).
Args:
path (str): The path to write the SVG to.
title (str): The title of the tab in the output image
title (str, optional): The title of the tab in the output image
theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal
clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``
code_format (str): Format string used to generate the SVG. Rich will inject a number of variables
code_format (str, optional): Format string used to generate the SVG. Rich will inject a number of variables
into the string in order to form the final SVG output. The default template used and the variables
injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.
font_aspect_ratio (float, optional): The width to height ratio of the font used in the ``code_format``
string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font).
If you aren't specifying a different font inside ``code_format``, you probably don't need this.
unique_id (str, optional): unique id that is used as the prefix for various elements (CSS styles, node
ids). If not set, this defaults to a computed value based on the recorded content.
"""
svg = self.export_svg(
title=title,
theme=theme,
clear=clear,
code_format=code_format,
font_aspect_ratio=font_aspect_ratio,
unique_id=unique_id,
)
with open(path, "wt", encoding="utf-8") as write_file:
write_file.write(svg)
Expand Down
2 changes: 1 addition & 1 deletion src/pip/_vendor/rich/filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2
The functions declared in this module should cover the different
usecases needed to generate a string representation of a file size
use cases needed to generate a string representation of a file size
using several different units. Since there are many standards regarding
file size units, three different functions have been implemented.
Expand Down
4 changes: 2 additions & 2 deletions src/pip/_vendor/rich/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __init__(
indent: Union[None, int, str] = 2,
highlight: bool = True,
skip_keys: bool = False,
ensure_ascii: bool = True,
ensure_ascii: bool = False,
check_circular: bool = True,
allow_nan: bool = True,
default: Optional[Callable[[Any], Any]] = None,
Expand Down Expand Up @@ -56,7 +56,7 @@ def from_data(
indent: Union[None, int, str] = 2,
highlight: bool = True,
skip_keys: bool = False,
ensure_ascii: bool = True,
ensure_ascii: bool = False,
check_circular: bool = True,
allow_nan: bool = True,
default: Optional[Callable[[Any], Any]] = None,
Expand Down
Loading

0 comments on commit cecd346

Please sign in to comment.