Add files using upload-large-folder tool
Browse files- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/pager.py +34 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/palette.py +100 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/panel.py +317 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/pretty.py +1016 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/progress.py +1716 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/progress_bar.py +223 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/prompt.py +400 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/protocol.py +41 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/py.typed +0 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/region.py +10 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/repr.py +150 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/rule.py +130 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/scope.py +92 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/screen.py +54 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/segment.py +780 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/spinner.py +132 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/status.py +131 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/style.py +796 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/styled.py +42 -0
- .cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/syntax.py +988 -0
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/pager.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Pager(ABC):
|
| 6 |
+
"""Base class for a pager."""
|
| 7 |
+
|
| 8 |
+
@abstractmethod
|
| 9 |
+
def show(self, content: str) -> None:
|
| 10 |
+
"""Show content in pager.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
content (str): Content to be displayed.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SystemPager(Pager):
|
| 18 |
+
"""Uses the pager installed on the system."""
|
| 19 |
+
|
| 20 |
+
def _pager(self, content: str) -> Any: # pragma: no cover
|
| 21 |
+
return __import__("pydoc").pager(content)
|
| 22 |
+
|
| 23 |
+
def show(self, content: str) -> None:
|
| 24 |
+
"""Use the same pager used by pydoc."""
|
| 25 |
+
self._pager(content)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if __name__ == "__main__": # pragma: no cover
|
| 29 |
+
from .__main__ import make_test_card
|
| 30 |
+
from .console import Console
|
| 31 |
+
|
| 32 |
+
console = Console()
|
| 33 |
+
with console.pager(styles=True):
|
| 34 |
+
console.print(make_test_card())
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/palette.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from math import sqrt
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from typing import Sequence, Tuple, TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from .color_triplet import ColorTriplet
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from rich.table import Table
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Palette:
|
| 12 |
+
"""A palette of available colors."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, colors: Sequence[Tuple[int, int, int]]):
|
| 15 |
+
self._colors = colors
|
| 16 |
+
|
| 17 |
+
def __getitem__(self, number: int) -> ColorTriplet:
|
| 18 |
+
return ColorTriplet(*self._colors[number])
|
| 19 |
+
|
| 20 |
+
def __rich__(self) -> "Table":
|
| 21 |
+
from rich.color import Color
|
| 22 |
+
from rich.style import Style
|
| 23 |
+
from rich.text import Text
|
| 24 |
+
from rich.table import Table
|
| 25 |
+
|
| 26 |
+
table = Table(
|
| 27 |
+
"index",
|
| 28 |
+
"RGB",
|
| 29 |
+
"Color",
|
| 30 |
+
title="Palette",
|
| 31 |
+
caption=f"{len(self._colors)} colors",
|
| 32 |
+
highlight=True,
|
| 33 |
+
caption_justify="right",
|
| 34 |
+
)
|
| 35 |
+
for index, color in enumerate(self._colors):
|
| 36 |
+
table.add_row(
|
| 37 |
+
str(index),
|
| 38 |
+
repr(color),
|
| 39 |
+
Text(" " * 16, style=Style(bgcolor=Color.from_rgb(*color))),
|
| 40 |
+
)
|
| 41 |
+
return table
|
| 42 |
+
|
| 43 |
+
# This is somewhat inefficient and needs caching
|
| 44 |
+
@lru_cache(maxsize=1024)
|
| 45 |
+
def match(self, color: Tuple[int, int, int]) -> int:
|
| 46 |
+
"""Find a color from a palette that most closely matches a given color.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
color (Tuple[int, int, int]): RGB components in range 0 > 255.
|
| 50 |
+
|
| 51 |
+
Returns:
|
| 52 |
+
int: Index of closes matching color.
|
| 53 |
+
"""
|
| 54 |
+
red1, green1, blue1 = color
|
| 55 |
+
_sqrt = sqrt
|
| 56 |
+
get_color = self._colors.__getitem__
|
| 57 |
+
|
| 58 |
+
def get_color_distance(index: int) -> float:
|
| 59 |
+
"""Get the distance to a color."""
|
| 60 |
+
red2, green2, blue2 = get_color(index)
|
| 61 |
+
red_mean = (red1 + red2) // 2
|
| 62 |
+
red = red1 - red2
|
| 63 |
+
green = green1 - green2
|
| 64 |
+
blue = blue1 - blue2
|
| 65 |
+
return _sqrt(
|
| 66 |
+
(((512 + red_mean) * red * red) >> 8)
|
| 67 |
+
+ 4 * green * green
|
| 68 |
+
+ (((767 - red_mean) * blue * blue) >> 8)
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
min_index = min(range(len(self._colors)), key=get_color_distance)
|
| 72 |
+
return min_index
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__": # pragma: no cover
|
| 76 |
+
import colorsys
|
| 77 |
+
from typing import Iterable
|
| 78 |
+
from rich.color import Color
|
| 79 |
+
from rich.console import Console, ConsoleOptions
|
| 80 |
+
from rich.segment import Segment
|
| 81 |
+
from rich.style import Style
|
| 82 |
+
|
| 83 |
+
class ColorBox:
|
| 84 |
+
def __rich_console__(
|
| 85 |
+
self, console: Console, options: ConsoleOptions
|
| 86 |
+
) -> Iterable[Segment]:
|
| 87 |
+
height = console.size.height - 3
|
| 88 |
+
for y in range(0, height):
|
| 89 |
+
for x in range(options.max_width):
|
| 90 |
+
h = x / options.max_width
|
| 91 |
+
l = y / (height + 1)
|
| 92 |
+
r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)
|
| 93 |
+
r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0)
|
| 94 |
+
bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)
|
| 95 |
+
color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)
|
| 96 |
+
yield Segment("▄", Style(color=color, bgcolor=bgcolor))
|
| 97 |
+
yield Segment.line()
|
| 98 |
+
|
| 99 |
+
console = Console()
|
| 100 |
+
console.print(ColorBox())
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/panel.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, Optional
|
| 2 |
+
|
| 3 |
+
from .align import AlignMethod
|
| 4 |
+
from .box import ROUNDED, Box
|
| 5 |
+
from .cells import cell_len
|
| 6 |
+
from .jupyter import JupyterMixin
|
| 7 |
+
from .measure import Measurement, measure_renderables
|
| 8 |
+
from .padding import Padding, PaddingDimensions
|
| 9 |
+
from .segment import Segment
|
| 10 |
+
from .style import Style, StyleType
|
| 11 |
+
from .text import Text, TextType
|
| 12 |
+
|
| 13 |
+
if TYPE_CHECKING:
|
| 14 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Panel(JupyterMixin):
|
| 18 |
+
"""A console renderable that draws a border around its contents.
|
| 19 |
+
|
| 20 |
+
Example:
|
| 21 |
+
>>> console.print(Panel("Hello, World!"))
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
renderable (RenderableType): A console renderable object.
|
| 25 |
+
box (Box): A Box instance that defines the look of the border (see :ref:`appendix_box`. Defaults to box.ROUNDED.
|
| 26 |
+
title (Optional[TextType], optional): Optional title displayed in panel header. Defaults to None.
|
| 27 |
+
title_align (AlignMethod, optional): Alignment of title. Defaults to "center".
|
| 28 |
+
subtitle (Optional[TextType], optional): Optional subtitle displayed in panel footer. Defaults to None.
|
| 29 |
+
subtitle_align (AlignMethod, optional): Alignment of subtitle. Defaults to "center".
|
| 30 |
+
safe_box (bool, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.
|
| 31 |
+
expand (bool, optional): If True the panel will stretch to fill the console width, otherwise it will be sized to fit the contents. Defaults to True.
|
| 32 |
+
style (str, optional): The style of the panel (border and contents). Defaults to "none".
|
| 33 |
+
border_style (str, optional): The style of the border. Defaults to "none".
|
| 34 |
+
width (Optional[int], optional): Optional width of panel. Defaults to None to auto-detect.
|
| 35 |
+
height (Optional[int], optional): Optional height of panel. Defaults to None to auto-detect.
|
| 36 |
+
padding (Optional[PaddingDimensions]): Optional padding around renderable. Defaults to 0.
|
| 37 |
+
highlight (bool, optional): Enable automatic highlighting of panel title (if str). Defaults to False.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(
|
| 41 |
+
self,
|
| 42 |
+
renderable: "RenderableType",
|
| 43 |
+
box: Box = ROUNDED,
|
| 44 |
+
*,
|
| 45 |
+
title: Optional[TextType] = None,
|
| 46 |
+
title_align: AlignMethod = "center",
|
| 47 |
+
subtitle: Optional[TextType] = None,
|
| 48 |
+
subtitle_align: AlignMethod = "center",
|
| 49 |
+
safe_box: Optional[bool] = None,
|
| 50 |
+
expand: bool = True,
|
| 51 |
+
style: StyleType = "none",
|
| 52 |
+
border_style: StyleType = "none",
|
| 53 |
+
width: Optional[int] = None,
|
| 54 |
+
height: Optional[int] = None,
|
| 55 |
+
padding: PaddingDimensions = (0, 1),
|
| 56 |
+
highlight: bool = False,
|
| 57 |
+
) -> None:
|
| 58 |
+
self.renderable = renderable
|
| 59 |
+
self.box = box
|
| 60 |
+
self.title = title
|
| 61 |
+
self.title_align: AlignMethod = title_align
|
| 62 |
+
self.subtitle = subtitle
|
| 63 |
+
self.subtitle_align = subtitle_align
|
| 64 |
+
self.safe_box = safe_box
|
| 65 |
+
self.expand = expand
|
| 66 |
+
self.style = style
|
| 67 |
+
self.border_style = border_style
|
| 68 |
+
self.width = width
|
| 69 |
+
self.height = height
|
| 70 |
+
self.padding = padding
|
| 71 |
+
self.highlight = highlight
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def fit(
|
| 75 |
+
cls,
|
| 76 |
+
renderable: "RenderableType",
|
| 77 |
+
box: Box = ROUNDED,
|
| 78 |
+
*,
|
| 79 |
+
title: Optional[TextType] = None,
|
| 80 |
+
title_align: AlignMethod = "center",
|
| 81 |
+
subtitle: Optional[TextType] = None,
|
| 82 |
+
subtitle_align: AlignMethod = "center",
|
| 83 |
+
safe_box: Optional[bool] = None,
|
| 84 |
+
style: StyleType = "none",
|
| 85 |
+
border_style: StyleType = "none",
|
| 86 |
+
width: Optional[int] = None,
|
| 87 |
+
height: Optional[int] = None,
|
| 88 |
+
padding: PaddingDimensions = (0, 1),
|
| 89 |
+
highlight: bool = False,
|
| 90 |
+
) -> "Panel":
|
| 91 |
+
"""An alternative constructor that sets expand=False."""
|
| 92 |
+
return cls(
|
| 93 |
+
renderable,
|
| 94 |
+
box,
|
| 95 |
+
title=title,
|
| 96 |
+
title_align=title_align,
|
| 97 |
+
subtitle=subtitle,
|
| 98 |
+
subtitle_align=subtitle_align,
|
| 99 |
+
safe_box=safe_box,
|
| 100 |
+
style=style,
|
| 101 |
+
border_style=border_style,
|
| 102 |
+
width=width,
|
| 103 |
+
height=height,
|
| 104 |
+
padding=padding,
|
| 105 |
+
highlight=highlight,
|
| 106 |
+
expand=False,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def _title(self) -> Optional[Text]:
|
| 111 |
+
if self.title:
|
| 112 |
+
title_text = (
|
| 113 |
+
Text.from_markup(self.title)
|
| 114 |
+
if isinstance(self.title, str)
|
| 115 |
+
else self.title.copy()
|
| 116 |
+
)
|
| 117 |
+
title_text.end = ""
|
| 118 |
+
title_text.plain = title_text.plain.replace("\n", " ")
|
| 119 |
+
title_text.no_wrap = True
|
| 120 |
+
title_text.expand_tabs()
|
| 121 |
+
title_text.pad(1)
|
| 122 |
+
return title_text
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def _subtitle(self) -> Optional[Text]:
|
| 127 |
+
if self.subtitle:
|
| 128 |
+
subtitle_text = (
|
| 129 |
+
Text.from_markup(self.subtitle)
|
| 130 |
+
if isinstance(self.subtitle, str)
|
| 131 |
+
else self.subtitle.copy()
|
| 132 |
+
)
|
| 133 |
+
subtitle_text.end = ""
|
| 134 |
+
subtitle_text.plain = subtitle_text.plain.replace("\n", " ")
|
| 135 |
+
subtitle_text.no_wrap = True
|
| 136 |
+
subtitle_text.expand_tabs()
|
| 137 |
+
subtitle_text.pad(1)
|
| 138 |
+
return subtitle_text
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
def __rich_console__(
|
| 142 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 143 |
+
) -> "RenderResult":
|
| 144 |
+
_padding = Padding.unpack(self.padding)
|
| 145 |
+
renderable = (
|
| 146 |
+
Padding(self.renderable, _padding) if any(_padding) else self.renderable
|
| 147 |
+
)
|
| 148 |
+
style = console.get_style(self.style)
|
| 149 |
+
border_style = style + console.get_style(self.border_style)
|
| 150 |
+
width = (
|
| 151 |
+
options.max_width
|
| 152 |
+
if self.width is None
|
| 153 |
+
else min(options.max_width, self.width)
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
safe_box: bool = console.safe_box if self.safe_box is None else self.safe_box
|
| 157 |
+
box = self.box.substitute(options, safe=safe_box)
|
| 158 |
+
|
| 159 |
+
def align_text(
|
| 160 |
+
text: Text, width: int, align: str, character: str, style: Style
|
| 161 |
+
) -> Text:
|
| 162 |
+
"""Gets new aligned text.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
text (Text): Title or subtitle text.
|
| 166 |
+
width (int): Desired width.
|
| 167 |
+
align (str): Alignment.
|
| 168 |
+
character (str): Character for alignment.
|
| 169 |
+
style (Style): Border style
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Text: New text instance
|
| 173 |
+
"""
|
| 174 |
+
text = text.copy()
|
| 175 |
+
text.truncate(width)
|
| 176 |
+
excess_space = width - cell_len(text.plain)
|
| 177 |
+
if text.style:
|
| 178 |
+
text.stylize(console.get_style(text.style))
|
| 179 |
+
|
| 180 |
+
if excess_space:
|
| 181 |
+
if align == "left":
|
| 182 |
+
return Text.assemble(
|
| 183 |
+
text,
|
| 184 |
+
(character * excess_space, style),
|
| 185 |
+
no_wrap=True,
|
| 186 |
+
end="",
|
| 187 |
+
)
|
| 188 |
+
elif align == "center":
|
| 189 |
+
left = excess_space // 2
|
| 190 |
+
return Text.assemble(
|
| 191 |
+
(character * left, style),
|
| 192 |
+
text,
|
| 193 |
+
(character * (excess_space - left), style),
|
| 194 |
+
no_wrap=True,
|
| 195 |
+
end="",
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
return Text.assemble(
|
| 199 |
+
(character * excess_space, style),
|
| 200 |
+
text,
|
| 201 |
+
no_wrap=True,
|
| 202 |
+
end="",
|
| 203 |
+
)
|
| 204 |
+
return text
|
| 205 |
+
|
| 206 |
+
title_text = self._title
|
| 207 |
+
if title_text is not None:
|
| 208 |
+
title_text.stylize_before(border_style)
|
| 209 |
+
|
| 210 |
+
child_width = (
|
| 211 |
+
width - 2
|
| 212 |
+
if self.expand
|
| 213 |
+
else console.measure(
|
| 214 |
+
renderable, options=options.update_width(width - 2)
|
| 215 |
+
).maximum
|
| 216 |
+
)
|
| 217 |
+
child_height = self.height or options.height or None
|
| 218 |
+
if child_height:
|
| 219 |
+
child_height -= 2
|
| 220 |
+
if title_text is not None:
|
| 221 |
+
child_width = min(
|
| 222 |
+
options.max_width - 2, max(child_width, title_text.cell_len + 2)
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
width = child_width + 2
|
| 226 |
+
child_options = options.update(
|
| 227 |
+
width=child_width, height=child_height, highlight=self.highlight
|
| 228 |
+
)
|
| 229 |
+
lines = console.render_lines(renderable, child_options, style=style)
|
| 230 |
+
|
| 231 |
+
line_start = Segment(box.mid_left, border_style)
|
| 232 |
+
line_end = Segment(f"{box.mid_right}", border_style)
|
| 233 |
+
new_line = Segment.line()
|
| 234 |
+
if title_text is None or width <= 4:
|
| 235 |
+
yield Segment(box.get_top([width - 2]), border_style)
|
| 236 |
+
else:
|
| 237 |
+
title_text = align_text(
|
| 238 |
+
title_text,
|
| 239 |
+
width - 4,
|
| 240 |
+
self.title_align,
|
| 241 |
+
box.top,
|
| 242 |
+
border_style,
|
| 243 |
+
)
|
| 244 |
+
yield Segment(box.top_left + box.top, border_style)
|
| 245 |
+
yield from console.render(title_text, child_options.update_width(width - 4))
|
| 246 |
+
yield Segment(box.top + box.top_right, border_style)
|
| 247 |
+
|
| 248 |
+
yield new_line
|
| 249 |
+
for line in lines:
|
| 250 |
+
yield line_start
|
| 251 |
+
yield from line
|
| 252 |
+
yield line_end
|
| 253 |
+
yield new_line
|
| 254 |
+
|
| 255 |
+
subtitle_text = self._subtitle
|
| 256 |
+
if subtitle_text is not None:
|
| 257 |
+
subtitle_text.stylize_before(border_style)
|
| 258 |
+
|
| 259 |
+
if subtitle_text is None or width <= 4:
|
| 260 |
+
yield Segment(box.get_bottom([width - 2]), border_style)
|
| 261 |
+
else:
|
| 262 |
+
subtitle_text = align_text(
|
| 263 |
+
subtitle_text,
|
| 264 |
+
width - 4,
|
| 265 |
+
self.subtitle_align,
|
| 266 |
+
box.bottom,
|
| 267 |
+
border_style,
|
| 268 |
+
)
|
| 269 |
+
yield Segment(box.bottom_left + box.bottom, border_style)
|
| 270 |
+
yield from console.render(
|
| 271 |
+
subtitle_text, child_options.update_width(width - 4)
|
| 272 |
+
)
|
| 273 |
+
yield Segment(box.bottom + box.bottom_right, border_style)
|
| 274 |
+
|
| 275 |
+
yield new_line
|
| 276 |
+
|
| 277 |
+
def __rich_measure__(
|
| 278 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 279 |
+
) -> "Measurement":
|
| 280 |
+
_title = self._title
|
| 281 |
+
_, right, _, left = Padding.unpack(self.padding)
|
| 282 |
+
padding = left + right
|
| 283 |
+
renderables = [self.renderable, _title] if _title else [self.renderable]
|
| 284 |
+
|
| 285 |
+
if self.width is None:
|
| 286 |
+
width = (
|
| 287 |
+
measure_renderables(
|
| 288 |
+
console,
|
| 289 |
+
options.update_width(options.max_width - padding - 2),
|
| 290 |
+
renderables,
|
| 291 |
+
).maximum
|
| 292 |
+
+ padding
|
| 293 |
+
+ 2
|
| 294 |
+
)
|
| 295 |
+
else:
|
| 296 |
+
width = self.width
|
| 297 |
+
return Measurement(width, width)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
if __name__ == "__main__": # pragma: no cover
|
| 301 |
+
from .console import Console
|
| 302 |
+
|
| 303 |
+
c = Console()
|
| 304 |
+
|
| 305 |
+
from .box import DOUBLE, ROUNDED
|
| 306 |
+
from .padding import Padding
|
| 307 |
+
|
| 308 |
+
p = Panel(
|
| 309 |
+
"Hello, World!",
|
| 310 |
+
title="rich.Panel",
|
| 311 |
+
style="white on blue",
|
| 312 |
+
box=DOUBLE,
|
| 313 |
+
padding=1,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
c.print()
|
| 317 |
+
c.print(p)
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/pretty.py
ADDED
|
@@ -0,0 +1,1016 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import builtins
|
| 2 |
+
import collections
|
| 3 |
+
import dataclasses
|
| 4 |
+
import inspect
|
| 5 |
+
import os
|
| 6 |
+
import reprlib
|
| 7 |
+
import sys
|
| 8 |
+
from array import array
|
| 9 |
+
from collections import Counter, UserDict, UserList, defaultdict, deque
|
| 10 |
+
from dataclasses import dataclass, fields, is_dataclass
|
| 11 |
+
from inspect import isclass
|
| 12 |
+
from itertools import islice
|
| 13 |
+
from types import MappingProxyType
|
| 14 |
+
from typing import (
|
| 15 |
+
TYPE_CHECKING,
|
| 16 |
+
Any,
|
| 17 |
+
Callable,
|
| 18 |
+
DefaultDict,
|
| 19 |
+
Deque,
|
| 20 |
+
Dict,
|
| 21 |
+
Iterable,
|
| 22 |
+
List,
|
| 23 |
+
Optional,
|
| 24 |
+
Sequence,
|
| 25 |
+
Set,
|
| 26 |
+
Tuple,
|
| 27 |
+
Union,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
from rich.repr import RichReprResult
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import attr as _attr_module
|
| 34 |
+
|
| 35 |
+
_has_attrs = hasattr(_attr_module, "ib")
|
| 36 |
+
except ImportError: # pragma: no cover
|
| 37 |
+
_has_attrs = False
|
| 38 |
+
|
| 39 |
+
from . import get_console
|
| 40 |
+
from ._loop import loop_last
|
| 41 |
+
from ._pick import pick_bool
|
| 42 |
+
from .abc import RichRenderable
|
| 43 |
+
from .cells import cell_len
|
| 44 |
+
from .highlighter import ReprHighlighter
|
| 45 |
+
from .jupyter import JupyterMixin, JupyterRenderable
|
| 46 |
+
from .measure import Measurement
|
| 47 |
+
from .text import Text
|
| 48 |
+
|
| 49 |
+
if TYPE_CHECKING:
|
| 50 |
+
from .console import (
|
| 51 |
+
Console,
|
| 52 |
+
ConsoleOptions,
|
| 53 |
+
HighlighterType,
|
| 54 |
+
JustifyMethod,
|
| 55 |
+
OverflowMethod,
|
| 56 |
+
RenderResult,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _is_attr_object(obj: Any) -> bool:
|
| 61 |
+
"""Check if an object was created with attrs module."""
|
| 62 |
+
return _has_attrs and _attr_module.has(type(obj))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _get_attr_fields(obj: Any) -> Sequence["_attr_module.Attribute[Any]"]:
|
| 66 |
+
"""Get fields for an attrs object."""
|
| 67 |
+
return _attr_module.fields(type(obj)) if _has_attrs else []
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _is_dataclass_repr(obj: object) -> bool:
|
| 71 |
+
"""Check if an instance of a dataclass contains the default repr.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
obj (object): A dataclass instance.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
bool: True if the default repr is used, False if there is a custom repr.
|
| 78 |
+
"""
|
| 79 |
+
# Digging in to a lot of internals here
|
| 80 |
+
# Catching all exceptions in case something is missing on a non CPython implementation
|
| 81 |
+
try:
|
| 82 |
+
return obj.__repr__.__code__.co_filename in (
|
| 83 |
+
dataclasses.__file__,
|
| 84 |
+
reprlib.__file__,
|
| 85 |
+
)
|
| 86 |
+
except Exception: # pragma: no coverage
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
_dummy_namedtuple = collections.namedtuple("_dummy_namedtuple", [])
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _has_default_namedtuple_repr(obj: object) -> bool:
|
| 94 |
+
"""Check if an instance of namedtuple contains the default repr
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
obj (object): A namedtuple
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
bool: True if the default repr is used, False if there's a custom repr.
|
| 101 |
+
"""
|
| 102 |
+
obj_file = None
|
| 103 |
+
try:
|
| 104 |
+
obj_file = inspect.getfile(obj.__repr__)
|
| 105 |
+
except (OSError, TypeError):
|
| 106 |
+
# OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available.
|
| 107 |
+
# TypeError trapped defensively, in case of object without filename slips through.
|
| 108 |
+
pass
|
| 109 |
+
default_repr_file = inspect.getfile(_dummy_namedtuple.__repr__)
|
| 110 |
+
return obj_file == default_repr_file
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _ipy_display_hook(
|
| 114 |
+
value: Any,
|
| 115 |
+
console: Optional["Console"] = None,
|
| 116 |
+
overflow: "OverflowMethod" = "ignore",
|
| 117 |
+
crop: bool = False,
|
| 118 |
+
indent_guides: bool = False,
|
| 119 |
+
max_length: Optional[int] = None,
|
| 120 |
+
max_string: Optional[int] = None,
|
| 121 |
+
max_depth: Optional[int] = None,
|
| 122 |
+
expand_all: bool = False,
|
| 123 |
+
) -> Union[str, None]:
|
| 124 |
+
# needed here to prevent circular import:
|
| 125 |
+
from .console import ConsoleRenderable
|
| 126 |
+
|
| 127 |
+
# always skip rich generated jupyter renderables or None values
|
| 128 |
+
if _safe_isinstance(value, JupyterRenderable) or value is None:
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
console = console or get_console()
|
| 132 |
+
|
| 133 |
+
with console.capture() as capture:
|
| 134 |
+
# certain renderables should start on a new line
|
| 135 |
+
if _safe_isinstance(value, ConsoleRenderable):
|
| 136 |
+
console.line()
|
| 137 |
+
console.print(
|
| 138 |
+
(
|
| 139 |
+
value
|
| 140 |
+
if _safe_isinstance(value, RichRenderable)
|
| 141 |
+
else Pretty(
|
| 142 |
+
value,
|
| 143 |
+
overflow=overflow,
|
| 144 |
+
indent_guides=indent_guides,
|
| 145 |
+
max_length=max_length,
|
| 146 |
+
max_string=max_string,
|
| 147 |
+
max_depth=max_depth,
|
| 148 |
+
expand_all=expand_all,
|
| 149 |
+
margin=12,
|
| 150 |
+
)
|
| 151 |
+
),
|
| 152 |
+
crop=crop,
|
| 153 |
+
new_line_start=True,
|
| 154 |
+
end="",
|
| 155 |
+
)
|
| 156 |
+
# strip trailing newline, not usually part of a text repr
|
| 157 |
+
# I'm not sure if this should be prevented at a lower level
|
| 158 |
+
return capture.get().rstrip("\n")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _safe_isinstance(
|
| 162 |
+
obj: object, class_or_tuple: Union[type, Tuple[type, ...]]
|
| 163 |
+
) -> bool:
|
| 164 |
+
"""isinstance can fail in rare cases, for example types with no __class__"""
|
| 165 |
+
try:
|
| 166 |
+
return isinstance(obj, class_or_tuple)
|
| 167 |
+
except Exception:
|
| 168 |
+
return False
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def install(
|
| 172 |
+
console: Optional["Console"] = None,
|
| 173 |
+
overflow: "OverflowMethod" = "ignore",
|
| 174 |
+
crop: bool = False,
|
| 175 |
+
indent_guides: bool = False,
|
| 176 |
+
max_length: Optional[int] = None,
|
| 177 |
+
max_string: Optional[int] = None,
|
| 178 |
+
max_depth: Optional[int] = None,
|
| 179 |
+
expand_all: bool = False,
|
| 180 |
+
) -> None:
|
| 181 |
+
"""Install automatic pretty printing in the Python REPL.
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.
|
| 185 |
+
overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to "ignore".
|
| 186 |
+
crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.
|
| 187 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to False.
|
| 188 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 189 |
+
Defaults to None.
|
| 190 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
|
| 191 |
+
max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
|
| 192 |
+
expand_all (bool, optional): Expand all containers. Defaults to False.
|
| 193 |
+
max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
|
| 194 |
+
"""
|
| 195 |
+
from rich import get_console
|
| 196 |
+
|
| 197 |
+
console = console or get_console()
|
| 198 |
+
assert console is not None
|
| 199 |
+
|
| 200 |
+
def display_hook(value: Any) -> None:
|
| 201 |
+
"""Replacement sys.displayhook which prettifies objects with Rich."""
|
| 202 |
+
if value is not None:
|
| 203 |
+
assert console is not None
|
| 204 |
+
builtins._ = None # type: ignore[attr-defined]
|
| 205 |
+
console.print(
|
| 206 |
+
(
|
| 207 |
+
value
|
| 208 |
+
if _safe_isinstance(value, RichRenderable)
|
| 209 |
+
else Pretty(
|
| 210 |
+
value,
|
| 211 |
+
overflow=overflow,
|
| 212 |
+
indent_guides=indent_guides,
|
| 213 |
+
max_length=max_length,
|
| 214 |
+
max_string=max_string,
|
| 215 |
+
max_depth=max_depth,
|
| 216 |
+
expand_all=expand_all,
|
| 217 |
+
)
|
| 218 |
+
),
|
| 219 |
+
crop=crop,
|
| 220 |
+
)
|
| 221 |
+
builtins._ = value # type: ignore[attr-defined]
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
ip = get_ipython() # type: ignore[name-defined]
|
| 225 |
+
except NameError:
|
| 226 |
+
sys.displayhook = display_hook
|
| 227 |
+
else:
|
| 228 |
+
from IPython.core.formatters import BaseFormatter
|
| 229 |
+
|
| 230 |
+
class RichFormatter(BaseFormatter): # type: ignore[misc]
|
| 231 |
+
pprint: bool = True
|
| 232 |
+
|
| 233 |
+
def __call__(self, value: Any) -> Any:
|
| 234 |
+
if self.pprint:
|
| 235 |
+
return _ipy_display_hook(
|
| 236 |
+
value,
|
| 237 |
+
console=console,
|
| 238 |
+
overflow=overflow,
|
| 239 |
+
indent_guides=indent_guides,
|
| 240 |
+
max_length=max_length,
|
| 241 |
+
max_string=max_string,
|
| 242 |
+
max_depth=max_depth,
|
| 243 |
+
expand_all=expand_all,
|
| 244 |
+
)
|
| 245 |
+
else:
|
| 246 |
+
return repr(value)
|
| 247 |
+
|
| 248 |
+
# replace plain text formatter with rich formatter
|
| 249 |
+
rich_formatter = RichFormatter()
|
| 250 |
+
ip.display_formatter.formatters["text/plain"] = rich_formatter
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class Pretty(JupyterMixin):
|
| 254 |
+
"""A rich renderable that pretty prints an object.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
_object (Any): An object to pretty print.
|
| 258 |
+
highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.
|
| 259 |
+
indent_size (int, optional): Number of spaces in indent. Defaults to 4.
|
| 260 |
+
justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.
|
| 261 |
+
overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.
|
| 262 |
+
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.
|
| 263 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to False.
|
| 264 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 265 |
+
Defaults to None.
|
| 266 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
|
| 267 |
+
max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.
|
| 268 |
+
expand_all (bool, optional): Expand all containers. Defaults to False.
|
| 269 |
+
margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.
|
| 270 |
+
insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
def __init__(
|
| 274 |
+
self,
|
| 275 |
+
_object: Any,
|
| 276 |
+
highlighter: Optional["HighlighterType"] = None,
|
| 277 |
+
*,
|
| 278 |
+
indent_size: int = 4,
|
| 279 |
+
justify: Optional["JustifyMethod"] = None,
|
| 280 |
+
overflow: Optional["OverflowMethod"] = None,
|
| 281 |
+
no_wrap: Optional[bool] = False,
|
| 282 |
+
indent_guides: bool = False,
|
| 283 |
+
max_length: Optional[int] = None,
|
| 284 |
+
max_string: Optional[int] = None,
|
| 285 |
+
max_depth: Optional[int] = None,
|
| 286 |
+
expand_all: bool = False,
|
| 287 |
+
margin: int = 0,
|
| 288 |
+
insert_line: bool = False,
|
| 289 |
+
) -> None:
|
| 290 |
+
self._object = _object
|
| 291 |
+
self.highlighter = highlighter or ReprHighlighter()
|
| 292 |
+
self.indent_size = indent_size
|
| 293 |
+
self.justify: Optional["JustifyMethod"] = justify
|
| 294 |
+
self.overflow: Optional["OverflowMethod"] = overflow
|
| 295 |
+
self.no_wrap = no_wrap
|
| 296 |
+
self.indent_guides = indent_guides
|
| 297 |
+
self.max_length = max_length
|
| 298 |
+
self.max_string = max_string
|
| 299 |
+
self.max_depth = max_depth
|
| 300 |
+
self.expand_all = expand_all
|
| 301 |
+
self.margin = margin
|
| 302 |
+
self.insert_line = insert_line
|
| 303 |
+
|
| 304 |
+
def __rich_console__(
|
| 305 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 306 |
+
) -> "RenderResult":
|
| 307 |
+
pretty_str = pretty_repr(
|
| 308 |
+
self._object,
|
| 309 |
+
max_width=options.max_width - self.margin,
|
| 310 |
+
indent_size=self.indent_size,
|
| 311 |
+
max_length=self.max_length,
|
| 312 |
+
max_string=self.max_string,
|
| 313 |
+
max_depth=self.max_depth,
|
| 314 |
+
expand_all=self.expand_all,
|
| 315 |
+
)
|
| 316 |
+
pretty_text = Text.from_ansi(
|
| 317 |
+
pretty_str,
|
| 318 |
+
justify=self.justify or options.justify,
|
| 319 |
+
overflow=self.overflow or options.overflow,
|
| 320 |
+
no_wrap=pick_bool(self.no_wrap, options.no_wrap),
|
| 321 |
+
style="pretty",
|
| 322 |
+
)
|
| 323 |
+
pretty_text = (
|
| 324 |
+
self.highlighter(pretty_text)
|
| 325 |
+
if pretty_text
|
| 326 |
+
else Text(
|
| 327 |
+
f"{type(self._object)}.__repr__ returned empty string",
|
| 328 |
+
style="dim italic",
|
| 329 |
+
)
|
| 330 |
+
)
|
| 331 |
+
if self.indent_guides and not options.ascii_only:
|
| 332 |
+
pretty_text = pretty_text.with_indent_guides(
|
| 333 |
+
self.indent_size, style="repr.indent"
|
| 334 |
+
)
|
| 335 |
+
if self.insert_line and "\n" in pretty_text:
|
| 336 |
+
yield ""
|
| 337 |
+
yield pretty_text
|
| 338 |
+
|
| 339 |
+
def __rich_measure__(
|
| 340 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 341 |
+
) -> "Measurement":
|
| 342 |
+
pretty_str = pretty_repr(
|
| 343 |
+
self._object,
|
| 344 |
+
max_width=options.max_width,
|
| 345 |
+
indent_size=self.indent_size,
|
| 346 |
+
max_length=self.max_length,
|
| 347 |
+
max_string=self.max_string,
|
| 348 |
+
max_depth=self.max_depth,
|
| 349 |
+
expand_all=self.expand_all,
|
| 350 |
+
)
|
| 351 |
+
text_width = (
|
| 352 |
+
max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0
|
| 353 |
+
)
|
| 354 |
+
return Measurement(text_width, text_width)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:
|
| 358 |
+
return (
|
| 359 |
+
f"defaultdict({_object.default_factory!r}, {{",
|
| 360 |
+
"})",
|
| 361 |
+
f"defaultdict({_object.default_factory!r}, {{}})",
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _get_braces_for_deque(_object: Deque[Any]) -> Tuple[str, str, str]:
|
| 366 |
+
if _object.maxlen is None:
|
| 367 |
+
return ("deque([", "])", "deque()")
|
| 368 |
+
return (
|
| 369 |
+
"deque([",
|
| 370 |
+
f"], maxlen={_object.maxlen})",
|
| 371 |
+
f"deque(maxlen={_object.maxlen})",
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _get_braces_for_array(_object: "array[Any]") -> Tuple[str, str, str]:
|
| 376 |
+
return (f"array({_object.typecode!r}, [", "])", f"array({_object.typecode!r})")
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {
|
| 380 |
+
os._Environ: lambda _object: ("environ({", "})", "environ({})"),
|
| 381 |
+
array: _get_braces_for_array,
|
| 382 |
+
defaultdict: _get_braces_for_defaultdict,
|
| 383 |
+
Counter: lambda _object: ("Counter({", "})", "Counter()"),
|
| 384 |
+
deque: _get_braces_for_deque,
|
| 385 |
+
dict: lambda _object: ("{", "}", "{}"),
|
| 386 |
+
UserDict: lambda _object: ("{", "}", "{}"),
|
| 387 |
+
frozenset: lambda _object: ("frozenset({", "})", "frozenset()"),
|
| 388 |
+
list: lambda _object: ("[", "]", "[]"),
|
| 389 |
+
UserList: lambda _object: ("[", "]", "[]"),
|
| 390 |
+
set: lambda _object: ("{", "}", "set()"),
|
| 391 |
+
tuple: lambda _object: ("(", ")", "()"),
|
| 392 |
+
MappingProxyType: lambda _object: ("mappingproxy({", "})", "mappingproxy({})"),
|
| 393 |
+
}
|
| 394 |
+
_CONTAINERS = tuple(_BRACES.keys())
|
| 395 |
+
_MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def is_expandable(obj: Any) -> bool:
|
| 399 |
+
"""Check if an object may be expanded by pretty print."""
|
| 400 |
+
return (
|
| 401 |
+
_safe_isinstance(obj, _CONTAINERS)
|
| 402 |
+
or (is_dataclass(obj))
|
| 403 |
+
or (hasattr(obj, "__rich_repr__"))
|
| 404 |
+
or _is_attr_object(obj)
|
| 405 |
+
) and not isclass(obj)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
@dataclass
|
| 409 |
+
class Node:
|
| 410 |
+
"""A node in a repr tree. May be atomic or a container."""
|
| 411 |
+
|
| 412 |
+
key_repr: str = ""
|
| 413 |
+
value_repr: str = ""
|
| 414 |
+
open_brace: str = ""
|
| 415 |
+
close_brace: str = ""
|
| 416 |
+
empty: str = ""
|
| 417 |
+
last: bool = False
|
| 418 |
+
is_tuple: bool = False
|
| 419 |
+
is_namedtuple: bool = False
|
| 420 |
+
children: Optional[List["Node"]] = None
|
| 421 |
+
key_separator: str = ": "
|
| 422 |
+
separator: str = ", "
|
| 423 |
+
|
| 424 |
+
def iter_tokens(self) -> Iterable[str]:
|
| 425 |
+
"""Generate tokens for this node."""
|
| 426 |
+
if self.key_repr:
|
| 427 |
+
yield self.key_repr
|
| 428 |
+
yield self.key_separator
|
| 429 |
+
if self.value_repr:
|
| 430 |
+
yield self.value_repr
|
| 431 |
+
elif self.children is not None:
|
| 432 |
+
if self.children:
|
| 433 |
+
yield self.open_brace
|
| 434 |
+
if self.is_tuple and not self.is_namedtuple and len(self.children) == 1:
|
| 435 |
+
yield from self.children[0].iter_tokens()
|
| 436 |
+
yield ","
|
| 437 |
+
else:
|
| 438 |
+
for child in self.children:
|
| 439 |
+
yield from child.iter_tokens()
|
| 440 |
+
if not child.last:
|
| 441 |
+
yield self.separator
|
| 442 |
+
yield self.close_brace
|
| 443 |
+
else:
|
| 444 |
+
yield self.empty
|
| 445 |
+
|
| 446 |
+
def check_length(self, start_length: int, max_length: int) -> bool:
|
| 447 |
+
"""Check the length fits within a limit.
|
| 448 |
+
|
| 449 |
+
Args:
|
| 450 |
+
start_length (int): Starting length of the line (indent, prefix, suffix).
|
| 451 |
+
max_length (int): Maximum length.
|
| 452 |
+
|
| 453 |
+
Returns:
|
| 454 |
+
bool: True if the node can be rendered within max length, otherwise False.
|
| 455 |
+
"""
|
| 456 |
+
total_length = start_length
|
| 457 |
+
for token in self.iter_tokens():
|
| 458 |
+
total_length += cell_len(token)
|
| 459 |
+
if total_length > max_length:
|
| 460 |
+
return False
|
| 461 |
+
return True
|
| 462 |
+
|
| 463 |
+
def __str__(self) -> str:
|
| 464 |
+
repr_text = "".join(self.iter_tokens())
|
| 465 |
+
return repr_text
|
| 466 |
+
|
| 467 |
+
def render(
|
| 468 |
+
self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False
|
| 469 |
+
) -> str:
|
| 470 |
+
"""Render the node to a pretty repr.
|
| 471 |
+
|
| 472 |
+
Args:
|
| 473 |
+
max_width (int, optional): Maximum width of the repr. Defaults to 80.
|
| 474 |
+
indent_size (int, optional): Size of indents. Defaults to 4.
|
| 475 |
+
expand_all (bool, optional): Expand all levels. Defaults to False.
|
| 476 |
+
|
| 477 |
+
Returns:
|
| 478 |
+
str: A repr string of the original object.
|
| 479 |
+
"""
|
| 480 |
+
lines = [_Line(node=self, is_root=True)]
|
| 481 |
+
line_no = 0
|
| 482 |
+
while line_no < len(lines):
|
| 483 |
+
line = lines[line_no]
|
| 484 |
+
if line.expandable and not line.expanded:
|
| 485 |
+
if expand_all or not line.check_length(max_width):
|
| 486 |
+
lines[line_no : line_no + 1] = line.expand(indent_size)
|
| 487 |
+
line_no += 1
|
| 488 |
+
|
| 489 |
+
repr_str = "\n".join(str(line) for line in lines)
|
| 490 |
+
return repr_str
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
@dataclass
|
| 494 |
+
class _Line:
|
| 495 |
+
"""A line in repr output."""
|
| 496 |
+
|
| 497 |
+
parent: Optional["_Line"] = None
|
| 498 |
+
is_root: bool = False
|
| 499 |
+
node: Optional[Node] = None
|
| 500 |
+
text: str = ""
|
| 501 |
+
suffix: str = ""
|
| 502 |
+
whitespace: str = ""
|
| 503 |
+
expanded: bool = False
|
| 504 |
+
last: bool = False
|
| 505 |
+
|
| 506 |
+
@property
|
| 507 |
+
def expandable(self) -> bool:
|
| 508 |
+
"""Check if the line may be expanded."""
|
| 509 |
+
return bool(self.node is not None and self.node.children)
|
| 510 |
+
|
| 511 |
+
def check_length(self, max_length: int) -> bool:
|
| 512 |
+
"""Check this line fits within a given number of cells."""
|
| 513 |
+
start_length = (
|
| 514 |
+
len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix)
|
| 515 |
+
)
|
| 516 |
+
assert self.node is not None
|
| 517 |
+
return self.node.check_length(start_length, max_length)
|
| 518 |
+
|
| 519 |
+
def expand(self, indent_size: int) -> Iterable["_Line"]:
|
| 520 |
+
"""Expand this line by adding children on their own line."""
|
| 521 |
+
node = self.node
|
| 522 |
+
assert node is not None
|
| 523 |
+
whitespace = self.whitespace
|
| 524 |
+
assert node.children
|
| 525 |
+
if node.key_repr:
|
| 526 |
+
new_line = yield _Line(
|
| 527 |
+
text=f"{node.key_repr}{node.key_separator}{node.open_brace}",
|
| 528 |
+
whitespace=whitespace,
|
| 529 |
+
)
|
| 530 |
+
else:
|
| 531 |
+
new_line = yield _Line(text=node.open_brace, whitespace=whitespace)
|
| 532 |
+
child_whitespace = self.whitespace + " " * indent_size
|
| 533 |
+
tuple_of_one = node.is_tuple and len(node.children) == 1
|
| 534 |
+
for last, child in loop_last(node.children):
|
| 535 |
+
separator = "," if tuple_of_one else node.separator
|
| 536 |
+
line = _Line(
|
| 537 |
+
parent=new_line,
|
| 538 |
+
node=child,
|
| 539 |
+
whitespace=child_whitespace,
|
| 540 |
+
suffix=separator,
|
| 541 |
+
last=last and not tuple_of_one,
|
| 542 |
+
)
|
| 543 |
+
yield line
|
| 544 |
+
|
| 545 |
+
yield _Line(
|
| 546 |
+
text=node.close_brace,
|
| 547 |
+
whitespace=whitespace,
|
| 548 |
+
suffix=self.suffix,
|
| 549 |
+
last=self.last,
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
def __str__(self) -> str:
|
| 553 |
+
if self.last:
|
| 554 |
+
return f"{self.whitespace}{self.text}{self.node or ''}"
|
| 555 |
+
else:
|
| 556 |
+
return (
|
| 557 |
+
f"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}"
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def _is_namedtuple(obj: Any) -> bool:
|
| 562 |
+
"""Checks if an object is most likely a namedtuple. It is possible
|
| 563 |
+
to craft an object that passes this check and isn't a namedtuple, but
|
| 564 |
+
there is only a minuscule chance of this happening unintentionally.
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
obj (Any): The object to test
|
| 568 |
+
|
| 569 |
+
Returns:
|
| 570 |
+
bool: True if the object is a namedtuple. False otherwise.
|
| 571 |
+
"""
|
| 572 |
+
try:
|
| 573 |
+
fields = getattr(obj, "_fields", None)
|
| 574 |
+
except Exception:
|
| 575 |
+
# Being very defensive - if we cannot get the attr then its not a namedtuple
|
| 576 |
+
return False
|
| 577 |
+
return isinstance(obj, tuple) and isinstance(fields, tuple)
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def traverse(
|
| 581 |
+
_object: Any,
|
| 582 |
+
max_length: Optional[int] = None,
|
| 583 |
+
max_string: Optional[int] = None,
|
| 584 |
+
max_depth: Optional[int] = None,
|
| 585 |
+
) -> Node:
|
| 586 |
+
"""Traverse object and generate a tree.
|
| 587 |
+
|
| 588 |
+
Args:
|
| 589 |
+
_object (Any): Object to be traversed.
|
| 590 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 591 |
+
Defaults to None.
|
| 592 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
|
| 593 |
+
Defaults to None.
|
| 594 |
+
max_depth (int, optional): Maximum depth of data structures, or None for no maximum.
|
| 595 |
+
Defaults to None.
|
| 596 |
+
|
| 597 |
+
Returns:
|
| 598 |
+
Node: The root of a tree structure which can be used to render a pretty repr.
|
| 599 |
+
"""
|
| 600 |
+
|
| 601 |
+
def to_repr(obj: Any) -> str:
|
| 602 |
+
"""Get repr string for an object, but catch errors."""
|
| 603 |
+
if (
|
| 604 |
+
max_string is not None
|
| 605 |
+
and _safe_isinstance(obj, (bytes, str))
|
| 606 |
+
and len(obj) > max_string
|
| 607 |
+
):
|
| 608 |
+
truncated = len(obj) - max_string
|
| 609 |
+
obj_repr = f"{obj[:max_string]!r}+{truncated}"
|
| 610 |
+
else:
|
| 611 |
+
try:
|
| 612 |
+
obj_repr = repr(obj)
|
| 613 |
+
except Exception as error:
|
| 614 |
+
obj_repr = f"<repr-error {str(error)!r}>"
|
| 615 |
+
return obj_repr
|
| 616 |
+
|
| 617 |
+
visited_ids: Set[int] = set()
|
| 618 |
+
push_visited = visited_ids.add
|
| 619 |
+
pop_visited = visited_ids.remove
|
| 620 |
+
|
| 621 |
+
def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:
|
| 622 |
+
"""Walk the object depth first."""
|
| 623 |
+
|
| 624 |
+
obj_id = id(obj)
|
| 625 |
+
if obj_id in visited_ids:
|
| 626 |
+
# Recursion detected
|
| 627 |
+
return Node(value_repr="...")
|
| 628 |
+
|
| 629 |
+
obj_type = type(obj)
|
| 630 |
+
children: List[Node]
|
| 631 |
+
reached_max_depth = max_depth is not None and depth >= max_depth
|
| 632 |
+
|
| 633 |
+
def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:
|
| 634 |
+
for arg in rich_args:
|
| 635 |
+
if _safe_isinstance(arg, tuple):
|
| 636 |
+
if len(arg) == 3:
|
| 637 |
+
key, child, default = arg
|
| 638 |
+
if default == child:
|
| 639 |
+
continue
|
| 640 |
+
yield key, child
|
| 641 |
+
elif len(arg) == 2:
|
| 642 |
+
key, child = arg
|
| 643 |
+
yield key, child
|
| 644 |
+
elif len(arg) == 1:
|
| 645 |
+
yield arg[0]
|
| 646 |
+
else:
|
| 647 |
+
yield arg
|
| 648 |
+
|
| 649 |
+
try:
|
| 650 |
+
fake_attributes = hasattr(
|
| 651 |
+
obj, "awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492"
|
| 652 |
+
)
|
| 653 |
+
except Exception:
|
| 654 |
+
fake_attributes = False
|
| 655 |
+
|
| 656 |
+
rich_repr_result: Optional[RichReprResult] = None
|
| 657 |
+
if not fake_attributes:
|
| 658 |
+
try:
|
| 659 |
+
if hasattr(obj, "__rich_repr__") and not isclass(obj):
|
| 660 |
+
rich_repr_result = obj.__rich_repr__()
|
| 661 |
+
except Exception:
|
| 662 |
+
pass
|
| 663 |
+
|
| 664 |
+
if rich_repr_result is not None:
|
| 665 |
+
push_visited(obj_id)
|
| 666 |
+
angular = getattr(obj.__rich_repr__, "angular", False)
|
| 667 |
+
args = list(iter_rich_args(rich_repr_result))
|
| 668 |
+
class_name = obj.__class__.__name__
|
| 669 |
+
|
| 670 |
+
if args:
|
| 671 |
+
children = []
|
| 672 |
+
append = children.append
|
| 673 |
+
|
| 674 |
+
if reached_max_depth:
|
| 675 |
+
if angular:
|
| 676 |
+
node = Node(value_repr=f"<{class_name}...>")
|
| 677 |
+
else:
|
| 678 |
+
node = Node(value_repr=f"{class_name}(...)")
|
| 679 |
+
else:
|
| 680 |
+
if angular:
|
| 681 |
+
node = Node(
|
| 682 |
+
open_brace=f"<{class_name} ",
|
| 683 |
+
close_brace=">",
|
| 684 |
+
children=children,
|
| 685 |
+
last=root,
|
| 686 |
+
separator=" ",
|
| 687 |
+
)
|
| 688 |
+
else:
|
| 689 |
+
node = Node(
|
| 690 |
+
open_brace=f"{class_name}(",
|
| 691 |
+
close_brace=")",
|
| 692 |
+
children=children,
|
| 693 |
+
last=root,
|
| 694 |
+
)
|
| 695 |
+
for last, arg in loop_last(args):
|
| 696 |
+
if _safe_isinstance(arg, tuple):
|
| 697 |
+
key, child = arg
|
| 698 |
+
child_node = _traverse(child, depth=depth + 1)
|
| 699 |
+
child_node.last = last
|
| 700 |
+
child_node.key_repr = key
|
| 701 |
+
child_node.key_separator = "="
|
| 702 |
+
append(child_node)
|
| 703 |
+
else:
|
| 704 |
+
child_node = _traverse(arg, depth=depth + 1)
|
| 705 |
+
child_node.last = last
|
| 706 |
+
append(child_node)
|
| 707 |
+
else:
|
| 708 |
+
node = Node(
|
| 709 |
+
value_repr=f"<{class_name}>" if angular else f"{class_name}()",
|
| 710 |
+
children=[],
|
| 711 |
+
last=root,
|
| 712 |
+
)
|
| 713 |
+
pop_visited(obj_id)
|
| 714 |
+
elif _is_attr_object(obj) and not fake_attributes:
|
| 715 |
+
push_visited(obj_id)
|
| 716 |
+
children = []
|
| 717 |
+
append = children.append
|
| 718 |
+
|
| 719 |
+
attr_fields = _get_attr_fields(obj)
|
| 720 |
+
if attr_fields:
|
| 721 |
+
if reached_max_depth:
|
| 722 |
+
node = Node(value_repr=f"{obj.__class__.__name__}(...)")
|
| 723 |
+
else:
|
| 724 |
+
node = Node(
|
| 725 |
+
open_brace=f"{obj.__class__.__name__}(",
|
| 726 |
+
close_brace=")",
|
| 727 |
+
children=children,
|
| 728 |
+
last=root,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
def iter_attrs() -> (
|
| 732 |
+
Iterable[Tuple[str, Any, Optional[Callable[[Any], str]]]]
|
| 733 |
+
):
|
| 734 |
+
"""Iterate over attr fields and values."""
|
| 735 |
+
for attr in attr_fields:
|
| 736 |
+
if attr.repr:
|
| 737 |
+
try:
|
| 738 |
+
value = getattr(obj, attr.name)
|
| 739 |
+
except Exception as error:
|
| 740 |
+
# Can happen, albeit rarely
|
| 741 |
+
yield (attr.name, error, None)
|
| 742 |
+
else:
|
| 743 |
+
yield (
|
| 744 |
+
attr.name,
|
| 745 |
+
value,
|
| 746 |
+
attr.repr if callable(attr.repr) else None,
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
for last, (name, value, repr_callable) in loop_last(iter_attrs()):
|
| 750 |
+
if repr_callable:
|
| 751 |
+
child_node = Node(value_repr=str(repr_callable(value)))
|
| 752 |
+
else:
|
| 753 |
+
child_node = _traverse(value, depth=depth + 1)
|
| 754 |
+
child_node.last = last
|
| 755 |
+
child_node.key_repr = name
|
| 756 |
+
child_node.key_separator = "="
|
| 757 |
+
append(child_node)
|
| 758 |
+
else:
|
| 759 |
+
node = Node(
|
| 760 |
+
value_repr=f"{obj.__class__.__name__}()", children=[], last=root
|
| 761 |
+
)
|
| 762 |
+
pop_visited(obj_id)
|
| 763 |
+
elif (
|
| 764 |
+
is_dataclass(obj)
|
| 765 |
+
and not _safe_isinstance(obj, type)
|
| 766 |
+
and not fake_attributes
|
| 767 |
+
and _is_dataclass_repr(obj)
|
| 768 |
+
):
|
| 769 |
+
push_visited(obj_id)
|
| 770 |
+
children = []
|
| 771 |
+
append = children.append
|
| 772 |
+
if reached_max_depth:
|
| 773 |
+
node = Node(value_repr=f"{obj.__class__.__name__}(...)")
|
| 774 |
+
else:
|
| 775 |
+
node = Node(
|
| 776 |
+
open_brace=f"{obj.__class__.__name__}(",
|
| 777 |
+
close_brace=")",
|
| 778 |
+
children=children,
|
| 779 |
+
last=root,
|
| 780 |
+
empty=f"{obj.__class__.__name__}()",
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
for last, field in loop_last(
|
| 784 |
+
field
|
| 785 |
+
for field in fields(obj)
|
| 786 |
+
if field.repr and hasattr(obj, field.name)
|
| 787 |
+
):
|
| 788 |
+
child_node = _traverse(getattr(obj, field.name), depth=depth + 1)
|
| 789 |
+
child_node.key_repr = field.name
|
| 790 |
+
child_node.last = last
|
| 791 |
+
child_node.key_separator = "="
|
| 792 |
+
append(child_node)
|
| 793 |
+
|
| 794 |
+
pop_visited(obj_id)
|
| 795 |
+
elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj):
|
| 796 |
+
push_visited(obj_id)
|
| 797 |
+
class_name = obj.__class__.__name__
|
| 798 |
+
if reached_max_depth:
|
| 799 |
+
# If we've reached the max depth, we still show the class name, but not its contents
|
| 800 |
+
node = Node(
|
| 801 |
+
value_repr=f"{class_name}(...)",
|
| 802 |
+
)
|
| 803 |
+
else:
|
| 804 |
+
children = []
|
| 805 |
+
append = children.append
|
| 806 |
+
node = Node(
|
| 807 |
+
open_brace=f"{class_name}(",
|
| 808 |
+
close_brace=")",
|
| 809 |
+
children=children,
|
| 810 |
+
empty=f"{class_name}()",
|
| 811 |
+
)
|
| 812 |
+
for last, (key, value) in loop_last(obj._asdict().items()):
|
| 813 |
+
child_node = _traverse(value, depth=depth + 1)
|
| 814 |
+
child_node.key_repr = key
|
| 815 |
+
child_node.last = last
|
| 816 |
+
child_node.key_separator = "="
|
| 817 |
+
append(child_node)
|
| 818 |
+
pop_visited(obj_id)
|
| 819 |
+
elif _safe_isinstance(obj, _CONTAINERS):
|
| 820 |
+
for container_type in _CONTAINERS:
|
| 821 |
+
if _safe_isinstance(obj, container_type):
|
| 822 |
+
obj_type = container_type
|
| 823 |
+
break
|
| 824 |
+
|
| 825 |
+
push_visited(obj_id)
|
| 826 |
+
|
| 827 |
+
open_brace, close_brace, empty = _BRACES[obj_type](obj)
|
| 828 |
+
|
| 829 |
+
if reached_max_depth:
|
| 830 |
+
node = Node(value_repr=f"{open_brace}...{close_brace}")
|
| 831 |
+
elif obj_type.__repr__ != type(obj).__repr__:
|
| 832 |
+
node = Node(value_repr=to_repr(obj), last=root)
|
| 833 |
+
elif obj:
|
| 834 |
+
children = []
|
| 835 |
+
node = Node(
|
| 836 |
+
open_brace=open_brace,
|
| 837 |
+
close_brace=close_brace,
|
| 838 |
+
children=children,
|
| 839 |
+
last=root,
|
| 840 |
+
)
|
| 841 |
+
append = children.append
|
| 842 |
+
num_items = len(obj)
|
| 843 |
+
last_item_index = num_items - 1
|
| 844 |
+
|
| 845 |
+
if _safe_isinstance(obj, _MAPPING_CONTAINERS):
|
| 846 |
+
iter_items = iter(obj.items())
|
| 847 |
+
if max_length is not None:
|
| 848 |
+
iter_items = islice(iter_items, max_length)
|
| 849 |
+
for index, (key, child) in enumerate(iter_items):
|
| 850 |
+
child_node = _traverse(child, depth=depth + 1)
|
| 851 |
+
child_node.key_repr = to_repr(key)
|
| 852 |
+
child_node.last = index == last_item_index
|
| 853 |
+
append(child_node)
|
| 854 |
+
else:
|
| 855 |
+
iter_values = iter(obj)
|
| 856 |
+
if max_length is not None:
|
| 857 |
+
iter_values = islice(iter_values, max_length)
|
| 858 |
+
for index, child in enumerate(iter_values):
|
| 859 |
+
child_node = _traverse(child, depth=depth + 1)
|
| 860 |
+
child_node.last = index == last_item_index
|
| 861 |
+
append(child_node)
|
| 862 |
+
if max_length is not None and num_items > max_length:
|
| 863 |
+
append(Node(value_repr=f"... +{num_items - max_length}", last=True))
|
| 864 |
+
else:
|
| 865 |
+
node = Node(empty=empty, children=[], last=root)
|
| 866 |
+
|
| 867 |
+
pop_visited(obj_id)
|
| 868 |
+
else:
|
| 869 |
+
node = Node(value_repr=to_repr(obj), last=root)
|
| 870 |
+
node.is_tuple = type(obj) == tuple
|
| 871 |
+
node.is_namedtuple = _is_namedtuple(obj)
|
| 872 |
+
return node
|
| 873 |
+
|
| 874 |
+
node = _traverse(_object, root=True)
|
| 875 |
+
return node
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def pretty_repr(
|
| 879 |
+
_object: Any,
|
| 880 |
+
*,
|
| 881 |
+
max_width: int = 80,
|
| 882 |
+
indent_size: int = 4,
|
| 883 |
+
max_length: Optional[int] = None,
|
| 884 |
+
max_string: Optional[int] = None,
|
| 885 |
+
max_depth: Optional[int] = None,
|
| 886 |
+
expand_all: bool = False,
|
| 887 |
+
) -> str:
|
| 888 |
+
"""Prettify repr string by expanding on to new lines to fit within a given width.
|
| 889 |
+
|
| 890 |
+
Args:
|
| 891 |
+
_object (Any): Object to repr.
|
| 892 |
+
max_width (int, optional): Desired maximum width of repr string. Defaults to 80.
|
| 893 |
+
indent_size (int, optional): Number of spaces to indent. Defaults to 4.
|
| 894 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 895 |
+
Defaults to None.
|
| 896 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.
|
| 897 |
+
Defaults to None.
|
| 898 |
+
max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.
|
| 899 |
+
Defaults to None.
|
| 900 |
+
expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.
|
| 901 |
+
|
| 902 |
+
Returns:
|
| 903 |
+
str: A possibly multi-line representation of the object.
|
| 904 |
+
"""
|
| 905 |
+
|
| 906 |
+
if _safe_isinstance(_object, Node):
|
| 907 |
+
node = _object
|
| 908 |
+
else:
|
| 909 |
+
node = traverse(
|
| 910 |
+
_object, max_length=max_length, max_string=max_string, max_depth=max_depth
|
| 911 |
+
)
|
| 912 |
+
repr_str: str = node.render(
|
| 913 |
+
max_width=max_width, indent_size=indent_size, expand_all=expand_all
|
| 914 |
+
)
|
| 915 |
+
return repr_str
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def pprint(
|
| 919 |
+
_object: Any,
|
| 920 |
+
*,
|
| 921 |
+
console: Optional["Console"] = None,
|
| 922 |
+
indent_guides: bool = True,
|
| 923 |
+
max_length: Optional[int] = None,
|
| 924 |
+
max_string: Optional[int] = None,
|
| 925 |
+
max_depth: Optional[int] = None,
|
| 926 |
+
expand_all: bool = False,
|
| 927 |
+
) -> None:
|
| 928 |
+
"""A convenience function for pretty printing.
|
| 929 |
+
|
| 930 |
+
Args:
|
| 931 |
+
_object (Any): Object to pretty print.
|
| 932 |
+
console (Console, optional): Console instance, or None to use default. Defaults to None.
|
| 933 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 934 |
+
Defaults to None.
|
| 935 |
+
max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.
|
| 936 |
+
max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.
|
| 937 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to True.
|
| 938 |
+
expand_all (bool, optional): Expand all containers. Defaults to False.
|
| 939 |
+
"""
|
| 940 |
+
_console = get_console() if console is None else console
|
| 941 |
+
_console.print(
|
| 942 |
+
Pretty(
|
| 943 |
+
_object,
|
| 944 |
+
max_length=max_length,
|
| 945 |
+
max_string=max_string,
|
| 946 |
+
max_depth=max_depth,
|
| 947 |
+
indent_guides=indent_guides,
|
| 948 |
+
expand_all=expand_all,
|
| 949 |
+
overflow="ignore",
|
| 950 |
+
),
|
| 951 |
+
soft_wrap=True,
|
| 952 |
+
)
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
if __name__ == "__main__": # pragma: no cover
|
| 956 |
+
|
| 957 |
+
class BrokenRepr:
|
| 958 |
+
def __repr__(self) -> str:
|
| 959 |
+
1 / 0
|
| 960 |
+
return "this will fail"
|
| 961 |
+
|
| 962 |
+
from typing import NamedTuple
|
| 963 |
+
|
| 964 |
+
class StockKeepingUnit(NamedTuple):
|
| 965 |
+
name: str
|
| 966 |
+
description: str
|
| 967 |
+
price: float
|
| 968 |
+
category: str
|
| 969 |
+
reviews: List[str]
|
| 970 |
+
|
| 971 |
+
d = defaultdict(int)
|
| 972 |
+
d["foo"] = 5
|
| 973 |
+
data = {
|
| 974 |
+
"foo": [
|
| 975 |
+
1,
|
| 976 |
+
"Hello World!",
|
| 977 |
+
100.123,
|
| 978 |
+
323.232,
|
| 979 |
+
432324.0,
|
| 980 |
+
{5, 6, 7, (1, 2, 3, 4), 8},
|
| 981 |
+
],
|
| 982 |
+
"bar": frozenset({1, 2, 3}),
|
| 983 |
+
"defaultdict": defaultdict(
|
| 984 |
+
list, {"crumble": ["apple", "rhubarb", "butter", "sugar", "flour"]}
|
| 985 |
+
),
|
| 986 |
+
"counter": Counter(
|
| 987 |
+
[
|
| 988 |
+
"apple",
|
| 989 |
+
"orange",
|
| 990 |
+
"pear",
|
| 991 |
+
"kumquat",
|
| 992 |
+
"kumquat",
|
| 993 |
+
"durian" * 100,
|
| 994 |
+
]
|
| 995 |
+
),
|
| 996 |
+
"atomic": (False, True, None),
|
| 997 |
+
"namedtuple": StockKeepingUnit(
|
| 998 |
+
"Sparkling British Spring Water",
|
| 999 |
+
"Carbonated spring water",
|
| 1000 |
+
0.9,
|
| 1001 |
+
"water",
|
| 1002 |
+
["its amazing!", "its terrible!"],
|
| 1003 |
+
),
|
| 1004 |
+
"Broken": BrokenRepr(),
|
| 1005 |
+
}
|
| 1006 |
+
data["foo"].append(data) # type: ignore[attr-defined]
|
| 1007 |
+
|
| 1008 |
+
from rich import print
|
| 1009 |
+
|
| 1010 |
+
print(Pretty(data, indent_guides=True, max_string=20))
|
| 1011 |
+
|
| 1012 |
+
class Thing:
|
| 1013 |
+
def __repr__(self) -> str:
|
| 1014 |
+
return "Hello\x1b[38;5;239m World!"
|
| 1015 |
+
|
| 1016 |
+
print(Pretty(Thing()))
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/progress.py
ADDED
|
@@ -0,0 +1,1716 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
import warnings
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from collections import deque
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
from datetime import timedelta
|
| 10 |
+
from io import RawIOBase, UnsupportedOperation
|
| 11 |
+
from math import ceil
|
| 12 |
+
from mmap import mmap
|
| 13 |
+
from operator import length_hint
|
| 14 |
+
from os import PathLike, stat
|
| 15 |
+
from threading import Event, RLock, Thread
|
| 16 |
+
from types import TracebackType
|
| 17 |
+
from typing import (
|
| 18 |
+
TYPE_CHECKING,
|
| 19 |
+
Any,
|
| 20 |
+
BinaryIO,
|
| 21 |
+
Callable,
|
| 22 |
+
ContextManager,
|
| 23 |
+
Deque,
|
| 24 |
+
Dict,
|
| 25 |
+
Generic,
|
| 26 |
+
Iterable,
|
| 27 |
+
List,
|
| 28 |
+
Literal,
|
| 29 |
+
NamedTuple,
|
| 30 |
+
NewType,
|
| 31 |
+
Optional,
|
| 32 |
+
TextIO,
|
| 33 |
+
Tuple,
|
| 34 |
+
Type,
|
| 35 |
+
TypeVar,
|
| 36 |
+
Union,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
# Can be replaced with `from typing import Self` in Python 3.11+
|
| 41 |
+
from typing_extensions import Self # pragma: no cover
|
| 42 |
+
|
| 43 |
+
from . import filesize, get_console
|
| 44 |
+
from .console import Console, Group, JustifyMethod, RenderableType
|
| 45 |
+
from .highlighter import Highlighter
|
| 46 |
+
from .jupyter import JupyterMixin
|
| 47 |
+
from .live import Live
|
| 48 |
+
from .progress_bar import ProgressBar
|
| 49 |
+
from .spinner import Spinner
|
| 50 |
+
from .style import StyleType
|
| 51 |
+
from .table import Column, Table
|
| 52 |
+
from .text import Text, TextType
|
| 53 |
+
|
| 54 |
+
TaskID = NewType("TaskID", int)
|
| 55 |
+
|
| 56 |
+
ProgressType = TypeVar("ProgressType")
|
| 57 |
+
|
| 58 |
+
GetTimeCallable = Callable[[], float]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
_I = typing.TypeVar("_I", TextIO, BinaryIO)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class _TrackThread(Thread):
|
| 65 |
+
"""A thread to periodically update progress."""
|
| 66 |
+
|
| 67 |
+
def __init__(self, progress: "Progress", task_id: "TaskID", update_period: float):
|
| 68 |
+
self.progress = progress
|
| 69 |
+
self.task_id = task_id
|
| 70 |
+
self.update_period = update_period
|
| 71 |
+
self.done = Event()
|
| 72 |
+
|
| 73 |
+
self.completed = 0
|
| 74 |
+
super().__init__(daemon=True)
|
| 75 |
+
|
| 76 |
+
def run(self) -> None:
|
| 77 |
+
task_id = self.task_id
|
| 78 |
+
advance = self.progress.advance
|
| 79 |
+
update_period = self.update_period
|
| 80 |
+
last_completed = 0
|
| 81 |
+
wait = self.done.wait
|
| 82 |
+
while not wait(update_period) and self.progress.live.is_started:
|
| 83 |
+
completed = self.completed
|
| 84 |
+
if last_completed != completed:
|
| 85 |
+
advance(task_id, completed - last_completed)
|
| 86 |
+
last_completed = completed
|
| 87 |
+
|
| 88 |
+
self.progress.update(self.task_id, completed=self.completed, refresh=True)
|
| 89 |
+
|
| 90 |
+
def __enter__(self) -> "_TrackThread":
|
| 91 |
+
self.start()
|
| 92 |
+
return self
|
| 93 |
+
|
| 94 |
+
def __exit__(
|
| 95 |
+
self,
|
| 96 |
+
exc_type: Optional[Type[BaseException]],
|
| 97 |
+
exc_val: Optional[BaseException],
|
| 98 |
+
exc_tb: Optional[TracebackType],
|
| 99 |
+
) -> None:
|
| 100 |
+
self.done.set()
|
| 101 |
+
self.join()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def track(
|
| 105 |
+
sequence: Iterable[ProgressType],
|
| 106 |
+
description: str = "Working...",
|
| 107 |
+
total: Optional[float] = None,
|
| 108 |
+
completed: int = 0,
|
| 109 |
+
auto_refresh: bool = True,
|
| 110 |
+
console: Optional[Console] = None,
|
| 111 |
+
transient: bool = False,
|
| 112 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 113 |
+
refresh_per_second: float = 10,
|
| 114 |
+
style: StyleType = "bar.back",
|
| 115 |
+
complete_style: StyleType = "bar.complete",
|
| 116 |
+
finished_style: StyleType = "bar.finished",
|
| 117 |
+
pulse_style: StyleType = "bar.pulse",
|
| 118 |
+
update_period: float = 0.1,
|
| 119 |
+
disable: bool = False,
|
| 120 |
+
show_speed: bool = True,
|
| 121 |
+
) -> Iterable[ProgressType]:
|
| 122 |
+
"""Track progress by iterating over a sequence.
|
| 123 |
+
|
| 124 |
+
You can also track progress of an iterable, which might require that you additionally specify ``total``.
|
| 125 |
+
|
| 126 |
+
Args:
|
| 127 |
+
sequence (Iterable[ProgressType]): Values you wish to iterate over and track progress.
|
| 128 |
+
description (str, optional): Description of task show next to progress bar. Defaults to "Working".
|
| 129 |
+
total: (float, optional): Total number of steps. Default is len(sequence).
|
| 130 |
+
completed (int, optional): Number of steps completed so far. Defaults to 0.
|
| 131 |
+
auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
|
| 132 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 133 |
+
console (Console, optional): Console to write to. Default creates internal Console instance.
|
| 134 |
+
refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
|
| 135 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 136 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 137 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 138 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 139 |
+
update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
|
| 140 |
+
disable (bool, optional): Disable display of progress.
|
| 141 |
+
show_speed (bool, optional): Show speed if total isn't known. Defaults to True.
|
| 142 |
+
Returns:
|
| 143 |
+
Iterable[ProgressType]: An iterable of the values in the sequence.
|
| 144 |
+
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
columns: List["ProgressColumn"] = (
|
| 148 |
+
[TextColumn("[progress.description]{task.description}")] if description else []
|
| 149 |
+
)
|
| 150 |
+
columns.extend(
|
| 151 |
+
(
|
| 152 |
+
BarColumn(
|
| 153 |
+
style=style,
|
| 154 |
+
complete_style=complete_style,
|
| 155 |
+
finished_style=finished_style,
|
| 156 |
+
pulse_style=pulse_style,
|
| 157 |
+
),
|
| 158 |
+
TaskProgressColumn(show_speed=show_speed),
|
| 159 |
+
TimeRemainingColumn(elapsed_when_finished=True),
|
| 160 |
+
)
|
| 161 |
+
)
|
| 162 |
+
progress = Progress(
|
| 163 |
+
*columns,
|
| 164 |
+
auto_refresh=auto_refresh,
|
| 165 |
+
console=console,
|
| 166 |
+
transient=transient,
|
| 167 |
+
get_time=get_time,
|
| 168 |
+
refresh_per_second=refresh_per_second or 10,
|
| 169 |
+
disable=disable,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
with progress:
|
| 173 |
+
yield from progress.track(
|
| 174 |
+
sequence,
|
| 175 |
+
total=total,
|
| 176 |
+
completed=completed,
|
| 177 |
+
description=description,
|
| 178 |
+
update_period=update_period,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class _Reader(RawIOBase, BinaryIO):
|
| 183 |
+
"""A reader that tracks progress while it's being read from."""
|
| 184 |
+
|
| 185 |
+
def __init__(
|
| 186 |
+
self,
|
| 187 |
+
handle: BinaryIO,
|
| 188 |
+
progress: "Progress",
|
| 189 |
+
task: TaskID,
|
| 190 |
+
close_handle: bool = True,
|
| 191 |
+
) -> None:
|
| 192 |
+
self.handle = handle
|
| 193 |
+
self.progress = progress
|
| 194 |
+
self.task = task
|
| 195 |
+
self.close_handle = close_handle
|
| 196 |
+
self._closed = False
|
| 197 |
+
|
| 198 |
+
def __enter__(self) -> "_Reader":
|
| 199 |
+
self.handle.__enter__()
|
| 200 |
+
return self
|
| 201 |
+
|
| 202 |
+
def __exit__(
|
| 203 |
+
self,
|
| 204 |
+
exc_type: Optional[Type[BaseException]],
|
| 205 |
+
exc_val: Optional[BaseException],
|
| 206 |
+
exc_tb: Optional[TracebackType],
|
| 207 |
+
) -> None:
|
| 208 |
+
self.close()
|
| 209 |
+
|
| 210 |
+
def __iter__(self) -> BinaryIO:
|
| 211 |
+
return self
|
| 212 |
+
|
| 213 |
+
def __next__(self) -> bytes:
|
| 214 |
+
line = next(self.handle)
|
| 215 |
+
self.progress.advance(self.task, advance=len(line))
|
| 216 |
+
return line
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def closed(self) -> bool:
|
| 220 |
+
return self._closed
|
| 221 |
+
|
| 222 |
+
def fileno(self) -> int:
|
| 223 |
+
return self.handle.fileno()
|
| 224 |
+
|
| 225 |
+
def isatty(self) -> bool:
|
| 226 |
+
return self.handle.isatty()
|
| 227 |
+
|
| 228 |
+
@property
|
| 229 |
+
def mode(self) -> str:
|
| 230 |
+
return self.handle.mode
|
| 231 |
+
|
| 232 |
+
@property
|
| 233 |
+
def name(self) -> str:
|
| 234 |
+
return self.handle.name
|
| 235 |
+
|
| 236 |
+
def readable(self) -> bool:
|
| 237 |
+
return self.handle.readable()
|
| 238 |
+
|
| 239 |
+
def seekable(self) -> bool:
|
| 240 |
+
return self.handle.seekable()
|
| 241 |
+
|
| 242 |
+
def writable(self) -> bool:
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
def read(self, size: int = -1) -> bytes:
|
| 246 |
+
block = self.handle.read(size)
|
| 247 |
+
self.progress.advance(self.task, advance=len(block))
|
| 248 |
+
return block
|
| 249 |
+
|
| 250 |
+
def readinto(self, b: Union[bytearray, memoryview, mmap]): # type: ignore[no-untyped-def, override]
|
| 251 |
+
n = self.handle.readinto(b) # type: ignore[attr-defined]
|
| 252 |
+
self.progress.advance(self.task, advance=n)
|
| 253 |
+
return n
|
| 254 |
+
|
| 255 |
+
def readline(self, size: int = -1) -> bytes: # type: ignore[override]
|
| 256 |
+
line = self.handle.readline(size)
|
| 257 |
+
self.progress.advance(self.task, advance=len(line))
|
| 258 |
+
return line
|
| 259 |
+
|
| 260 |
+
def readlines(self, hint: int = -1) -> List[bytes]:
|
| 261 |
+
lines = self.handle.readlines(hint)
|
| 262 |
+
self.progress.advance(self.task, advance=sum(map(len, lines)))
|
| 263 |
+
return lines
|
| 264 |
+
|
| 265 |
+
def close(self) -> None:
|
| 266 |
+
if self.close_handle:
|
| 267 |
+
self.handle.close()
|
| 268 |
+
self._closed = True
|
| 269 |
+
|
| 270 |
+
def seek(self, offset: int, whence: int = 0) -> int:
|
| 271 |
+
pos = self.handle.seek(offset, whence)
|
| 272 |
+
self.progress.update(self.task, completed=pos)
|
| 273 |
+
return pos
|
| 274 |
+
|
| 275 |
+
def tell(self) -> int:
|
| 276 |
+
return self.handle.tell()
|
| 277 |
+
|
| 278 |
+
def write(self, s: Any) -> int:
|
| 279 |
+
raise UnsupportedOperation("write")
|
| 280 |
+
|
| 281 |
+
def writelines(self, lines: Iterable[Any]) -> None:
|
| 282 |
+
raise UnsupportedOperation("writelines")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class _ReadContext(ContextManager[_I], Generic[_I]):
|
| 286 |
+
"""A utility class to handle a context for both a reader and a progress."""
|
| 287 |
+
|
| 288 |
+
def __init__(self, progress: "Progress", reader: _I) -> None:
|
| 289 |
+
self.progress = progress
|
| 290 |
+
self.reader: _I = reader
|
| 291 |
+
|
| 292 |
+
def __enter__(self) -> _I:
|
| 293 |
+
self.progress.start()
|
| 294 |
+
return self.reader.__enter__()
|
| 295 |
+
|
| 296 |
+
def __exit__(
|
| 297 |
+
self,
|
| 298 |
+
exc_type: Optional[Type[BaseException]],
|
| 299 |
+
exc_val: Optional[BaseException],
|
| 300 |
+
exc_tb: Optional[TracebackType],
|
| 301 |
+
) -> None:
|
| 302 |
+
self.progress.stop()
|
| 303 |
+
self.reader.__exit__(exc_type, exc_val, exc_tb)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def wrap_file(
|
| 307 |
+
file: BinaryIO,
|
| 308 |
+
total: int,
|
| 309 |
+
*,
|
| 310 |
+
description: str = "Reading...",
|
| 311 |
+
auto_refresh: bool = True,
|
| 312 |
+
console: Optional[Console] = None,
|
| 313 |
+
transient: bool = False,
|
| 314 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 315 |
+
refresh_per_second: float = 10,
|
| 316 |
+
style: StyleType = "bar.back",
|
| 317 |
+
complete_style: StyleType = "bar.complete",
|
| 318 |
+
finished_style: StyleType = "bar.finished",
|
| 319 |
+
pulse_style: StyleType = "bar.pulse",
|
| 320 |
+
disable: bool = False,
|
| 321 |
+
) -> ContextManager[BinaryIO]:
|
| 322 |
+
"""Read bytes from a file while tracking progress.
|
| 323 |
+
|
| 324 |
+
Args:
|
| 325 |
+
file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
|
| 326 |
+
total (int): Total number of bytes to read.
|
| 327 |
+
description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
|
| 328 |
+
auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
|
| 329 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 330 |
+
console (Console, optional): Console to write to. Default creates internal Console instance.
|
| 331 |
+
refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
|
| 332 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 333 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 334 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 335 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 336 |
+
disable (bool, optional): Disable display of progress.
|
| 337 |
+
Returns:
|
| 338 |
+
ContextManager[BinaryIO]: A context manager yielding a progress reader.
|
| 339 |
+
|
| 340 |
+
"""
|
| 341 |
+
|
| 342 |
+
columns: List["ProgressColumn"] = (
|
| 343 |
+
[TextColumn("[progress.description]{task.description}")] if description else []
|
| 344 |
+
)
|
| 345 |
+
columns.extend(
|
| 346 |
+
(
|
| 347 |
+
BarColumn(
|
| 348 |
+
style=style,
|
| 349 |
+
complete_style=complete_style,
|
| 350 |
+
finished_style=finished_style,
|
| 351 |
+
pulse_style=pulse_style,
|
| 352 |
+
),
|
| 353 |
+
DownloadColumn(),
|
| 354 |
+
TimeRemainingColumn(),
|
| 355 |
+
)
|
| 356 |
+
)
|
| 357 |
+
progress = Progress(
|
| 358 |
+
*columns,
|
| 359 |
+
auto_refresh=auto_refresh,
|
| 360 |
+
console=console,
|
| 361 |
+
transient=transient,
|
| 362 |
+
get_time=get_time,
|
| 363 |
+
refresh_per_second=refresh_per_second or 10,
|
| 364 |
+
disable=disable,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
reader = progress.wrap_file(file, total=total, description=description)
|
| 368 |
+
return _ReadContext(progress, reader)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@typing.overload
|
| 372 |
+
def open(
|
| 373 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 374 |
+
mode: Union[Literal["rt"], Literal["r"]],
|
| 375 |
+
buffering: int = -1,
|
| 376 |
+
encoding: Optional[str] = None,
|
| 377 |
+
errors: Optional[str] = None,
|
| 378 |
+
newline: Optional[str] = None,
|
| 379 |
+
*,
|
| 380 |
+
total: Optional[int] = None,
|
| 381 |
+
description: str = "Reading...",
|
| 382 |
+
auto_refresh: bool = True,
|
| 383 |
+
console: Optional[Console] = None,
|
| 384 |
+
transient: bool = False,
|
| 385 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 386 |
+
refresh_per_second: float = 10,
|
| 387 |
+
style: StyleType = "bar.back",
|
| 388 |
+
complete_style: StyleType = "bar.complete",
|
| 389 |
+
finished_style: StyleType = "bar.finished",
|
| 390 |
+
pulse_style: StyleType = "bar.pulse",
|
| 391 |
+
disable: bool = False,
|
| 392 |
+
) -> ContextManager[TextIO]:
|
| 393 |
+
pass
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
@typing.overload
|
| 397 |
+
def open(
|
| 398 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 399 |
+
mode: Literal["rb"],
|
| 400 |
+
buffering: int = -1,
|
| 401 |
+
encoding: Optional[str] = None,
|
| 402 |
+
errors: Optional[str] = None,
|
| 403 |
+
newline: Optional[str] = None,
|
| 404 |
+
*,
|
| 405 |
+
total: Optional[int] = None,
|
| 406 |
+
description: str = "Reading...",
|
| 407 |
+
auto_refresh: bool = True,
|
| 408 |
+
console: Optional[Console] = None,
|
| 409 |
+
transient: bool = False,
|
| 410 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 411 |
+
refresh_per_second: float = 10,
|
| 412 |
+
style: StyleType = "bar.back",
|
| 413 |
+
complete_style: StyleType = "bar.complete",
|
| 414 |
+
finished_style: StyleType = "bar.finished",
|
| 415 |
+
pulse_style: StyleType = "bar.pulse",
|
| 416 |
+
disable: bool = False,
|
| 417 |
+
) -> ContextManager[BinaryIO]:
|
| 418 |
+
pass
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def open(
|
| 422 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 423 |
+
mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r",
|
| 424 |
+
buffering: int = -1,
|
| 425 |
+
encoding: Optional[str] = None,
|
| 426 |
+
errors: Optional[str] = None,
|
| 427 |
+
newline: Optional[str] = None,
|
| 428 |
+
*,
|
| 429 |
+
total: Optional[int] = None,
|
| 430 |
+
description: str = "Reading...",
|
| 431 |
+
auto_refresh: bool = True,
|
| 432 |
+
console: Optional[Console] = None,
|
| 433 |
+
transient: bool = False,
|
| 434 |
+
get_time: Optional[Callable[[], float]] = None,
|
| 435 |
+
refresh_per_second: float = 10,
|
| 436 |
+
style: StyleType = "bar.back",
|
| 437 |
+
complete_style: StyleType = "bar.complete",
|
| 438 |
+
finished_style: StyleType = "bar.finished",
|
| 439 |
+
pulse_style: StyleType = "bar.pulse",
|
| 440 |
+
disable: bool = False,
|
| 441 |
+
) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:
|
| 442 |
+
"""Read bytes from a file while tracking progress.
|
| 443 |
+
|
| 444 |
+
Args:
|
| 445 |
+
path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
|
| 446 |
+
mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
|
| 447 |
+
buffering (int): The buffering strategy to use, see :func:`io.open`.
|
| 448 |
+
encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
|
| 449 |
+
errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
|
| 450 |
+
newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`
|
| 451 |
+
total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size.
|
| 452 |
+
description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
|
| 453 |
+
auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
|
| 454 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 455 |
+
console (Console, optional): Console to write to. Default creates internal Console instance.
|
| 456 |
+
refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
|
| 457 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 458 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 459 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 460 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 461 |
+
disable (bool, optional): Disable display of progress.
|
| 462 |
+
encoding (str, optional): The encoding to use when reading in text mode.
|
| 463 |
+
|
| 464 |
+
Returns:
|
| 465 |
+
ContextManager[BinaryIO]: A context manager yielding a progress reader.
|
| 466 |
+
|
| 467 |
+
"""
|
| 468 |
+
|
| 469 |
+
columns: List["ProgressColumn"] = (
|
| 470 |
+
[TextColumn("[progress.description]{task.description}")] if description else []
|
| 471 |
+
)
|
| 472 |
+
columns.extend(
|
| 473 |
+
(
|
| 474 |
+
BarColumn(
|
| 475 |
+
style=style,
|
| 476 |
+
complete_style=complete_style,
|
| 477 |
+
finished_style=finished_style,
|
| 478 |
+
pulse_style=pulse_style,
|
| 479 |
+
),
|
| 480 |
+
DownloadColumn(),
|
| 481 |
+
TimeRemainingColumn(),
|
| 482 |
+
)
|
| 483 |
+
)
|
| 484 |
+
progress = Progress(
|
| 485 |
+
*columns,
|
| 486 |
+
auto_refresh=auto_refresh,
|
| 487 |
+
console=console,
|
| 488 |
+
transient=transient,
|
| 489 |
+
get_time=get_time,
|
| 490 |
+
refresh_per_second=refresh_per_second or 10,
|
| 491 |
+
disable=disable,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
reader = progress.open(
|
| 495 |
+
file,
|
| 496 |
+
mode=mode,
|
| 497 |
+
buffering=buffering,
|
| 498 |
+
encoding=encoding,
|
| 499 |
+
errors=errors,
|
| 500 |
+
newline=newline,
|
| 501 |
+
total=total,
|
| 502 |
+
description=description,
|
| 503 |
+
)
|
| 504 |
+
return _ReadContext(progress, reader) # type: ignore[return-value, type-var]
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class ProgressColumn(ABC):
|
| 508 |
+
"""Base class for a widget to use in progress display."""
|
| 509 |
+
|
| 510 |
+
max_refresh: Optional[float] = None
|
| 511 |
+
|
| 512 |
+
def __init__(self, table_column: Optional[Column] = None) -> None:
|
| 513 |
+
self._table_column = table_column
|
| 514 |
+
self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {}
|
| 515 |
+
self._update_time: Optional[float] = None
|
| 516 |
+
|
| 517 |
+
def get_table_column(self) -> Column:
|
| 518 |
+
"""Get a table column, used to build tasks table."""
|
| 519 |
+
return self._table_column or Column()
|
| 520 |
+
|
| 521 |
+
def __call__(self, task: "Task") -> RenderableType:
|
| 522 |
+
"""Called by the Progress object to return a renderable for the given task.
|
| 523 |
+
|
| 524 |
+
Args:
|
| 525 |
+
task (Task): An object containing information regarding the task.
|
| 526 |
+
|
| 527 |
+
Returns:
|
| 528 |
+
RenderableType: Anything renderable (including str).
|
| 529 |
+
"""
|
| 530 |
+
current_time = task.get_time()
|
| 531 |
+
if self.max_refresh is not None and not task.completed:
|
| 532 |
+
try:
|
| 533 |
+
timestamp, renderable = self._renderable_cache[task.id]
|
| 534 |
+
except KeyError:
|
| 535 |
+
pass
|
| 536 |
+
else:
|
| 537 |
+
if timestamp + self.max_refresh > current_time:
|
| 538 |
+
return renderable
|
| 539 |
+
|
| 540 |
+
renderable = self.render(task)
|
| 541 |
+
self._renderable_cache[task.id] = (current_time, renderable)
|
| 542 |
+
return renderable
|
| 543 |
+
|
| 544 |
+
@abstractmethod
|
| 545 |
+
def render(self, task: "Task") -> RenderableType:
|
| 546 |
+
"""Should return a renderable object."""
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class RenderableColumn(ProgressColumn):
|
| 550 |
+
"""A column to insert an arbitrary column.
|
| 551 |
+
|
| 552 |
+
Args:
|
| 553 |
+
renderable (RenderableType, optional): Any renderable. Defaults to empty string.
|
| 554 |
+
"""
|
| 555 |
+
|
| 556 |
+
def __init__(
|
| 557 |
+
self, renderable: RenderableType = "", *, table_column: Optional[Column] = None
|
| 558 |
+
):
|
| 559 |
+
self.renderable = renderable
|
| 560 |
+
super().__init__(table_column=table_column)
|
| 561 |
+
|
| 562 |
+
def render(self, task: "Task") -> RenderableType:
|
| 563 |
+
return self.renderable
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
class SpinnerColumn(ProgressColumn):
|
| 567 |
+
"""A column with a 'spinner' animation.
|
| 568 |
+
|
| 569 |
+
Args:
|
| 570 |
+
spinner_name (str, optional): Name of spinner animation. Defaults to "dots".
|
| 571 |
+
style (StyleType, optional): Style of spinner. Defaults to "progress.spinner".
|
| 572 |
+
speed (float, optional): Speed factor of spinner. Defaults to 1.0.
|
| 573 |
+
finished_text (TextType, optional): Text used when task is finished. Defaults to " ".
|
| 574 |
+
"""
|
| 575 |
+
|
| 576 |
+
def __init__(
|
| 577 |
+
self,
|
| 578 |
+
spinner_name: str = "dots",
|
| 579 |
+
style: Optional[StyleType] = "progress.spinner",
|
| 580 |
+
speed: float = 1.0,
|
| 581 |
+
finished_text: TextType = " ",
|
| 582 |
+
table_column: Optional[Column] = None,
|
| 583 |
+
):
|
| 584 |
+
self.spinner = Spinner(spinner_name, style=style, speed=speed)
|
| 585 |
+
self.finished_text = (
|
| 586 |
+
Text.from_markup(finished_text)
|
| 587 |
+
if isinstance(finished_text, str)
|
| 588 |
+
else finished_text
|
| 589 |
+
)
|
| 590 |
+
super().__init__(table_column=table_column)
|
| 591 |
+
|
| 592 |
+
def set_spinner(
|
| 593 |
+
self,
|
| 594 |
+
spinner_name: str,
|
| 595 |
+
spinner_style: Optional[StyleType] = "progress.spinner",
|
| 596 |
+
speed: float = 1.0,
|
| 597 |
+
) -> None:
|
| 598 |
+
"""Set a new spinner.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
spinner_name (str): Spinner name, see python -m rich.spinner.
|
| 602 |
+
spinner_style (Optional[StyleType], optional): Spinner style. Defaults to "progress.spinner".
|
| 603 |
+
speed (float, optional): Speed factor of spinner. Defaults to 1.0.
|
| 604 |
+
"""
|
| 605 |
+
self.spinner = Spinner(spinner_name, style=spinner_style, speed=speed)
|
| 606 |
+
|
| 607 |
+
def render(self, task: "Task") -> RenderableType:
|
| 608 |
+
text = (
|
| 609 |
+
self.finished_text
|
| 610 |
+
if task.finished
|
| 611 |
+
else self.spinner.render(task.get_time())
|
| 612 |
+
)
|
| 613 |
+
return text
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
class TextColumn(ProgressColumn):
|
| 617 |
+
"""A column containing text."""
|
| 618 |
+
|
| 619 |
+
def __init__(
|
| 620 |
+
self,
|
| 621 |
+
text_format: str,
|
| 622 |
+
style: StyleType = "none",
|
| 623 |
+
justify: JustifyMethod = "left",
|
| 624 |
+
markup: bool = True,
|
| 625 |
+
highlighter: Optional[Highlighter] = None,
|
| 626 |
+
table_column: Optional[Column] = None,
|
| 627 |
+
) -> None:
|
| 628 |
+
self.text_format = text_format
|
| 629 |
+
self.justify: JustifyMethod = justify
|
| 630 |
+
self.style = style
|
| 631 |
+
self.markup = markup
|
| 632 |
+
self.highlighter = highlighter
|
| 633 |
+
super().__init__(table_column=table_column or Column(no_wrap=True))
|
| 634 |
+
|
| 635 |
+
def render(self, task: "Task") -> Text:
|
| 636 |
+
_text = self.text_format.format(task=task)
|
| 637 |
+
if self.markup:
|
| 638 |
+
text = Text.from_markup(_text, style=self.style, justify=self.justify)
|
| 639 |
+
else:
|
| 640 |
+
text = Text(_text, style=self.style, justify=self.justify)
|
| 641 |
+
if self.highlighter:
|
| 642 |
+
self.highlighter.highlight(text)
|
| 643 |
+
return text
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
class BarColumn(ProgressColumn):
|
| 647 |
+
"""Renders a visual progress bar.
|
| 648 |
+
|
| 649 |
+
Args:
|
| 650 |
+
bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40.
|
| 651 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 652 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 653 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 654 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 655 |
+
"""
|
| 656 |
+
|
| 657 |
+
def __init__(
|
| 658 |
+
self,
|
| 659 |
+
bar_width: Optional[int] = 40,
|
| 660 |
+
style: StyleType = "bar.back",
|
| 661 |
+
complete_style: StyleType = "bar.complete",
|
| 662 |
+
finished_style: StyleType = "bar.finished",
|
| 663 |
+
pulse_style: StyleType = "bar.pulse",
|
| 664 |
+
table_column: Optional[Column] = None,
|
| 665 |
+
) -> None:
|
| 666 |
+
self.bar_width = bar_width
|
| 667 |
+
self.style = style
|
| 668 |
+
self.complete_style = complete_style
|
| 669 |
+
self.finished_style = finished_style
|
| 670 |
+
self.pulse_style = pulse_style
|
| 671 |
+
super().__init__(table_column=table_column)
|
| 672 |
+
|
| 673 |
+
def render(self, task: "Task") -> ProgressBar:
|
| 674 |
+
"""Gets a progress bar widget for a task."""
|
| 675 |
+
return ProgressBar(
|
| 676 |
+
total=max(0, task.total) if task.total is not None else None,
|
| 677 |
+
completed=max(0, task.completed),
|
| 678 |
+
width=None if self.bar_width is None else max(1, self.bar_width),
|
| 679 |
+
pulse=not task.started,
|
| 680 |
+
animation_time=task.get_time(),
|
| 681 |
+
style=self.style,
|
| 682 |
+
complete_style=self.complete_style,
|
| 683 |
+
finished_style=self.finished_style,
|
| 684 |
+
pulse_style=self.pulse_style,
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
class TimeElapsedColumn(ProgressColumn):
|
| 689 |
+
"""Renders time elapsed."""
|
| 690 |
+
|
| 691 |
+
def render(self, task: "Task") -> Text:
|
| 692 |
+
"""Show time elapsed."""
|
| 693 |
+
elapsed = task.finished_time if task.finished else task.elapsed
|
| 694 |
+
if elapsed is None:
|
| 695 |
+
return Text("-:--:--", style="progress.elapsed")
|
| 696 |
+
delta = timedelta(seconds=max(0, int(elapsed)))
|
| 697 |
+
return Text(str(delta), style="progress.elapsed")
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
class TaskProgressColumn(TextColumn):
|
| 701 |
+
"""Show task progress as a percentage.
|
| 702 |
+
|
| 703 |
+
Args:
|
| 704 |
+
text_format (str, optional): Format for percentage display. Defaults to "[progress.percentage]{task.percentage:>3.0f}%".
|
| 705 |
+
text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to "".
|
| 706 |
+
style (StyleType, optional): Style of output. Defaults to "none".
|
| 707 |
+
justify (JustifyMethod, optional): Text justification. Defaults to "left".
|
| 708 |
+
markup (bool, optional): Enable markup. Defaults to True.
|
| 709 |
+
highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None.
|
| 710 |
+
table_column (Optional[Column], optional): Table Column to use. Defaults to None.
|
| 711 |
+
show_speed (bool, optional): Show speed if total is unknown. Defaults to False.
|
| 712 |
+
"""
|
| 713 |
+
|
| 714 |
+
def __init__(
|
| 715 |
+
self,
|
| 716 |
+
text_format: str = "[progress.percentage]{task.percentage:>3.0f}%",
|
| 717 |
+
text_format_no_percentage: str = "",
|
| 718 |
+
style: StyleType = "none",
|
| 719 |
+
justify: JustifyMethod = "left",
|
| 720 |
+
markup: bool = True,
|
| 721 |
+
highlighter: Optional[Highlighter] = None,
|
| 722 |
+
table_column: Optional[Column] = None,
|
| 723 |
+
show_speed: bool = False,
|
| 724 |
+
) -> None:
|
| 725 |
+
self.text_format_no_percentage = text_format_no_percentage
|
| 726 |
+
self.show_speed = show_speed
|
| 727 |
+
super().__init__(
|
| 728 |
+
text_format=text_format,
|
| 729 |
+
style=style,
|
| 730 |
+
justify=justify,
|
| 731 |
+
markup=markup,
|
| 732 |
+
highlighter=highlighter,
|
| 733 |
+
table_column=table_column,
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
@classmethod
|
| 737 |
+
def render_speed(cls, speed: Optional[float]) -> Text:
|
| 738 |
+
"""Render the speed in iterations per second.
|
| 739 |
+
|
| 740 |
+
Args:
|
| 741 |
+
task (Task): A Task object.
|
| 742 |
+
|
| 743 |
+
Returns:
|
| 744 |
+
Text: Text object containing the task speed.
|
| 745 |
+
"""
|
| 746 |
+
if speed is None:
|
| 747 |
+
return Text("", style="progress.percentage")
|
| 748 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 749 |
+
int(speed),
|
| 750 |
+
["", "×10³", "×10⁶", "×10⁹", "×10¹²"],
|
| 751 |
+
1000,
|
| 752 |
+
)
|
| 753 |
+
data_speed = speed / unit
|
| 754 |
+
return Text(f"{data_speed:.1f}{suffix} it/s", style="progress.percentage")
|
| 755 |
+
|
| 756 |
+
def render(self, task: "Task") -> Text:
|
| 757 |
+
if task.total is None and self.show_speed:
|
| 758 |
+
return self.render_speed(task.finished_speed or task.speed)
|
| 759 |
+
text_format = (
|
| 760 |
+
self.text_format_no_percentage if task.total is None else self.text_format
|
| 761 |
+
)
|
| 762 |
+
_text = text_format.format(task=task)
|
| 763 |
+
if self.markup:
|
| 764 |
+
text = Text.from_markup(_text, style=self.style, justify=self.justify)
|
| 765 |
+
else:
|
| 766 |
+
text = Text(_text, style=self.style, justify=self.justify)
|
| 767 |
+
if self.highlighter:
|
| 768 |
+
self.highlighter.highlight(text)
|
| 769 |
+
return text
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
class TimeRemainingColumn(ProgressColumn):
|
| 773 |
+
"""Renders estimated time remaining.
|
| 774 |
+
|
| 775 |
+
Args:
|
| 776 |
+
compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False.
|
| 777 |
+
elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False.
|
| 778 |
+
"""
|
| 779 |
+
|
| 780 |
+
# Only refresh twice a second to prevent jitter
|
| 781 |
+
max_refresh = 0.5
|
| 782 |
+
|
| 783 |
+
def __init__(
|
| 784 |
+
self,
|
| 785 |
+
compact: bool = False,
|
| 786 |
+
elapsed_when_finished: bool = False,
|
| 787 |
+
table_column: Optional[Column] = None,
|
| 788 |
+
):
|
| 789 |
+
self.compact = compact
|
| 790 |
+
self.elapsed_when_finished = elapsed_when_finished
|
| 791 |
+
super().__init__(table_column=table_column)
|
| 792 |
+
|
| 793 |
+
def render(self, task: "Task") -> Text:
|
| 794 |
+
"""Show time remaining."""
|
| 795 |
+
if self.elapsed_when_finished and task.finished:
|
| 796 |
+
task_time = task.finished_time
|
| 797 |
+
style = "progress.elapsed"
|
| 798 |
+
else:
|
| 799 |
+
task_time = task.time_remaining
|
| 800 |
+
style = "progress.remaining"
|
| 801 |
+
|
| 802 |
+
if task.total is None:
|
| 803 |
+
return Text("", style=style)
|
| 804 |
+
|
| 805 |
+
if task_time is None:
|
| 806 |
+
return Text("--:--" if self.compact else "-:--:--", style=style)
|
| 807 |
+
|
| 808 |
+
# Based on https://github.com/tqdm/tqdm/blob/master/tqdm/std.py
|
| 809 |
+
minutes, seconds = divmod(int(task_time), 60)
|
| 810 |
+
hours, minutes = divmod(minutes, 60)
|
| 811 |
+
|
| 812 |
+
if self.compact and not hours:
|
| 813 |
+
formatted = f"{minutes:02d}:{seconds:02d}"
|
| 814 |
+
else:
|
| 815 |
+
formatted = f"{hours:d}:{minutes:02d}:{seconds:02d}"
|
| 816 |
+
|
| 817 |
+
return Text(formatted, style=style)
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
class FileSizeColumn(ProgressColumn):
|
| 821 |
+
"""Renders completed filesize."""
|
| 822 |
+
|
| 823 |
+
def render(self, task: "Task") -> Text:
|
| 824 |
+
"""Show data completed."""
|
| 825 |
+
data_size = filesize.decimal(int(task.completed))
|
| 826 |
+
return Text(data_size, style="progress.filesize")
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
class TotalFileSizeColumn(ProgressColumn):
|
| 830 |
+
"""Renders total filesize."""
|
| 831 |
+
|
| 832 |
+
def render(self, task: "Task") -> Text:
|
| 833 |
+
"""Show data completed."""
|
| 834 |
+
data_size = filesize.decimal(int(task.total)) if task.total is not None else ""
|
| 835 |
+
return Text(data_size, style="progress.filesize.total")
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
class MofNCompleteColumn(ProgressColumn):
|
| 839 |
+
"""Renders completed count/total, e.g. ' 10/1000'.
|
| 840 |
+
|
| 841 |
+
Best for bounded tasks with int quantities.
|
| 842 |
+
|
| 843 |
+
Space pads the completed count so that progress length does not change as task progresses
|
| 844 |
+
past powers of 10.
|
| 845 |
+
|
| 846 |
+
Args:
|
| 847 |
+
separator (str, optional): Text to separate completed and total values. Defaults to "/".
|
| 848 |
+
"""
|
| 849 |
+
|
| 850 |
+
def __init__(self, separator: str = "/", table_column: Optional[Column] = None):
|
| 851 |
+
self.separator = separator
|
| 852 |
+
super().__init__(table_column=table_column)
|
| 853 |
+
|
| 854 |
+
def render(self, task: "Task") -> Text:
|
| 855 |
+
"""Show completed/total."""
|
| 856 |
+
completed = int(task.completed)
|
| 857 |
+
total = int(task.total) if task.total is not None else "?"
|
| 858 |
+
total_width = len(str(total))
|
| 859 |
+
return Text(
|
| 860 |
+
f"{completed:{total_width}d}{self.separator}{total}",
|
| 861 |
+
style="progress.download",
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
class DownloadColumn(ProgressColumn):
|
| 866 |
+
"""Renders file size downloaded and total, e.g. '0.5/2.3 GB'.
|
| 867 |
+
|
| 868 |
+
Args:
|
| 869 |
+
binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False.
|
| 870 |
+
"""
|
| 871 |
+
|
| 872 |
+
def __init__(
|
| 873 |
+
self, binary_units: bool = False, table_column: Optional[Column] = None
|
| 874 |
+
) -> None:
|
| 875 |
+
self.binary_units = binary_units
|
| 876 |
+
super().__init__(table_column=table_column)
|
| 877 |
+
|
| 878 |
+
def render(self, task: "Task") -> Text:
|
| 879 |
+
"""Calculate common unit for completed and total."""
|
| 880 |
+
completed = int(task.completed)
|
| 881 |
+
|
| 882 |
+
unit_and_suffix_calculation_base = (
|
| 883 |
+
int(task.total) if task.total is not None else completed
|
| 884 |
+
)
|
| 885 |
+
if self.binary_units:
|
| 886 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 887 |
+
unit_and_suffix_calculation_base,
|
| 888 |
+
["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"],
|
| 889 |
+
1024,
|
| 890 |
+
)
|
| 891 |
+
else:
|
| 892 |
+
unit, suffix = filesize.pick_unit_and_suffix(
|
| 893 |
+
unit_and_suffix_calculation_base,
|
| 894 |
+
["bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
|
| 895 |
+
1000,
|
| 896 |
+
)
|
| 897 |
+
precision = 0 if unit == 1 else 1
|
| 898 |
+
|
| 899 |
+
completed_ratio = completed / unit
|
| 900 |
+
completed_str = f"{completed_ratio:,.{precision}f}"
|
| 901 |
+
|
| 902 |
+
if task.total is not None:
|
| 903 |
+
total = int(task.total)
|
| 904 |
+
total_ratio = total / unit
|
| 905 |
+
total_str = f"{total_ratio:,.{precision}f}"
|
| 906 |
+
else:
|
| 907 |
+
total_str = "?"
|
| 908 |
+
|
| 909 |
+
download_status = f"{completed_str}/{total_str} {suffix}"
|
| 910 |
+
download_text = Text(download_status, style="progress.download")
|
| 911 |
+
return download_text
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
class TransferSpeedColumn(ProgressColumn):
|
| 915 |
+
"""Renders human readable transfer speed."""
|
| 916 |
+
|
| 917 |
+
def render(self, task: "Task") -> Text:
|
| 918 |
+
"""Show data transfer speed."""
|
| 919 |
+
speed = task.finished_speed or task.speed
|
| 920 |
+
if speed is None:
|
| 921 |
+
return Text("?", style="progress.data.speed")
|
| 922 |
+
data_speed = filesize.decimal(int(speed))
|
| 923 |
+
return Text(f"{data_speed}/s", style="progress.data.speed")
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
class ProgressSample(NamedTuple):
|
| 927 |
+
"""Sample of progress for a given time."""
|
| 928 |
+
|
| 929 |
+
timestamp: float
|
| 930 |
+
"""Timestamp of sample."""
|
| 931 |
+
completed: float
|
| 932 |
+
"""Number of steps completed."""
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
@dataclass
|
| 936 |
+
class Task:
|
| 937 |
+
"""Information regarding a progress task.
|
| 938 |
+
|
| 939 |
+
This object should be considered read-only outside of the :class:`~Progress` class.
|
| 940 |
+
|
| 941 |
+
"""
|
| 942 |
+
|
| 943 |
+
id: TaskID
|
| 944 |
+
"""Task ID associated with this task (used in Progress methods)."""
|
| 945 |
+
|
| 946 |
+
description: str
|
| 947 |
+
"""str: Description of the task."""
|
| 948 |
+
|
| 949 |
+
total: Optional[float]
|
| 950 |
+
"""Optional[float]: Total number of steps in this task."""
|
| 951 |
+
|
| 952 |
+
completed: float
|
| 953 |
+
"""float: Number of steps completed"""
|
| 954 |
+
|
| 955 |
+
_get_time: GetTimeCallable
|
| 956 |
+
"""Callable to get the current time."""
|
| 957 |
+
|
| 958 |
+
finished_time: Optional[float] = None
|
| 959 |
+
"""float: Time task was finished."""
|
| 960 |
+
|
| 961 |
+
visible: bool = True
|
| 962 |
+
"""bool: Indicates if this task is visible in the progress display."""
|
| 963 |
+
|
| 964 |
+
fields: Dict[str, Any] = field(default_factory=dict)
|
| 965 |
+
"""dict: Arbitrary fields passed in via Progress.update."""
|
| 966 |
+
|
| 967 |
+
start_time: Optional[float] = field(default=None, init=False, repr=False)
|
| 968 |
+
"""Optional[float]: Time this task was started, or None if not started."""
|
| 969 |
+
|
| 970 |
+
stop_time: Optional[float] = field(default=None, init=False, repr=False)
|
| 971 |
+
"""Optional[float]: Time this task was stopped, or None if not stopped."""
|
| 972 |
+
|
| 973 |
+
finished_speed: Optional[float] = None
|
| 974 |
+
"""Optional[float]: The last speed for a finished task."""
|
| 975 |
+
|
| 976 |
+
_progress: Deque[ProgressSample] = field(
|
| 977 |
+
default_factory=lambda: deque(maxlen=1000), init=False, repr=False
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
_lock: RLock = field(repr=False, default_factory=RLock)
|
| 981 |
+
"""Thread lock."""
|
| 982 |
+
|
| 983 |
+
def get_time(self) -> float:
|
| 984 |
+
"""float: Get the current time, in seconds."""
|
| 985 |
+
return self._get_time()
|
| 986 |
+
|
| 987 |
+
@property
|
| 988 |
+
def started(self) -> bool:
|
| 989 |
+
"""bool: Check if the task as started."""
|
| 990 |
+
return self.start_time is not None
|
| 991 |
+
|
| 992 |
+
@property
|
| 993 |
+
def remaining(self) -> Optional[float]:
|
| 994 |
+
"""Optional[float]: Get the number of steps remaining, if a non-None total was set."""
|
| 995 |
+
if self.total is None:
|
| 996 |
+
return None
|
| 997 |
+
return self.total - self.completed
|
| 998 |
+
|
| 999 |
+
@property
|
| 1000 |
+
def elapsed(self) -> Optional[float]:
|
| 1001 |
+
"""Optional[float]: Time elapsed since task was started, or ``None`` if the task hasn't started."""
|
| 1002 |
+
if self.start_time is None:
|
| 1003 |
+
return None
|
| 1004 |
+
if self.stop_time is not None:
|
| 1005 |
+
return self.stop_time - self.start_time
|
| 1006 |
+
return self.get_time() - self.start_time
|
| 1007 |
+
|
| 1008 |
+
@property
|
| 1009 |
+
def finished(self) -> bool:
|
| 1010 |
+
"""Check if the task has finished."""
|
| 1011 |
+
return self.finished_time is not None
|
| 1012 |
+
|
| 1013 |
+
@property
|
| 1014 |
+
def percentage(self) -> float:
|
| 1015 |
+
"""float: Get progress of task as a percentage. If a None total was set, returns 0"""
|
| 1016 |
+
if not self.total:
|
| 1017 |
+
return 0.0
|
| 1018 |
+
completed = (self.completed / self.total) * 100.0
|
| 1019 |
+
completed = min(100.0, max(0.0, completed))
|
| 1020 |
+
return completed
|
| 1021 |
+
|
| 1022 |
+
@property
|
| 1023 |
+
def speed(self) -> Optional[float]:
|
| 1024 |
+
"""Optional[float]: Get the estimated speed in steps per second."""
|
| 1025 |
+
if self.start_time is None:
|
| 1026 |
+
return None
|
| 1027 |
+
with self._lock:
|
| 1028 |
+
progress = self._progress
|
| 1029 |
+
if not progress:
|
| 1030 |
+
return None
|
| 1031 |
+
total_time = progress[-1].timestamp - progress[0].timestamp
|
| 1032 |
+
if total_time == 0:
|
| 1033 |
+
return None
|
| 1034 |
+
iter_progress = iter(progress)
|
| 1035 |
+
next(iter_progress)
|
| 1036 |
+
total_completed = sum(sample.completed for sample in iter_progress)
|
| 1037 |
+
speed = total_completed / total_time
|
| 1038 |
+
return speed
|
| 1039 |
+
|
| 1040 |
+
@property
|
| 1041 |
+
def time_remaining(self) -> Optional[float]:
|
| 1042 |
+
"""Optional[float]: Get estimated time to completion, or ``None`` if no data."""
|
| 1043 |
+
if self.finished:
|
| 1044 |
+
return 0.0
|
| 1045 |
+
speed = self.speed
|
| 1046 |
+
if not speed:
|
| 1047 |
+
return None
|
| 1048 |
+
remaining = self.remaining
|
| 1049 |
+
if remaining is None:
|
| 1050 |
+
return None
|
| 1051 |
+
estimate = ceil(remaining / speed)
|
| 1052 |
+
return estimate
|
| 1053 |
+
|
| 1054 |
+
def _reset(self) -> None:
|
| 1055 |
+
"""Reset progress."""
|
| 1056 |
+
self._progress.clear()
|
| 1057 |
+
self.finished_time = None
|
| 1058 |
+
self.finished_speed = None
|
| 1059 |
+
|
| 1060 |
+
|
| 1061 |
+
class Progress(JupyterMixin):
|
| 1062 |
+
"""Renders an auto-updating progress bar(s).
|
| 1063 |
+
|
| 1064 |
+
Args:
|
| 1065 |
+
console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.
|
| 1066 |
+
auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.
|
| 1067 |
+
refresh_per_second (float, optional): Number of times per second to refresh the progress information. Defaults to 10.
|
| 1068 |
+
speed_estimate_period: (float, optional): Period (in seconds) used to calculate the speed estimate. Defaults to 30.
|
| 1069 |
+
transient: (bool, optional): Clear the progress on exit. Defaults to False.
|
| 1070 |
+
redirect_stdout: (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
|
| 1071 |
+
redirect_stderr: (bool, optional): Enable redirection of stderr. Defaults to True.
|
| 1072 |
+
get_time: (Callable, optional): A callable that gets the current time, or None to use Console.get_time. Defaults to None.
|
| 1073 |
+
disable (bool, optional): Disable progress display. Defaults to False
|
| 1074 |
+
expand (bool, optional): Expand tasks table to fit width. Defaults to False.
|
| 1075 |
+
"""
|
| 1076 |
+
|
| 1077 |
+
def __init__(
|
| 1078 |
+
self,
|
| 1079 |
+
*columns: Union[str, ProgressColumn],
|
| 1080 |
+
console: Optional[Console] = None,
|
| 1081 |
+
auto_refresh: bool = True,
|
| 1082 |
+
refresh_per_second: float = 10,
|
| 1083 |
+
speed_estimate_period: float = 30.0,
|
| 1084 |
+
transient: bool = False,
|
| 1085 |
+
redirect_stdout: bool = True,
|
| 1086 |
+
redirect_stderr: bool = True,
|
| 1087 |
+
get_time: Optional[GetTimeCallable] = None,
|
| 1088 |
+
disable: bool = False,
|
| 1089 |
+
expand: bool = False,
|
| 1090 |
+
) -> None:
|
| 1091 |
+
assert refresh_per_second > 0, "refresh_per_second must be > 0"
|
| 1092 |
+
self._lock = RLock()
|
| 1093 |
+
self.columns = columns or self.get_default_columns()
|
| 1094 |
+
self.speed_estimate_period = speed_estimate_period
|
| 1095 |
+
|
| 1096 |
+
self.disable = disable
|
| 1097 |
+
self.expand = expand
|
| 1098 |
+
self._tasks: Dict[TaskID, Task] = {}
|
| 1099 |
+
self._task_index: TaskID = TaskID(0)
|
| 1100 |
+
self.live = Live(
|
| 1101 |
+
console=console or get_console(),
|
| 1102 |
+
auto_refresh=auto_refresh,
|
| 1103 |
+
refresh_per_second=refresh_per_second,
|
| 1104 |
+
transient=transient,
|
| 1105 |
+
redirect_stdout=redirect_stdout,
|
| 1106 |
+
redirect_stderr=redirect_stderr,
|
| 1107 |
+
get_renderable=self.get_renderable,
|
| 1108 |
+
)
|
| 1109 |
+
self.get_time = get_time or self.console.get_time
|
| 1110 |
+
self.print = self.console.print
|
| 1111 |
+
self.log = self.console.log
|
| 1112 |
+
|
| 1113 |
+
@classmethod
|
| 1114 |
+
def get_default_columns(cls) -> Tuple[ProgressColumn, ...]:
|
| 1115 |
+
"""Get the default columns used for a new Progress instance:
|
| 1116 |
+
- a text column for the description (TextColumn)
|
| 1117 |
+
- the bar itself (BarColumn)
|
| 1118 |
+
- a text column showing completion percentage (TextColumn)
|
| 1119 |
+
- an estimated-time-remaining column (TimeRemainingColumn)
|
| 1120 |
+
If the Progress instance is created without passing a columns argument,
|
| 1121 |
+
the default columns defined here will be used.
|
| 1122 |
+
|
| 1123 |
+
You can also create a Progress instance using custom columns before
|
| 1124 |
+
and/or after the defaults, as in this example:
|
| 1125 |
+
|
| 1126 |
+
progress = Progress(
|
| 1127 |
+
SpinnerColumn(),
|
| 1128 |
+
*Progress.get_default_columns(),
|
| 1129 |
+
"Elapsed:",
|
| 1130 |
+
TimeElapsedColumn(),
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
This code shows the creation of a Progress display, containing
|
| 1134 |
+
a spinner to the left, the default columns, and a labeled elapsed
|
| 1135 |
+
time column.
|
| 1136 |
+
"""
|
| 1137 |
+
return (
|
| 1138 |
+
TextColumn("[progress.description]{task.description}"),
|
| 1139 |
+
BarColumn(),
|
| 1140 |
+
TaskProgressColumn(),
|
| 1141 |
+
TimeRemainingColumn(),
|
| 1142 |
+
)
|
| 1143 |
+
|
| 1144 |
+
@property
|
| 1145 |
+
def console(self) -> Console:
|
| 1146 |
+
return self.live.console
|
| 1147 |
+
|
| 1148 |
+
@property
|
| 1149 |
+
def tasks(self) -> List[Task]:
|
| 1150 |
+
"""Get a list of Task instances."""
|
| 1151 |
+
with self._lock:
|
| 1152 |
+
return list(self._tasks.values())
|
| 1153 |
+
|
| 1154 |
+
@property
|
| 1155 |
+
def task_ids(self) -> List[TaskID]:
|
| 1156 |
+
"""A list of task IDs."""
|
| 1157 |
+
with self._lock:
|
| 1158 |
+
return list(self._tasks.keys())
|
| 1159 |
+
|
| 1160 |
+
@property
|
| 1161 |
+
def finished(self) -> bool:
|
| 1162 |
+
"""Check if all tasks have been completed."""
|
| 1163 |
+
with self._lock:
|
| 1164 |
+
if not self._tasks:
|
| 1165 |
+
return True
|
| 1166 |
+
return all(task.finished for task in self._tasks.values())
|
| 1167 |
+
|
| 1168 |
+
def start(self) -> None:
|
| 1169 |
+
"""Start the progress display."""
|
| 1170 |
+
if not self.disable:
|
| 1171 |
+
self.live.start(refresh=True)
|
| 1172 |
+
|
| 1173 |
+
def stop(self) -> None:
|
| 1174 |
+
"""Stop the progress display."""
|
| 1175 |
+
if not self.disable:
|
| 1176 |
+
self.live.stop()
|
| 1177 |
+
if not self.console.is_interactive and not self.console.is_jupyter:
|
| 1178 |
+
self.console.print()
|
| 1179 |
+
|
| 1180 |
+
def __enter__(self) -> Self:
|
| 1181 |
+
self.start()
|
| 1182 |
+
return self
|
| 1183 |
+
|
| 1184 |
+
def __exit__(
|
| 1185 |
+
self,
|
| 1186 |
+
exc_type: Optional[Type[BaseException]],
|
| 1187 |
+
exc_val: Optional[BaseException],
|
| 1188 |
+
exc_tb: Optional[TracebackType],
|
| 1189 |
+
) -> None:
|
| 1190 |
+
self.stop()
|
| 1191 |
+
|
| 1192 |
+
def track(
|
| 1193 |
+
self,
|
| 1194 |
+
sequence: Iterable[ProgressType],
|
| 1195 |
+
total: Optional[float] = None,
|
| 1196 |
+
completed: int = 0,
|
| 1197 |
+
task_id: Optional[TaskID] = None,
|
| 1198 |
+
description: str = "Working...",
|
| 1199 |
+
update_period: float = 0.1,
|
| 1200 |
+
) -> Iterable[ProgressType]:
|
| 1201 |
+
"""Track progress by iterating over a sequence.
|
| 1202 |
+
|
| 1203 |
+
You can also track progress of an iterable, which might require that you additionally specify ``total``.
|
| 1204 |
+
|
| 1205 |
+
Args:
|
| 1206 |
+
sequence (Iterable[ProgressType]): Values you want to iterate over and track progress.
|
| 1207 |
+
total: (float, optional): Total number of steps. Default is len(sequence).
|
| 1208 |
+
completed (int, optional): Number of steps completed so far. Defaults to 0.
|
| 1209 |
+
task_id: (TaskID): Task to track. Default is new task.
|
| 1210 |
+
description: (str, optional): Description of task, if new task is created.
|
| 1211 |
+
update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
|
| 1212 |
+
|
| 1213 |
+
Returns:
|
| 1214 |
+
Iterable[ProgressType]: An iterable of values taken from the provided sequence.
|
| 1215 |
+
"""
|
| 1216 |
+
if total is None:
|
| 1217 |
+
total = float(length_hint(sequence)) or None
|
| 1218 |
+
|
| 1219 |
+
if task_id is None:
|
| 1220 |
+
task_id = self.add_task(description, total=total, completed=completed)
|
| 1221 |
+
else:
|
| 1222 |
+
self.update(task_id, total=total, completed=completed)
|
| 1223 |
+
|
| 1224 |
+
if self.live.auto_refresh:
|
| 1225 |
+
with _TrackThread(self, task_id, update_period) as track_thread:
|
| 1226 |
+
for value in sequence:
|
| 1227 |
+
yield value
|
| 1228 |
+
track_thread.completed += 1
|
| 1229 |
+
else:
|
| 1230 |
+
advance = self.advance
|
| 1231 |
+
refresh = self.refresh
|
| 1232 |
+
for value in sequence:
|
| 1233 |
+
yield value
|
| 1234 |
+
advance(task_id, 1)
|
| 1235 |
+
refresh()
|
| 1236 |
+
|
| 1237 |
+
def wrap_file(
|
| 1238 |
+
self,
|
| 1239 |
+
file: BinaryIO,
|
| 1240 |
+
total: Optional[int] = None,
|
| 1241 |
+
*,
|
| 1242 |
+
task_id: Optional[TaskID] = None,
|
| 1243 |
+
description: str = "Reading...",
|
| 1244 |
+
) -> BinaryIO:
|
| 1245 |
+
"""Track progress file reading from a binary file.
|
| 1246 |
+
|
| 1247 |
+
Args:
|
| 1248 |
+
file (BinaryIO): A file-like object opened in binary mode.
|
| 1249 |
+
total (int, optional): Total number of bytes to read. This must be provided unless a task with a total is also given.
|
| 1250 |
+
task_id (TaskID): Task to track. Default is new task.
|
| 1251 |
+
description (str, optional): Description of task, if new task is created.
|
| 1252 |
+
|
| 1253 |
+
Returns:
|
| 1254 |
+
BinaryIO: A readable file-like object in binary mode.
|
| 1255 |
+
|
| 1256 |
+
Raises:
|
| 1257 |
+
ValueError: When no total value can be extracted from the arguments or the task.
|
| 1258 |
+
"""
|
| 1259 |
+
# attempt to recover the total from the task
|
| 1260 |
+
total_bytes: Optional[float] = None
|
| 1261 |
+
if total is not None:
|
| 1262 |
+
total_bytes = total
|
| 1263 |
+
elif task_id is not None:
|
| 1264 |
+
with self._lock:
|
| 1265 |
+
total_bytes = self._tasks[task_id].total
|
| 1266 |
+
if total_bytes is None:
|
| 1267 |
+
raise ValueError(
|
| 1268 |
+
f"unable to get the total number of bytes, please specify 'total'"
|
| 1269 |
+
)
|
| 1270 |
+
|
| 1271 |
+
# update total of task or create new task
|
| 1272 |
+
if task_id is None:
|
| 1273 |
+
task_id = self.add_task(description, total=total_bytes)
|
| 1274 |
+
else:
|
| 1275 |
+
self.update(task_id, total=total_bytes)
|
| 1276 |
+
|
| 1277 |
+
return _Reader(file, self, task_id, close_handle=False)
|
| 1278 |
+
|
| 1279 |
+
@typing.overload
|
| 1280 |
+
def open(
|
| 1281 |
+
self,
|
| 1282 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 1283 |
+
mode: Literal["rb"],
|
| 1284 |
+
buffering: int = -1,
|
| 1285 |
+
encoding: Optional[str] = None,
|
| 1286 |
+
errors: Optional[str] = None,
|
| 1287 |
+
newline: Optional[str] = None,
|
| 1288 |
+
*,
|
| 1289 |
+
total: Optional[int] = None,
|
| 1290 |
+
task_id: Optional[TaskID] = None,
|
| 1291 |
+
description: str = "Reading...",
|
| 1292 |
+
) -> BinaryIO:
|
| 1293 |
+
pass
|
| 1294 |
+
|
| 1295 |
+
@typing.overload
|
| 1296 |
+
def open(
|
| 1297 |
+
self,
|
| 1298 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 1299 |
+
mode: Union[Literal["r"], Literal["rt"]],
|
| 1300 |
+
buffering: int = -1,
|
| 1301 |
+
encoding: Optional[str] = None,
|
| 1302 |
+
errors: Optional[str] = None,
|
| 1303 |
+
newline: Optional[str] = None,
|
| 1304 |
+
*,
|
| 1305 |
+
total: Optional[int] = None,
|
| 1306 |
+
task_id: Optional[TaskID] = None,
|
| 1307 |
+
description: str = "Reading...",
|
| 1308 |
+
) -> TextIO:
|
| 1309 |
+
pass
|
| 1310 |
+
|
| 1311 |
+
def open(
|
| 1312 |
+
self,
|
| 1313 |
+
file: Union[str, "PathLike[str]", bytes],
|
| 1314 |
+
mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r",
|
| 1315 |
+
buffering: int = -1,
|
| 1316 |
+
encoding: Optional[str] = None,
|
| 1317 |
+
errors: Optional[str] = None,
|
| 1318 |
+
newline: Optional[str] = None,
|
| 1319 |
+
*,
|
| 1320 |
+
total: Optional[int] = None,
|
| 1321 |
+
task_id: Optional[TaskID] = None,
|
| 1322 |
+
description: str = "Reading...",
|
| 1323 |
+
) -> Union[BinaryIO, TextIO]:
|
| 1324 |
+
"""Track progress while reading from a binary file.
|
| 1325 |
+
|
| 1326 |
+
Args:
|
| 1327 |
+
path (Union[str, PathLike[str]]): The path to the file to read.
|
| 1328 |
+
mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
|
| 1329 |
+
buffering (int): The buffering strategy to use, see :func:`io.open`.
|
| 1330 |
+
encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
|
| 1331 |
+
errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
|
| 1332 |
+
newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`.
|
| 1333 |
+
total (int, optional): Total number of bytes to read. If none given, os.stat(path).st_size is used.
|
| 1334 |
+
task_id (TaskID): Task to track. Default is new task.
|
| 1335 |
+
description (str, optional): Description of task, if new task is created.
|
| 1336 |
+
|
| 1337 |
+
Returns:
|
| 1338 |
+
BinaryIO: A readable file-like object in binary mode.
|
| 1339 |
+
|
| 1340 |
+
Raises:
|
| 1341 |
+
ValueError: When an invalid mode is given.
|
| 1342 |
+
"""
|
| 1343 |
+
# normalize the mode (always rb, rt)
|
| 1344 |
+
_mode = "".join(sorted(mode, reverse=False))
|
| 1345 |
+
if _mode not in ("br", "rt", "r"):
|
| 1346 |
+
raise ValueError(f"invalid mode {mode!r}")
|
| 1347 |
+
|
| 1348 |
+
# patch buffering to provide the same behaviour as the builtin `open`
|
| 1349 |
+
line_buffering = buffering == 1
|
| 1350 |
+
if _mode == "br" and buffering == 1:
|
| 1351 |
+
warnings.warn(
|
| 1352 |
+
"line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used",
|
| 1353 |
+
RuntimeWarning,
|
| 1354 |
+
)
|
| 1355 |
+
buffering = -1
|
| 1356 |
+
elif _mode in ("rt", "r"):
|
| 1357 |
+
if buffering == 0:
|
| 1358 |
+
raise ValueError("can't have unbuffered text I/O")
|
| 1359 |
+
elif buffering == 1:
|
| 1360 |
+
buffering = -1
|
| 1361 |
+
|
| 1362 |
+
# attempt to get the total with `os.stat`
|
| 1363 |
+
if total is None:
|
| 1364 |
+
total = stat(file).st_size
|
| 1365 |
+
|
| 1366 |
+
# update total of task or create new task
|
| 1367 |
+
if task_id is None:
|
| 1368 |
+
task_id = self.add_task(description, total=total)
|
| 1369 |
+
else:
|
| 1370 |
+
self.update(task_id, total=total)
|
| 1371 |
+
|
| 1372 |
+
# open the file in binary mode,
|
| 1373 |
+
handle = io.open(file, "rb", buffering=buffering)
|
| 1374 |
+
reader = _Reader(handle, self, task_id, close_handle=True)
|
| 1375 |
+
|
| 1376 |
+
# wrap the reader in a `TextIOWrapper` if text mode
|
| 1377 |
+
if mode in ("r", "rt"):
|
| 1378 |
+
return io.TextIOWrapper(
|
| 1379 |
+
reader,
|
| 1380 |
+
encoding=encoding,
|
| 1381 |
+
errors=errors,
|
| 1382 |
+
newline=newline,
|
| 1383 |
+
line_buffering=line_buffering,
|
| 1384 |
+
)
|
| 1385 |
+
|
| 1386 |
+
return reader
|
| 1387 |
+
|
| 1388 |
+
def start_task(self, task_id: TaskID) -> None:
|
| 1389 |
+
"""Start a task.
|
| 1390 |
+
|
| 1391 |
+
Starts a task (used when calculating elapsed time). You may need to call this manually,
|
| 1392 |
+
if you called ``add_task`` with ``start=False``.
|
| 1393 |
+
|
| 1394 |
+
Args:
|
| 1395 |
+
task_id (TaskID): ID of task.
|
| 1396 |
+
"""
|
| 1397 |
+
with self._lock:
|
| 1398 |
+
task = self._tasks[task_id]
|
| 1399 |
+
if task.start_time is None:
|
| 1400 |
+
task.start_time = self.get_time()
|
| 1401 |
+
|
| 1402 |
+
def stop_task(self, task_id: TaskID) -> None:
|
| 1403 |
+
"""Stop a task.
|
| 1404 |
+
|
| 1405 |
+
This will freeze the elapsed time on the task.
|
| 1406 |
+
|
| 1407 |
+
Args:
|
| 1408 |
+
task_id (TaskID): ID of task.
|
| 1409 |
+
"""
|
| 1410 |
+
with self._lock:
|
| 1411 |
+
task = self._tasks[task_id]
|
| 1412 |
+
current_time = self.get_time()
|
| 1413 |
+
if task.start_time is None:
|
| 1414 |
+
task.start_time = current_time
|
| 1415 |
+
task.stop_time = current_time
|
| 1416 |
+
|
| 1417 |
+
def update(
|
| 1418 |
+
self,
|
| 1419 |
+
task_id: TaskID,
|
| 1420 |
+
*,
|
| 1421 |
+
total: Optional[float] = None,
|
| 1422 |
+
completed: Optional[float] = None,
|
| 1423 |
+
advance: Optional[float] = None,
|
| 1424 |
+
description: Optional[str] = None,
|
| 1425 |
+
visible: Optional[bool] = None,
|
| 1426 |
+
refresh: bool = False,
|
| 1427 |
+
**fields: Any,
|
| 1428 |
+
) -> None:
|
| 1429 |
+
"""Update information associated with a task.
|
| 1430 |
+
|
| 1431 |
+
Args:
|
| 1432 |
+
task_id (TaskID): Task id (returned by add_task).
|
| 1433 |
+
total (float, optional): Updates task.total if not None.
|
| 1434 |
+
completed (float, optional): Updates task.completed if not None.
|
| 1435 |
+
advance (float, optional): Add a value to task.completed if not None.
|
| 1436 |
+
description (str, optional): Change task description if not None.
|
| 1437 |
+
visible (bool, optional): Set visible flag if not None.
|
| 1438 |
+
refresh (bool): Force a refresh of progress information. Default is False.
|
| 1439 |
+
**fields (Any): Additional data fields required for rendering.
|
| 1440 |
+
"""
|
| 1441 |
+
with self._lock:
|
| 1442 |
+
task = self._tasks[task_id]
|
| 1443 |
+
completed_start = task.completed
|
| 1444 |
+
|
| 1445 |
+
if total is not None and total != task.total:
|
| 1446 |
+
task.total = total
|
| 1447 |
+
task._reset()
|
| 1448 |
+
if advance is not None:
|
| 1449 |
+
task.completed += advance
|
| 1450 |
+
if completed is not None:
|
| 1451 |
+
task.completed = completed
|
| 1452 |
+
if description is not None:
|
| 1453 |
+
task.description = description
|
| 1454 |
+
if visible is not None:
|
| 1455 |
+
task.visible = visible
|
| 1456 |
+
task.fields.update(fields)
|
| 1457 |
+
update_completed = task.completed - completed_start
|
| 1458 |
+
|
| 1459 |
+
current_time = self.get_time()
|
| 1460 |
+
old_sample_time = current_time - self.speed_estimate_period
|
| 1461 |
+
_progress = task._progress
|
| 1462 |
+
|
| 1463 |
+
popleft = _progress.popleft
|
| 1464 |
+
while _progress and _progress[0].timestamp < old_sample_time:
|
| 1465 |
+
popleft()
|
| 1466 |
+
if update_completed > 0:
|
| 1467 |
+
_progress.append(ProgressSample(current_time, update_completed))
|
| 1468 |
+
if (
|
| 1469 |
+
task.total is not None
|
| 1470 |
+
and task.completed >= task.total
|
| 1471 |
+
and task.finished_time is None
|
| 1472 |
+
):
|
| 1473 |
+
task.finished_time = task.elapsed
|
| 1474 |
+
|
| 1475 |
+
if refresh:
|
| 1476 |
+
self.refresh()
|
| 1477 |
+
|
| 1478 |
+
def reset(
|
| 1479 |
+
self,
|
| 1480 |
+
task_id: TaskID,
|
| 1481 |
+
*,
|
| 1482 |
+
start: bool = True,
|
| 1483 |
+
total: Optional[float] = None,
|
| 1484 |
+
completed: int = 0,
|
| 1485 |
+
visible: Optional[bool] = None,
|
| 1486 |
+
description: Optional[str] = None,
|
| 1487 |
+
**fields: Any,
|
| 1488 |
+
) -> None:
|
| 1489 |
+
"""Reset a task so completed is 0 and the clock is reset.
|
| 1490 |
+
|
| 1491 |
+
Args:
|
| 1492 |
+
task_id (TaskID): ID of task.
|
| 1493 |
+
start (bool, optional): Start the task after reset. Defaults to True.
|
| 1494 |
+
total (float, optional): New total steps in task, or None to use current total. Defaults to None.
|
| 1495 |
+
completed (int, optional): Number of steps completed. Defaults to 0.
|
| 1496 |
+
visible (bool, optional): Set visible flag if not None.
|
| 1497 |
+
description (str, optional): Change task description if not None. Defaults to None.
|
| 1498 |
+
**fields (str): Additional data fields required for rendering.
|
| 1499 |
+
"""
|
| 1500 |
+
current_time = self.get_time()
|
| 1501 |
+
with self._lock:
|
| 1502 |
+
task = self._tasks[task_id]
|
| 1503 |
+
task._reset()
|
| 1504 |
+
task.start_time = current_time if start else None
|
| 1505 |
+
if total is not None:
|
| 1506 |
+
task.total = total
|
| 1507 |
+
task.completed = completed
|
| 1508 |
+
if visible is not None:
|
| 1509 |
+
task.visible = visible
|
| 1510 |
+
if fields:
|
| 1511 |
+
task.fields = fields
|
| 1512 |
+
if description is not None:
|
| 1513 |
+
task.description = description
|
| 1514 |
+
task.finished_time = None
|
| 1515 |
+
self.refresh()
|
| 1516 |
+
|
| 1517 |
+
def advance(self, task_id: TaskID, advance: float = 1) -> None:
|
| 1518 |
+
"""Advance task by a number of steps.
|
| 1519 |
+
|
| 1520 |
+
Args:
|
| 1521 |
+
task_id (TaskID): ID of task.
|
| 1522 |
+
advance (float): Number of steps to advance. Default is 1.
|
| 1523 |
+
"""
|
| 1524 |
+
current_time = self.get_time()
|
| 1525 |
+
with self._lock:
|
| 1526 |
+
task = self._tasks[task_id]
|
| 1527 |
+
completed_start = task.completed
|
| 1528 |
+
task.completed += advance
|
| 1529 |
+
update_completed = task.completed - completed_start
|
| 1530 |
+
old_sample_time = current_time - self.speed_estimate_period
|
| 1531 |
+
_progress = task._progress
|
| 1532 |
+
|
| 1533 |
+
popleft = _progress.popleft
|
| 1534 |
+
while _progress and _progress[0].timestamp < old_sample_time:
|
| 1535 |
+
popleft()
|
| 1536 |
+
while len(_progress) > 1000:
|
| 1537 |
+
popleft()
|
| 1538 |
+
_progress.append(ProgressSample(current_time, update_completed))
|
| 1539 |
+
if (
|
| 1540 |
+
task.total is not None
|
| 1541 |
+
and task.completed >= task.total
|
| 1542 |
+
and task.finished_time is None
|
| 1543 |
+
):
|
| 1544 |
+
task.finished_time = task.elapsed
|
| 1545 |
+
task.finished_speed = task.speed
|
| 1546 |
+
|
| 1547 |
+
def refresh(self) -> None:
|
| 1548 |
+
"""Refresh (render) the progress information."""
|
| 1549 |
+
if not self.disable and self.live.is_started:
|
| 1550 |
+
self.live.refresh()
|
| 1551 |
+
|
| 1552 |
+
def get_renderable(self) -> RenderableType:
|
| 1553 |
+
"""Get a renderable for the progress display."""
|
| 1554 |
+
renderable = Group(*self.get_renderables())
|
| 1555 |
+
return renderable
|
| 1556 |
+
|
| 1557 |
+
def get_renderables(self) -> Iterable[RenderableType]:
|
| 1558 |
+
"""Get a number of renderables for the progress display."""
|
| 1559 |
+
table = self.make_tasks_table(self.tasks)
|
| 1560 |
+
yield table
|
| 1561 |
+
|
| 1562 |
+
def make_tasks_table(self, tasks: Iterable[Task]) -> Table:
|
| 1563 |
+
"""Get a table to render the Progress display.
|
| 1564 |
+
|
| 1565 |
+
Args:
|
| 1566 |
+
tasks (Iterable[Task]): An iterable of Task instances, one per row of the table.
|
| 1567 |
+
|
| 1568 |
+
Returns:
|
| 1569 |
+
Table: A table instance.
|
| 1570 |
+
"""
|
| 1571 |
+
table_columns = (
|
| 1572 |
+
(
|
| 1573 |
+
Column(no_wrap=True)
|
| 1574 |
+
if isinstance(_column, str)
|
| 1575 |
+
else _column.get_table_column().copy()
|
| 1576 |
+
)
|
| 1577 |
+
for _column in self.columns
|
| 1578 |
+
)
|
| 1579 |
+
table = Table.grid(*table_columns, padding=(0, 1), expand=self.expand)
|
| 1580 |
+
|
| 1581 |
+
for task in tasks:
|
| 1582 |
+
if task.visible:
|
| 1583 |
+
table.add_row(
|
| 1584 |
+
*(
|
| 1585 |
+
(
|
| 1586 |
+
column.format(task=task)
|
| 1587 |
+
if isinstance(column, str)
|
| 1588 |
+
else column(task)
|
| 1589 |
+
)
|
| 1590 |
+
for column in self.columns
|
| 1591 |
+
)
|
| 1592 |
+
)
|
| 1593 |
+
return table
|
| 1594 |
+
|
| 1595 |
+
def __rich__(self) -> RenderableType:
|
| 1596 |
+
"""Makes the Progress class itself renderable."""
|
| 1597 |
+
with self._lock:
|
| 1598 |
+
return self.get_renderable()
|
| 1599 |
+
|
| 1600 |
+
def add_task(
|
| 1601 |
+
self,
|
| 1602 |
+
description: str,
|
| 1603 |
+
start: bool = True,
|
| 1604 |
+
total: Optional[float] = 100.0,
|
| 1605 |
+
completed: int = 0,
|
| 1606 |
+
visible: bool = True,
|
| 1607 |
+
**fields: Any,
|
| 1608 |
+
) -> TaskID:
|
| 1609 |
+
"""Add a new 'task' to the Progress display.
|
| 1610 |
+
|
| 1611 |
+
Args:
|
| 1612 |
+
description (str): A description of the task.
|
| 1613 |
+
start (bool, optional): Start the task immediately (to calculate elapsed time). If set to False,
|
| 1614 |
+
you will need to call `start` manually. Defaults to True.
|
| 1615 |
+
total (float, optional): Number of total steps in the progress if known.
|
| 1616 |
+
Set to None to render a pulsing animation. Defaults to 100.
|
| 1617 |
+
completed (int, optional): Number of steps completed so far. Defaults to 0.
|
| 1618 |
+
visible (bool, optional): Enable display of the task. Defaults to True.
|
| 1619 |
+
**fields (str): Additional data fields required for rendering.
|
| 1620 |
+
|
| 1621 |
+
Returns:
|
| 1622 |
+
TaskID: An ID you can use when calling `update`.
|
| 1623 |
+
"""
|
| 1624 |
+
with self._lock:
|
| 1625 |
+
task = Task(
|
| 1626 |
+
self._task_index,
|
| 1627 |
+
description,
|
| 1628 |
+
total,
|
| 1629 |
+
completed,
|
| 1630 |
+
visible=visible,
|
| 1631 |
+
fields=fields,
|
| 1632 |
+
_get_time=self.get_time,
|
| 1633 |
+
_lock=self._lock,
|
| 1634 |
+
)
|
| 1635 |
+
self._tasks[self._task_index] = task
|
| 1636 |
+
if start:
|
| 1637 |
+
self.start_task(self._task_index)
|
| 1638 |
+
new_task_index = self._task_index
|
| 1639 |
+
self._task_index = TaskID(int(self._task_index) + 1)
|
| 1640 |
+
self.refresh()
|
| 1641 |
+
return new_task_index
|
| 1642 |
+
|
| 1643 |
+
def remove_task(self, task_id: TaskID) -> None:
|
| 1644 |
+
"""Delete a task if it exists.
|
| 1645 |
+
|
| 1646 |
+
Args:
|
| 1647 |
+
task_id (TaskID): A task ID.
|
| 1648 |
+
|
| 1649 |
+
"""
|
| 1650 |
+
with self._lock:
|
| 1651 |
+
del self._tasks[task_id]
|
| 1652 |
+
|
| 1653 |
+
|
| 1654 |
+
if __name__ == "__main__": # pragma: no coverage
|
| 1655 |
+
import random
|
| 1656 |
+
import time
|
| 1657 |
+
|
| 1658 |
+
from .panel import Panel
|
| 1659 |
+
from .rule import Rule
|
| 1660 |
+
from .syntax import Syntax
|
| 1661 |
+
from .table import Table
|
| 1662 |
+
|
| 1663 |
+
syntax = Syntax(
|
| 1664 |
+
'''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
|
| 1665 |
+
"""Iterate and generate a tuple with a flag for last value."""
|
| 1666 |
+
iter_values = iter(values)
|
| 1667 |
+
try:
|
| 1668 |
+
previous_value = next(iter_values)
|
| 1669 |
+
except StopIteration:
|
| 1670 |
+
return
|
| 1671 |
+
for value in iter_values:
|
| 1672 |
+
yield False, previous_value
|
| 1673 |
+
previous_value = value
|
| 1674 |
+
yield True, previous_value''',
|
| 1675 |
+
"python",
|
| 1676 |
+
line_numbers=True,
|
| 1677 |
+
)
|
| 1678 |
+
|
| 1679 |
+
table = Table("foo", "bar", "baz")
|
| 1680 |
+
table.add_row("1", "2", "3")
|
| 1681 |
+
|
| 1682 |
+
progress_renderables = [
|
| 1683 |
+
"Text may be printed while the progress bars are rendering.",
|
| 1684 |
+
Panel("In fact, [i]any[/i] renderable will work"),
|
| 1685 |
+
"Such as [magenta]tables[/]...",
|
| 1686 |
+
table,
|
| 1687 |
+
"Pretty printed structures...",
|
| 1688 |
+
{"type": "example", "text": "Pretty printed"},
|
| 1689 |
+
"Syntax...",
|
| 1690 |
+
syntax,
|
| 1691 |
+
Rule("Give it a try!"),
|
| 1692 |
+
]
|
| 1693 |
+
|
| 1694 |
+
from itertools import cycle
|
| 1695 |
+
|
| 1696 |
+
examples = cycle(progress_renderables)
|
| 1697 |
+
|
| 1698 |
+
console = Console(record=True)
|
| 1699 |
+
|
| 1700 |
+
with Progress(
|
| 1701 |
+
SpinnerColumn(),
|
| 1702 |
+
*Progress.get_default_columns(),
|
| 1703 |
+
TimeElapsedColumn(),
|
| 1704 |
+
console=console,
|
| 1705 |
+
transient=False,
|
| 1706 |
+
) as progress:
|
| 1707 |
+
task1 = progress.add_task("[red]Downloading", total=1000)
|
| 1708 |
+
task2 = progress.add_task("[green]Processing", total=1000)
|
| 1709 |
+
task3 = progress.add_task("[yellow]Thinking", total=None)
|
| 1710 |
+
|
| 1711 |
+
while not progress.finished:
|
| 1712 |
+
progress.update(task1, advance=0.5)
|
| 1713 |
+
progress.update(task2, advance=0.3)
|
| 1714 |
+
time.sleep(0.01)
|
| 1715 |
+
if random.randint(0, 100) < 1:
|
| 1716 |
+
progress.log(next(examples))
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/progress_bar.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from time import monotonic
|
| 4 |
+
from typing import Iterable, List, Optional
|
| 5 |
+
|
| 6 |
+
from .color import Color, blend_rgb
|
| 7 |
+
from .color_triplet import ColorTriplet
|
| 8 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 9 |
+
from .jupyter import JupyterMixin
|
| 10 |
+
from .measure import Measurement
|
| 11 |
+
from .segment import Segment
|
| 12 |
+
from .style import Style, StyleType
|
| 13 |
+
|
| 14 |
+
# Number of characters before 'pulse' animation repeats
|
| 15 |
+
PULSE_SIZE = 20
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ProgressBar(JupyterMixin):
|
| 19 |
+
"""Renders a (progress) bar. Used by rich.progress.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
total (float, optional): Number of steps in the bar. Defaults to 100. Set to None to render a pulsing animation.
|
| 23 |
+
completed (float, optional): Number of steps completed. Defaults to 0.
|
| 24 |
+
width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None.
|
| 25 |
+
pulse (bool, optional): Enable pulse effect. Defaults to False. Will pulse if a None total was passed.
|
| 26 |
+
style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
|
| 27 |
+
complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
|
| 28 |
+
finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
|
| 29 |
+
pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
|
| 30 |
+
animation_time (Optional[float], optional): Time in seconds to use for animation, or None to use system time.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
total: Optional[float] = 100.0,
|
| 36 |
+
completed: float = 0,
|
| 37 |
+
width: Optional[int] = None,
|
| 38 |
+
pulse: bool = False,
|
| 39 |
+
style: StyleType = "bar.back",
|
| 40 |
+
complete_style: StyleType = "bar.complete",
|
| 41 |
+
finished_style: StyleType = "bar.finished",
|
| 42 |
+
pulse_style: StyleType = "bar.pulse",
|
| 43 |
+
animation_time: Optional[float] = None,
|
| 44 |
+
):
|
| 45 |
+
self.total = total
|
| 46 |
+
self.completed = completed
|
| 47 |
+
self.width = width
|
| 48 |
+
self.pulse = pulse
|
| 49 |
+
self.style = style
|
| 50 |
+
self.complete_style = complete_style
|
| 51 |
+
self.finished_style = finished_style
|
| 52 |
+
self.pulse_style = pulse_style
|
| 53 |
+
self.animation_time = animation_time
|
| 54 |
+
|
| 55 |
+
self._pulse_segments: Optional[List[Segment]] = None
|
| 56 |
+
|
| 57 |
+
def __repr__(self) -> str:
|
| 58 |
+
return f"<Bar {self.completed!r} of {self.total!r}>"
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def percentage_completed(self) -> Optional[float]:
|
| 62 |
+
"""Calculate percentage complete."""
|
| 63 |
+
if self.total is None:
|
| 64 |
+
return None
|
| 65 |
+
completed = (self.completed / self.total) * 100.0
|
| 66 |
+
completed = min(100, max(0.0, completed))
|
| 67 |
+
return completed
|
| 68 |
+
|
| 69 |
+
@lru_cache(maxsize=16)
|
| 70 |
+
def _get_pulse_segments(
|
| 71 |
+
self,
|
| 72 |
+
fore_style: Style,
|
| 73 |
+
back_style: Style,
|
| 74 |
+
color_system: str,
|
| 75 |
+
no_color: bool,
|
| 76 |
+
ascii: bool = False,
|
| 77 |
+
) -> List[Segment]:
|
| 78 |
+
"""Get a list of segments to render a pulse animation.
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
List[Segment]: A list of segments, one segment per character.
|
| 82 |
+
"""
|
| 83 |
+
bar = "-" if ascii else "━"
|
| 84 |
+
segments: List[Segment] = []
|
| 85 |
+
if color_system not in ("standard", "eight_bit", "truecolor") or no_color:
|
| 86 |
+
segments += [Segment(bar, fore_style)] * (PULSE_SIZE // 2)
|
| 87 |
+
segments += [Segment(" " if no_color else bar, back_style)] * (
|
| 88 |
+
PULSE_SIZE - (PULSE_SIZE // 2)
|
| 89 |
+
)
|
| 90 |
+
return segments
|
| 91 |
+
|
| 92 |
+
append = segments.append
|
| 93 |
+
fore_color = (
|
| 94 |
+
fore_style.color.get_truecolor()
|
| 95 |
+
if fore_style.color
|
| 96 |
+
else ColorTriplet(255, 0, 255)
|
| 97 |
+
)
|
| 98 |
+
back_color = (
|
| 99 |
+
back_style.color.get_truecolor()
|
| 100 |
+
if back_style.color
|
| 101 |
+
else ColorTriplet(0, 0, 0)
|
| 102 |
+
)
|
| 103 |
+
cos = math.cos
|
| 104 |
+
pi = math.pi
|
| 105 |
+
_Segment = Segment
|
| 106 |
+
_Style = Style
|
| 107 |
+
from_triplet = Color.from_triplet
|
| 108 |
+
|
| 109 |
+
for index in range(PULSE_SIZE):
|
| 110 |
+
position = index / PULSE_SIZE
|
| 111 |
+
fade = 0.5 + cos(position * pi * 2) / 2.0
|
| 112 |
+
color = blend_rgb(fore_color, back_color, cross_fade=fade)
|
| 113 |
+
append(_Segment(bar, _Style(color=from_triplet(color))))
|
| 114 |
+
return segments
|
| 115 |
+
|
| 116 |
+
def update(self, completed: float, total: Optional[float] = None) -> None:
|
| 117 |
+
"""Update progress with new values.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
completed (float): Number of steps completed.
|
| 121 |
+
total (float, optional): Total number of steps, or ``None`` to not change. Defaults to None.
|
| 122 |
+
"""
|
| 123 |
+
self.completed = completed
|
| 124 |
+
self.total = total if total is not None else self.total
|
| 125 |
+
|
| 126 |
+
def _render_pulse(
|
| 127 |
+
self, console: Console, width: int, ascii: bool = False
|
| 128 |
+
) -> Iterable[Segment]:
|
| 129 |
+
"""Renders the pulse animation.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
console (Console): Console instance.
|
| 133 |
+
width (int): Width in characters of pulse animation.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
RenderResult: [description]
|
| 137 |
+
|
| 138 |
+
Yields:
|
| 139 |
+
Iterator[Segment]: Segments to render pulse
|
| 140 |
+
"""
|
| 141 |
+
fore_style = console.get_style(self.pulse_style, default="white")
|
| 142 |
+
back_style = console.get_style(self.style, default="black")
|
| 143 |
+
|
| 144 |
+
pulse_segments = self._get_pulse_segments(
|
| 145 |
+
fore_style, back_style, console.color_system, console.no_color, ascii=ascii
|
| 146 |
+
)
|
| 147 |
+
segment_count = len(pulse_segments)
|
| 148 |
+
current_time = (
|
| 149 |
+
monotonic() if self.animation_time is None else self.animation_time
|
| 150 |
+
)
|
| 151 |
+
segments = pulse_segments * (int(width / segment_count) + 2)
|
| 152 |
+
offset = int(-current_time * 15) % segment_count
|
| 153 |
+
segments = segments[offset : offset + width]
|
| 154 |
+
yield from segments
|
| 155 |
+
|
| 156 |
+
def __rich_console__(
|
| 157 |
+
self, console: Console, options: ConsoleOptions
|
| 158 |
+
) -> RenderResult:
|
| 159 |
+
width = min(self.width or options.max_width, options.max_width)
|
| 160 |
+
ascii = options.legacy_windows or options.ascii_only
|
| 161 |
+
should_pulse = self.pulse or self.total is None
|
| 162 |
+
if should_pulse:
|
| 163 |
+
yield from self._render_pulse(console, width, ascii=ascii)
|
| 164 |
+
return
|
| 165 |
+
|
| 166 |
+
completed: Optional[float] = (
|
| 167 |
+
min(self.total, max(0, self.completed)) if self.total is not None else None
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
bar = "-" if ascii else "━"
|
| 171 |
+
half_bar_right = " " if ascii else "╸"
|
| 172 |
+
half_bar_left = " " if ascii else "╺"
|
| 173 |
+
complete_halves = (
|
| 174 |
+
int(width * 2 * completed / self.total)
|
| 175 |
+
if self.total and completed is not None
|
| 176 |
+
else width * 2
|
| 177 |
+
)
|
| 178 |
+
bar_count = complete_halves // 2
|
| 179 |
+
half_bar_count = complete_halves % 2
|
| 180 |
+
style = console.get_style(self.style)
|
| 181 |
+
is_finished = self.total is None or self.completed >= self.total
|
| 182 |
+
complete_style = console.get_style(
|
| 183 |
+
self.finished_style if is_finished else self.complete_style
|
| 184 |
+
)
|
| 185 |
+
_Segment = Segment
|
| 186 |
+
if bar_count:
|
| 187 |
+
yield _Segment(bar * bar_count, complete_style)
|
| 188 |
+
if half_bar_count:
|
| 189 |
+
yield _Segment(half_bar_right * half_bar_count, complete_style)
|
| 190 |
+
|
| 191 |
+
if not console.no_color:
|
| 192 |
+
remaining_bars = width - bar_count - half_bar_count
|
| 193 |
+
if remaining_bars and console.color_system is not None:
|
| 194 |
+
if not half_bar_count and bar_count:
|
| 195 |
+
yield _Segment(half_bar_left, style)
|
| 196 |
+
remaining_bars -= 1
|
| 197 |
+
if remaining_bars:
|
| 198 |
+
yield _Segment(bar * remaining_bars, style)
|
| 199 |
+
|
| 200 |
+
def __rich_measure__(
|
| 201 |
+
self, console: Console, options: ConsoleOptions
|
| 202 |
+
) -> Measurement:
|
| 203 |
+
return (
|
| 204 |
+
Measurement(self.width, self.width)
|
| 205 |
+
if self.width is not None
|
| 206 |
+
else Measurement(4, options.max_width)
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__": # pragma: no cover
|
| 211 |
+
console = Console()
|
| 212 |
+
bar = ProgressBar(width=50, total=100)
|
| 213 |
+
|
| 214 |
+
import time
|
| 215 |
+
|
| 216 |
+
console.show_cursor(False)
|
| 217 |
+
for n in range(0, 101, 1):
|
| 218 |
+
bar.update(n)
|
| 219 |
+
console.print(bar)
|
| 220 |
+
console.file.write("\r")
|
| 221 |
+
time.sleep(0.05)
|
| 222 |
+
console.show_cursor(True)
|
| 223 |
+
console.print()
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/prompt.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload
|
| 2 |
+
|
| 3 |
+
from . import get_console
|
| 4 |
+
from .console import Console
|
| 5 |
+
from .text import Text, TextType
|
| 6 |
+
|
| 7 |
+
PromptType = TypeVar("PromptType")
|
| 8 |
+
DefaultType = TypeVar("DefaultType")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PromptError(Exception):
|
| 12 |
+
"""Exception base class for prompt related errors."""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class InvalidResponse(PromptError):
|
| 16 |
+
"""Exception to indicate a response was invalid. Raise this within process_response() to indicate an error
|
| 17 |
+
and provide an error message.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
message (Union[str, Text]): Error message.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, message: TextType) -> None:
|
| 24 |
+
self.message = message
|
| 25 |
+
|
| 26 |
+
def __rich__(self) -> TextType:
|
| 27 |
+
return self.message
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class PromptBase(Generic[PromptType]):
|
| 31 |
+
"""Ask the user for input until a valid response is received. This is the base class, see one of
|
| 32 |
+
the concrete classes for examples.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
prompt (TextType, optional): Prompt text. Defaults to "".
|
| 36 |
+
console (Console, optional): A Console instance or None to use global console. Defaults to None.
|
| 37 |
+
password (bool, optional): Enable password input. Defaults to False.
|
| 38 |
+
choices (List[str], optional): A list of valid choices. Defaults to None.
|
| 39 |
+
case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True.
|
| 40 |
+
show_default (bool, optional): Show default in prompt. Defaults to True.
|
| 41 |
+
show_choices (bool, optional): Show choices in prompt. Defaults to True.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
response_type: type = str
|
| 45 |
+
|
| 46 |
+
validate_error_message = "[prompt.invalid]Please enter a valid value"
|
| 47 |
+
illegal_choice_message = (
|
| 48 |
+
"[prompt.invalid.choice]Please select one of the available options"
|
| 49 |
+
)
|
| 50 |
+
prompt_suffix = ": "
|
| 51 |
+
|
| 52 |
+
choices: Optional[List[str]] = None
|
| 53 |
+
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
prompt: TextType = "",
|
| 57 |
+
*,
|
| 58 |
+
console: Optional[Console] = None,
|
| 59 |
+
password: bool = False,
|
| 60 |
+
choices: Optional[List[str]] = None,
|
| 61 |
+
case_sensitive: bool = True,
|
| 62 |
+
show_default: bool = True,
|
| 63 |
+
show_choices: bool = True,
|
| 64 |
+
) -> None:
|
| 65 |
+
self.console = console or get_console()
|
| 66 |
+
self.prompt = (
|
| 67 |
+
Text.from_markup(prompt, style="prompt")
|
| 68 |
+
if isinstance(prompt, str)
|
| 69 |
+
else prompt
|
| 70 |
+
)
|
| 71 |
+
self.password = password
|
| 72 |
+
if choices is not None:
|
| 73 |
+
self.choices = choices
|
| 74 |
+
self.case_sensitive = case_sensitive
|
| 75 |
+
self.show_default = show_default
|
| 76 |
+
self.show_choices = show_choices
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
@overload
|
| 80 |
+
def ask(
|
| 81 |
+
cls,
|
| 82 |
+
prompt: TextType = "",
|
| 83 |
+
*,
|
| 84 |
+
console: Optional[Console] = None,
|
| 85 |
+
password: bool = False,
|
| 86 |
+
choices: Optional[List[str]] = None,
|
| 87 |
+
case_sensitive: bool = True,
|
| 88 |
+
show_default: bool = True,
|
| 89 |
+
show_choices: bool = True,
|
| 90 |
+
default: DefaultType,
|
| 91 |
+
stream: Optional[TextIO] = None,
|
| 92 |
+
) -> Union[DefaultType, PromptType]:
|
| 93 |
+
...
|
| 94 |
+
|
| 95 |
+
@classmethod
|
| 96 |
+
@overload
|
| 97 |
+
def ask(
|
| 98 |
+
cls,
|
| 99 |
+
prompt: TextType = "",
|
| 100 |
+
*,
|
| 101 |
+
console: Optional[Console] = None,
|
| 102 |
+
password: bool = False,
|
| 103 |
+
choices: Optional[List[str]] = None,
|
| 104 |
+
case_sensitive: bool = True,
|
| 105 |
+
show_default: bool = True,
|
| 106 |
+
show_choices: bool = True,
|
| 107 |
+
stream: Optional[TextIO] = None,
|
| 108 |
+
) -> PromptType:
|
| 109 |
+
...
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def ask(
|
| 113 |
+
cls,
|
| 114 |
+
prompt: TextType = "",
|
| 115 |
+
*,
|
| 116 |
+
console: Optional[Console] = None,
|
| 117 |
+
password: bool = False,
|
| 118 |
+
choices: Optional[List[str]] = None,
|
| 119 |
+
case_sensitive: bool = True,
|
| 120 |
+
show_default: bool = True,
|
| 121 |
+
show_choices: bool = True,
|
| 122 |
+
default: Any = ...,
|
| 123 |
+
stream: Optional[TextIO] = None,
|
| 124 |
+
) -> Any:
|
| 125 |
+
"""Shortcut to construct and run a prompt loop and return the result.
|
| 126 |
+
|
| 127 |
+
Example:
|
| 128 |
+
>>> filename = Prompt.ask("Enter a filename")
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
prompt (TextType, optional): Prompt text. Defaults to "".
|
| 132 |
+
console (Console, optional): A Console instance or None to use global console. Defaults to None.
|
| 133 |
+
password (bool, optional): Enable password input. Defaults to False.
|
| 134 |
+
choices (List[str], optional): A list of valid choices. Defaults to None.
|
| 135 |
+
case_sensitive (bool, optional): Matching of choices should be case-sensitive. Defaults to True.
|
| 136 |
+
show_default (bool, optional): Show default in prompt. Defaults to True.
|
| 137 |
+
show_choices (bool, optional): Show choices in prompt. Defaults to True.
|
| 138 |
+
stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None.
|
| 139 |
+
"""
|
| 140 |
+
_prompt = cls(
|
| 141 |
+
prompt,
|
| 142 |
+
console=console,
|
| 143 |
+
password=password,
|
| 144 |
+
choices=choices,
|
| 145 |
+
case_sensitive=case_sensitive,
|
| 146 |
+
show_default=show_default,
|
| 147 |
+
show_choices=show_choices,
|
| 148 |
+
)
|
| 149 |
+
return _prompt(default=default, stream=stream)
|
| 150 |
+
|
| 151 |
+
def render_default(self, default: DefaultType) -> Text:
|
| 152 |
+
"""Turn the supplied default in to a Text instance.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
default (DefaultType): Default value.
|
| 156 |
+
|
| 157 |
+
Returns:
|
| 158 |
+
Text: Text containing rendering of default value.
|
| 159 |
+
"""
|
| 160 |
+
return Text(f"({default})", "prompt.default")
|
| 161 |
+
|
| 162 |
+
def make_prompt(self, default: DefaultType) -> Text:
|
| 163 |
+
"""Make prompt text.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
default (DefaultType): Default value.
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
Text: Text to display in prompt.
|
| 170 |
+
"""
|
| 171 |
+
prompt = self.prompt.copy()
|
| 172 |
+
prompt.end = ""
|
| 173 |
+
|
| 174 |
+
if self.show_choices and self.choices:
|
| 175 |
+
_choices = "/".join(self.choices)
|
| 176 |
+
choices = f"[{_choices}]"
|
| 177 |
+
prompt.append(" ")
|
| 178 |
+
prompt.append(choices, "prompt.choices")
|
| 179 |
+
|
| 180 |
+
if (
|
| 181 |
+
default != ...
|
| 182 |
+
and self.show_default
|
| 183 |
+
and isinstance(default, (str, self.response_type))
|
| 184 |
+
):
|
| 185 |
+
prompt.append(" ")
|
| 186 |
+
_default = self.render_default(default)
|
| 187 |
+
prompt.append(_default)
|
| 188 |
+
|
| 189 |
+
prompt.append(self.prompt_suffix)
|
| 190 |
+
|
| 191 |
+
return prompt
|
| 192 |
+
|
| 193 |
+
@classmethod
|
| 194 |
+
def get_input(
|
| 195 |
+
cls,
|
| 196 |
+
console: Console,
|
| 197 |
+
prompt: TextType,
|
| 198 |
+
password: bool,
|
| 199 |
+
stream: Optional[TextIO] = None,
|
| 200 |
+
) -> str:
|
| 201 |
+
"""Get input from user.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
console (Console): Console instance.
|
| 205 |
+
prompt (TextType): Prompt text.
|
| 206 |
+
password (bool): Enable password entry.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
str: String from user.
|
| 210 |
+
"""
|
| 211 |
+
return console.input(prompt, password=password, stream=stream)
|
| 212 |
+
|
| 213 |
+
def check_choice(self, value: str) -> bool:
|
| 214 |
+
"""Check value is in the list of valid choices.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
value (str): Value entered by user.
|
| 218 |
+
|
| 219 |
+
Returns:
|
| 220 |
+
bool: True if choice was valid, otherwise False.
|
| 221 |
+
"""
|
| 222 |
+
assert self.choices is not None
|
| 223 |
+
if self.case_sensitive:
|
| 224 |
+
return value.strip() in self.choices
|
| 225 |
+
return value.strip().lower() in [choice.lower() for choice in self.choices]
|
| 226 |
+
|
| 227 |
+
def process_response(self, value: str) -> PromptType:
|
| 228 |
+
"""Process response from user, convert to prompt type.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
value (str): String typed by user.
|
| 232 |
+
|
| 233 |
+
Raises:
|
| 234 |
+
InvalidResponse: If ``value`` is invalid.
|
| 235 |
+
|
| 236 |
+
Returns:
|
| 237 |
+
PromptType: The value to be returned from ask method.
|
| 238 |
+
"""
|
| 239 |
+
value = value.strip()
|
| 240 |
+
try:
|
| 241 |
+
return_value: PromptType = self.response_type(value)
|
| 242 |
+
except ValueError:
|
| 243 |
+
raise InvalidResponse(self.validate_error_message)
|
| 244 |
+
|
| 245 |
+
if self.choices is not None:
|
| 246 |
+
if not self.check_choice(value):
|
| 247 |
+
raise InvalidResponse(self.illegal_choice_message)
|
| 248 |
+
|
| 249 |
+
if not self.case_sensitive:
|
| 250 |
+
# return the original choice, not the lower case version
|
| 251 |
+
return_value = self.response_type(
|
| 252 |
+
self.choices[
|
| 253 |
+
[choice.lower() for choice in self.choices].index(value.lower())
|
| 254 |
+
]
|
| 255 |
+
)
|
| 256 |
+
return return_value
|
| 257 |
+
|
| 258 |
+
def on_validate_error(self, value: str, error: InvalidResponse) -> None:
|
| 259 |
+
"""Called to handle validation error.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
value (str): String entered by user.
|
| 263 |
+
error (InvalidResponse): Exception instance the initiated the error.
|
| 264 |
+
"""
|
| 265 |
+
self.console.print(error, markup=True)
|
| 266 |
+
|
| 267 |
+
def pre_prompt(self) -> None:
|
| 268 |
+
"""Hook to display something before the prompt."""
|
| 269 |
+
|
| 270 |
+
@overload
|
| 271 |
+
def __call__(self, *, stream: Optional[TextIO] = None) -> PromptType:
|
| 272 |
+
...
|
| 273 |
+
|
| 274 |
+
@overload
|
| 275 |
+
def __call__(
|
| 276 |
+
self, *, default: DefaultType, stream: Optional[TextIO] = None
|
| 277 |
+
) -> Union[PromptType, DefaultType]:
|
| 278 |
+
...
|
| 279 |
+
|
| 280 |
+
def __call__(self, *, default: Any = ..., stream: Optional[TextIO] = None) -> Any:
|
| 281 |
+
"""Run the prompt loop.
|
| 282 |
+
|
| 283 |
+
Args:
|
| 284 |
+
default (Any, optional): Optional default value.
|
| 285 |
+
|
| 286 |
+
Returns:
|
| 287 |
+
PromptType: Processed value.
|
| 288 |
+
"""
|
| 289 |
+
while True:
|
| 290 |
+
self.pre_prompt()
|
| 291 |
+
prompt = self.make_prompt(default)
|
| 292 |
+
value = self.get_input(self.console, prompt, self.password, stream=stream)
|
| 293 |
+
if value == "" and default != ...:
|
| 294 |
+
return default
|
| 295 |
+
try:
|
| 296 |
+
return_value = self.process_response(value)
|
| 297 |
+
except InvalidResponse as error:
|
| 298 |
+
self.on_validate_error(value, error)
|
| 299 |
+
continue
|
| 300 |
+
else:
|
| 301 |
+
return return_value
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class Prompt(PromptBase[str]):
|
| 305 |
+
"""A prompt that returns a str.
|
| 306 |
+
|
| 307 |
+
Example:
|
| 308 |
+
>>> name = Prompt.ask("Enter your name")
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
"""
|
| 312 |
+
|
| 313 |
+
response_type = str
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class IntPrompt(PromptBase[int]):
|
| 317 |
+
"""A prompt that returns an integer.
|
| 318 |
+
|
| 319 |
+
Example:
|
| 320 |
+
>>> burrito_count = IntPrompt.ask("How many burritos do you want to order")
|
| 321 |
+
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
response_type = int
|
| 325 |
+
validate_error_message = "[prompt.invalid]Please enter a valid integer number"
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class FloatPrompt(PromptBase[float]):
|
| 329 |
+
"""A prompt that returns a float.
|
| 330 |
+
|
| 331 |
+
Example:
|
| 332 |
+
>>> temperature = FloatPrompt.ask("Enter desired temperature")
|
| 333 |
+
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
response_type = float
|
| 337 |
+
validate_error_message = "[prompt.invalid]Please enter a number"
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class Confirm(PromptBase[bool]):
|
| 341 |
+
"""A yes / no confirmation prompt.
|
| 342 |
+
|
| 343 |
+
Example:
|
| 344 |
+
>>> if Confirm.ask("Continue"):
|
| 345 |
+
run_job()
|
| 346 |
+
|
| 347 |
+
"""
|
| 348 |
+
|
| 349 |
+
response_type = bool
|
| 350 |
+
validate_error_message = "[prompt.invalid]Please enter Y or N"
|
| 351 |
+
choices: List[str] = ["y", "n"]
|
| 352 |
+
|
| 353 |
+
def render_default(self, default: DefaultType) -> Text:
|
| 354 |
+
"""Render the default as (y) or (n) rather than True/False."""
|
| 355 |
+
yes, no = self.choices
|
| 356 |
+
return Text(f"({yes})" if default else f"({no})", style="prompt.default")
|
| 357 |
+
|
| 358 |
+
def process_response(self, value: str) -> bool:
|
| 359 |
+
"""Convert choices to a bool."""
|
| 360 |
+
value = value.strip().lower()
|
| 361 |
+
if value not in self.choices:
|
| 362 |
+
raise InvalidResponse(self.validate_error_message)
|
| 363 |
+
return value == self.choices[0]
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
if __name__ == "__main__": # pragma: no cover
|
| 367 |
+
from rich import print
|
| 368 |
+
|
| 369 |
+
if Confirm.ask("Run [i]prompt[/i] tests?", default=True):
|
| 370 |
+
while True:
|
| 371 |
+
result = IntPrompt.ask(
|
| 372 |
+
":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5
|
| 373 |
+
)
|
| 374 |
+
if result >= 1 and result <= 10:
|
| 375 |
+
break
|
| 376 |
+
print(":pile_of_poo: [prompt.invalid]Number must be between 1 and 10")
|
| 377 |
+
print(f"number={result}")
|
| 378 |
+
|
| 379 |
+
while True:
|
| 380 |
+
password = Prompt.ask(
|
| 381 |
+
"Please enter a password [cyan](must be at least 5 characters)",
|
| 382 |
+
password=True,
|
| 383 |
+
)
|
| 384 |
+
if len(password) >= 5:
|
| 385 |
+
break
|
| 386 |
+
print("[prompt.invalid]password too short")
|
| 387 |
+
print(f"password={password!r}")
|
| 388 |
+
|
| 389 |
+
fruit = Prompt.ask("Enter a fruit", choices=["apple", "orange", "pear"])
|
| 390 |
+
print(f"fruit={fruit!r}")
|
| 391 |
+
|
| 392 |
+
doggie = Prompt.ask(
|
| 393 |
+
"What's the best Dog? (Case INSENSITIVE)",
|
| 394 |
+
choices=["Border Terrier", "Collie", "Labradoodle"],
|
| 395 |
+
case_sensitive=False,
|
| 396 |
+
)
|
| 397 |
+
print(f"doggie={doggie!r}")
|
| 398 |
+
|
| 399 |
+
else:
|
| 400 |
+
print("[b]OK :loudly_crying_face:")
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/protocol.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, cast, Set, TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
if TYPE_CHECKING:
|
| 4 |
+
from rich.console import RenderableType
|
| 5 |
+
|
| 6 |
+
_GIBBERISH = """aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf"""
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def is_renderable(check_object: Any) -> bool:
|
| 10 |
+
"""Check if an object may be rendered by Rich."""
|
| 11 |
+
return (
|
| 12 |
+
isinstance(check_object, str)
|
| 13 |
+
or hasattr(check_object, "__rich__")
|
| 14 |
+
or hasattr(check_object, "__rich_console__")
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def rich_cast(renderable: object) -> "RenderableType":
|
| 19 |
+
"""Cast an object to a renderable by calling __rich__ if present.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
renderable (object): A potentially renderable object
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
object: The result of recursively calling __rich__.
|
| 26 |
+
"""
|
| 27 |
+
from rich.console import RenderableType
|
| 28 |
+
|
| 29 |
+
rich_visited_set: Set[type] = set() # Prevent potential infinite loop
|
| 30 |
+
while hasattr(renderable, "__rich__") and not isinstance(renderable, type):
|
| 31 |
+
# Detect object which claim to have all the attributes
|
| 32 |
+
if hasattr(renderable, _GIBBERISH):
|
| 33 |
+
return repr(renderable)
|
| 34 |
+
cast_method = getattr(renderable, "__rich__")
|
| 35 |
+
renderable = cast_method()
|
| 36 |
+
renderable_type = type(renderable)
|
| 37 |
+
if renderable_type in rich_visited_set:
|
| 38 |
+
break
|
| 39 |
+
rich_visited_set.add(renderable_type)
|
| 40 |
+
|
| 41 |
+
return cast(RenderableType, renderable)
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/py.typed
ADDED
|
File without changes
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/region.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import NamedTuple
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Region(N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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import partial
|
| 2 |
+
from typing import (
|
| 3 |
+
Any,
|
| 4 |
+
Callable,
|
| 5 |
+
Iterable,
|
| 6 |
+
List,
|
| 7 |
+
Optional,
|
| 8 |
+
Tuple,
|
| 9 |
+
Type,
|
| 10 |
+
TypeVar,
|
| 11 |
+
Union,
|
| 12 |
+
overload,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
T = TypeVar("T")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
Result = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]
|
| 19 |
+
RichReprResult = Result
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ReprError(Exception):
|
| 23 |
+
"""An error occurred when attempting to build a repr."""
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@overload
|
| 27 |
+
def auto(cls: Optional[Type[T]]) -> Type[T]:
|
| 28 |
+
...
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@overload
|
| 32 |
+
def auto(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:
|
| 33 |
+
...
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def auto(
|
| 37 |
+
cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None
|
| 38 |
+
) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
|
| 39 |
+
"""Class decorator to create __repr__ from __rich_repr__"""
|
| 40 |
+
|
| 41 |
+
def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]:
|
| 42 |
+
def auto_repr(self: T) -> str:
|
| 43 |
+
"""Create repr string from __rich_repr__"""
|
| 44 |
+
repr_str: List[str] = []
|
| 45 |
+
append = repr_str.append
|
| 46 |
+
|
| 47 |
+
angular: bool = getattr(self.__rich_repr__, "angular", False) # type: ignore[attr-defined]
|
| 48 |
+
for arg in self.__rich_repr__(): # type: ignore[attr-defined]
|
| 49 |
+
if isinstance(arg, tuple):
|
| 50 |
+
if len(arg) == 1:
|
| 51 |
+
append(repr(arg[0]))
|
| 52 |
+
else:
|
| 53 |
+
key, value, *default = arg
|
| 54 |
+
if key is None:
|
| 55 |
+
append(repr(value))
|
| 56 |
+
else:
|
| 57 |
+
if default and default[0] == value:
|
| 58 |
+
continue
|
| 59 |
+
append(f"{key}={value!r}")
|
| 60 |
+
else:
|
| 61 |
+
append(repr(arg))
|
| 62 |
+
if angular:
|
| 63 |
+
return f"<{self.__class__.__name__} {' '.join(repr_str)}>"
|
| 64 |
+
else:
|
| 65 |
+
return f"{self.__class__.__name__}({', '.join(repr_str)})"
|
| 66 |
+
|
| 67 |
+
def auto_rich_repr(self: Type[T]) -> Result:
|
| 68 |
+
"""Auto generate __rich_rep__ from signature of __init__"""
|
| 69 |
+
try:
|
| 70 |
+
import inspect
|
| 71 |
+
|
| 72 |
+
signature = inspect.signature(self.__init__)
|
| 73 |
+
for name, param in signature.parameters.items():
|
| 74 |
+
if param.kind == param.POSITIONAL_ONLY:
|
| 75 |
+
yield getattr(self, name)
|
| 76 |
+
elif param.kind in (
|
| 77 |
+
param.POSITIONAL_OR_KEYWORD,
|
| 78 |
+
param.KEYWORD_ONLY,
|
| 79 |
+
):
|
| 80 |
+
if param.default is param.empty:
|
| 81 |
+
yield getattr(self, param.name)
|
| 82 |
+
else:
|
| 83 |
+
yield param.name, getattr(self, param.name), param.default
|
| 84 |
+
except Exception as error:
|
| 85 |
+
raise ReprError(
|
| 86 |
+
f"Failed to auto generate __rich_repr__; {error}"
|
| 87 |
+
) from None
|
| 88 |
+
|
| 89 |
+
if not hasattr(cls, "__rich_repr__"):
|
| 90 |
+
auto_rich_repr.__doc__ = "Build a rich repr"
|
| 91 |
+
cls.__rich_repr__ = auto_rich_repr # type: ignore[attr-defined]
|
| 92 |
+
|
| 93 |
+
auto_repr.__doc__ = "Return repr(self)"
|
| 94 |
+
cls.__repr__ = auto_repr # type: ignore[assignment]
|
| 95 |
+
if angular is not None:
|
| 96 |
+
cls.__rich_repr__.angular = angular # type: ignore[attr-defined]
|
| 97 |
+
return cls
|
| 98 |
+
|
| 99 |
+
if cls is None:
|
| 100 |
+
return partial(do_replace, angular=angular)
|
| 101 |
+
else:
|
| 102 |
+
return do_replace(cls, angular=angular)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@overload
|
| 106 |
+
def rich_repr(cls: Optional[Type[T]]) -> Type[T]:
|
| 107 |
+
...
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@overload
|
| 111 |
+
def rich_repr(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:
|
| 112 |
+
...
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def rich_repr(
|
| 116 |
+
cls: Optional[Type[T]] = None, *, angular: bool = False
|
| 117 |
+
) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
|
| 118 |
+
if cls is None:
|
| 119 |
+
return auto(angular=angular)
|
| 120 |
+
else:
|
| 121 |
+
return auto(cls)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
|
| 126 |
+
@auto
|
| 127 |
+
class Foo:
|
| 128 |
+
def __rich_repr__(self) -> Result:
|
| 129 |
+
yield "foo"
|
| 130 |
+
yield "bar", {"shopping": ["eggs", "ham", "pineapple"]}
|
| 131 |
+
yield "buy", "hand sanitizer"
|
| 132 |
+
|
| 133 |
+
foo = Foo()
|
| 134 |
+
from rich.console import Console
|
| 135 |
+
|
| 136 |
+
console = Console()
|
| 137 |
+
|
| 138 |
+
console.rule("Standard repr")
|
| 139 |
+
console.print(foo)
|
| 140 |
+
|
| 141 |
+
console.print(foo, width=60)
|
| 142 |
+
console.print(foo, width=30)
|
| 143 |
+
|
| 144 |
+
console.rule("Angular repr")
|
| 145 |
+
Foo.__rich_repr__.angular = True # type: ignore[attr-defined]
|
| 146 |
+
|
| 147 |
+
console.print(foo)
|
| 148 |
+
|
| 149 |
+
console.print(foo, width=60)
|
| 150 |
+
console.print(foo, width=30)
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/rule.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Union
|
| 2 |
+
|
| 3 |
+
from .align import AlignMethod
|
| 4 |
+
from .cells import cell_len, set_cell_size
|
| 5 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 6 |
+
from .jupyter import JupyterMixin
|
| 7 |
+
from .measure import Measurement
|
| 8 |
+
from .style import Style
|
| 9 |
+
from .text import Text
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Rule(JupyterMixin):
|
| 13 |
+
"""A console renderable to draw a horizontal rule (line).
|
| 14 |
+
|
| 15 |
+
Args:
|
| 16 |
+
title (Union[str, Text], optional): Text to render in the rule. Defaults to "".
|
| 17 |
+
characters (str, optional): Character(s) used to draw the line. Defaults to "─".
|
| 18 |
+
style (StyleType, optional): Style of Rule. Defaults to "rule.line".
|
| 19 |
+
end (str, optional): Character at end of Rule. defaults to "\\\\n"
|
| 20 |
+
align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
title: Union[str, Text] = "",
|
| 26 |
+
*,
|
| 27 |
+
characters: str = "─",
|
| 28 |
+
style: Union[str, Style] = "rule.line",
|
| 29 |
+
end: str = "\n",
|
| 30 |
+
align: AlignMethod = "center",
|
| 31 |
+
) -> None:
|
| 32 |
+
if cell_len(characters) < 1:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
"'characters' argument must have a cell width of at least 1"
|
| 35 |
+
)
|
| 36 |
+
if align not in ("left", "center", "right"):
|
| 37 |
+
raise ValueError(
|
| 38 |
+
f'invalid value for align, expected "left", "center", "right" (not {align!r})'
|
| 39 |
+
)
|
| 40 |
+
self.title = title
|
| 41 |
+
self.characters = characters
|
| 42 |
+
self.style = style
|
| 43 |
+
self.end = end
|
| 44 |
+
self.align = align
|
| 45 |
+
|
| 46 |
+
def __repr__(self) -> str:
|
| 47 |
+
return f"Rule({self.title!r}, {self.characters!r})"
|
| 48 |
+
|
| 49 |
+
def __rich_console__(
|
| 50 |
+
self, console: Console, options: ConsoleOptions
|
| 51 |
+
) -> RenderResult:
|
| 52 |
+
width = options.max_width
|
| 53 |
+
|
| 54 |
+
characters = (
|
| 55 |
+
"-"
|
| 56 |
+
if (options.ascii_only and not self.characters.isascii())
|
| 57 |
+
else self.characters
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
chars_len = cell_len(characters)
|
| 61 |
+
if not self.title:
|
| 62 |
+
yield self._rule_line(chars_len, width)
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
if isinstance(self.title, Text):
|
| 66 |
+
title_text = self.title
|
| 67 |
+
else:
|
| 68 |
+
title_text = console.render_str(self.title, style="rule.text")
|
| 69 |
+
|
| 70 |
+
title_text.plain = title_text.plain.replace("\n", " ")
|
| 71 |
+
title_text.expand_tabs()
|
| 72 |
+
|
| 73 |
+
required_space = 4 if self.align == "center" else 2
|
| 74 |
+
truncate_width = max(0, width - required_space)
|
| 75 |
+
if not truncate_width:
|
| 76 |
+
yield self._rule_line(chars_len, width)
|
| 77 |
+
return
|
| 78 |
+
|
| 79 |
+
rule_text = Text(end=self.end)
|
| 80 |
+
if self.align == "center":
|
| 81 |
+
title_text.truncate(truncate_width, overflow="ellipsis")
|
| 82 |
+
side_width = (width - cell_len(title_text.plain)) // 2
|
| 83 |
+
left = Text(characters * (side_width // chars_len + 1))
|
| 84 |
+
left.truncate(side_width - 1)
|
| 85 |
+
right_length = width - cell_len(left.plain) - cell_len(title_text.plain)
|
| 86 |
+
right = Text(characters * (side_width // chars_len + 1))
|
| 87 |
+
right.truncate(right_length)
|
| 88 |
+
rule_text.append(left.plain + " ", self.style)
|
| 89 |
+
rule_text.append(title_text)
|
| 90 |
+
rule_text.append(" " + right.plain, self.style)
|
| 91 |
+
elif self.align == "left":
|
| 92 |
+
title_text.truncate(truncate_width, overflow="ellipsis")
|
| 93 |
+
rule_text.append(title_text)
|
| 94 |
+
rule_text.append(" ")
|
| 95 |
+
rule_text.append(characters * (width - rule_text.cell_len), self.style)
|
| 96 |
+
elif self.align == "right":
|
| 97 |
+
title_text.truncate(truncate_width, overflow="ellipsis")
|
| 98 |
+
rule_text.append(characters * (width - title_text.cell_len - 1), self.style)
|
| 99 |
+
rule_text.append(" ")
|
| 100 |
+
rule_text.append(title_text)
|
| 101 |
+
|
| 102 |
+
rule_text.plain = set_cell_size(rule_text.plain, width)
|
| 103 |
+
yield rule_text
|
| 104 |
+
|
| 105 |
+
def _rule_line(self, chars_len: int, width: int) -> Text:
|
| 106 |
+
rule_text = Text(self.characters * ((width // chars_len) + 1), self.style)
|
| 107 |
+
rule_text.truncate(width)
|
| 108 |
+
rule_text.plain = set_cell_size(rule_text.plain, width)
|
| 109 |
+
return rule_text
|
| 110 |
+
|
| 111 |
+
def __rich_measure__(
|
| 112 |
+
self, console: Console, options: ConsoleOptions
|
| 113 |
+
) -> Measurement:
|
| 114 |
+
return Measurement(1, 1)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__": # pragma: no cover
|
| 118 |
+
import sys
|
| 119 |
+
|
| 120 |
+
from rich.console import Console
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
text = sys.argv[1]
|
| 124 |
+
except IndexError:
|
| 125 |
+
text = "Hello, World"
|
| 126 |
+
console = Console()
|
| 127 |
+
console.print(Rule(title=text))
|
| 128 |
+
|
| 129 |
+
console = Console()
|
| 130 |
+
console.print(Rule("foo"), width=4)
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/scope.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Mapping
|
| 2 |
+
from typing import TYPE_CHECKING, Any, Optional, Tuple
|
| 3 |
+
|
| 4 |
+
from .highlighter import ReprHighlighter
|
| 5 |
+
from .panel import Panel
|
| 6 |
+
from .pretty import Pretty
|
| 7 |
+
from .table import Table
|
| 8 |
+
from .text import Text, TextType
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from .console import ConsoleRenderable, OverflowMethod
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def render_scope(
|
| 15 |
+
scope: "Mapping[str, Any]",
|
| 16 |
+
*,
|
| 17 |
+
title: Optional[TextType] = None,
|
| 18 |
+
sort_keys: bool = True,
|
| 19 |
+
indent_guides: bool = False,
|
| 20 |
+
max_length: Optional[int] = None,
|
| 21 |
+
max_string: Optional[int] = None,
|
| 22 |
+
max_depth: Optional[int] = None,
|
| 23 |
+
overflow: Optional["OverflowMethod"] = None,
|
| 24 |
+
) -> "ConsoleRenderable":
|
| 25 |
+
"""Render python variables in a given scope.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
scope (Mapping): A mapping containing variable names and values.
|
| 29 |
+
title (str, optional): Optional title. Defaults to None.
|
| 30 |
+
sort_keys (bool, optional): Enable sorting of items. Defaults to True.
|
| 31 |
+
indent_guides (bool, optional): Enable indentation guides. Defaults to False.
|
| 32 |
+
max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
| 33 |
+
Defaults to None.
|
| 34 |
+
max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
|
| 35 |
+
max_depth (int, optional): Maximum depths of locals before truncating, or None to disable. Defaults to None.
|
| 36 |
+
overflow (OverflowMethod, optional): How to handle overflowing locals, or None to disable. Defaults to None.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
ConsoleRenderable: A renderable object.
|
| 40 |
+
"""
|
| 41 |
+
highlighter = ReprHighlighter()
|
| 42 |
+
items_table = Table.grid(padding=(0, 1), expand=False)
|
| 43 |
+
items_table.add_column(justify="right")
|
| 44 |
+
|
| 45 |
+
def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
|
| 46 |
+
"""Sort special variables first, then alphabetically."""
|
| 47 |
+
key, _ = item
|
| 48 |
+
return (not key.startswith("__"), key.lower())
|
| 49 |
+
|
| 50 |
+
items = sorted(scope.items(), key=sort_items) if sort_keys else scope.items()
|
| 51 |
+
for key, value in items:
|
| 52 |
+
key_text = Text.assemble(
|
| 53 |
+
(key, "scope.key.special" if key.startswith("__") else "scope.key"),
|
| 54 |
+
(" =", "scope.equals"),
|
| 55 |
+
)
|
| 56 |
+
items_table.add_row(
|
| 57 |
+
key_text,
|
| 58 |
+
Pretty(
|
| 59 |
+
value,
|
| 60 |
+
highlighter=highlighter,
|
| 61 |
+
indent_guides=indent_guides,
|
| 62 |
+
max_length=max_length,
|
| 63 |
+
max_string=max_string,
|
| 64 |
+
max_depth=max_depth,
|
| 65 |
+
overflow=overflow,
|
| 66 |
+
),
|
| 67 |
+
)
|
| 68 |
+
return Panel.fit(
|
| 69 |
+
items_table,
|
| 70 |
+
title=title,
|
| 71 |
+
border_style="scope.border",
|
| 72 |
+
padding=(0, 1),
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__": # pragma: no cover
|
| 77 |
+
from rich import print
|
| 78 |
+
|
| 79 |
+
print()
|
| 80 |
+
|
| 81 |
+
def test(foo: float, bar: float) -> None:
|
| 82 |
+
list_of_things = [1, 2, 3, None, 4, True, False, "Hello World"]
|
| 83 |
+
dict_of_things = {
|
| 84 |
+
"version": "1.1",
|
| 85 |
+
"method": "confirmFruitPurchase",
|
| 86 |
+
"params": [["apple", "orange", "mangoes", "pomelo"], 1.123],
|
| 87 |
+
"id": "194521489",
|
| 88 |
+
}
|
| 89 |
+
print(render_scope(locals(), title="[i]locals", sort_keys=False))
|
| 90 |
+
|
| 91 |
+
test(20.3423, 3.1427)
|
| 92 |
+
print()
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/screen.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from .segment import Segment
|
| 4 |
+
from .style import StyleType
|
| 5 |
+
from ._loop import loop_last
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from .console import (
|
| 10 |
+
Console,
|
| 11 |
+
ConsoleOptions,
|
| 12 |
+
RenderResult,
|
| 13 |
+
RenderableType,
|
| 14 |
+
Group,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Screen:
|
| 19 |
+
"""A renderable that fills the terminal screen and crops excess.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
renderable (RenderableType): Child renderable.
|
| 23 |
+
style (StyleType, optional): Optional background style. Defaults to None.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
renderable: "RenderableType"
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
*renderables: "RenderableType",
|
| 31 |
+
style: Optional[StyleType] = None,
|
| 32 |
+
application_mode: bool = False,
|
| 33 |
+
) -> None:
|
| 34 |
+
from rich.console import Group
|
| 35 |
+
|
| 36 |
+
self.renderable = Group(*renderables)
|
| 37 |
+
self.style = style
|
| 38 |
+
self.application_mode = application_mode
|
| 39 |
+
|
| 40 |
+
def __rich_console__(
|
| 41 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 42 |
+
) -> "RenderResult":
|
| 43 |
+
width, height = options.size
|
| 44 |
+
style = console.get_style(self.style) if self.style else None
|
| 45 |
+
render_options = options.update(width=width, height=height)
|
| 46 |
+
lines = console.render_lines(
|
| 47 |
+
self.renderable or "", render_options, style=style, pad=True
|
| 48 |
+
)
|
| 49 |
+
lines = Segment.set_shape(lines, width, height, style=style)
|
| 50 |
+
new_line = Segment("\n\r") if self.application_mode else Segment.line()
|
| 51 |
+
for last, line in loop_last(lines):
|
| 52 |
+
yield from line
|
| 53 |
+
if not last:
|
| 54 |
+
yield new_line
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/segment.py
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import IntEnum
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from itertools import filterfalse
|
| 4 |
+
from operator import attrgetter
|
| 5 |
+
from typing import (
|
| 6 |
+
TYPE_CHECKING,
|
| 7 |
+
Dict,
|
| 8 |
+
Iterable,
|
| 9 |
+
List,
|
| 10 |
+
NamedTuple,
|
| 11 |
+
Optional,
|
| 12 |
+
Sequence,
|
| 13 |
+
Tuple,
|
| 14 |
+
Type,
|
| 15 |
+
Union,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from .cells import (
|
| 19 |
+
_is_single_cell_widths,
|
| 20 |
+
cached_cell_len,
|
| 21 |
+
cell_len,
|
| 22 |
+
get_character_cell_size,
|
| 23 |
+
set_cell_size,
|
| 24 |
+
)
|
| 25 |
+
from .repr import Result, rich_repr
|
| 26 |
+
from .style import Style
|
| 27 |
+
|
| 28 |
+
if TYPE_CHECKING:
|
| 29 |
+
from .console import Console, ConsoleOptions, RenderResult
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ControlType(IntEnum):
|
| 33 |
+
"""Non-printable control codes which typically translate to ANSI codes."""
|
| 34 |
+
|
| 35 |
+
BELL = 1
|
| 36 |
+
CARRIAGE_RETURN = 2
|
| 37 |
+
HOME = 3
|
| 38 |
+
CLEAR = 4
|
| 39 |
+
SHOW_CURSOR = 5
|
| 40 |
+
HIDE_CURSOR = 6
|
| 41 |
+
ENABLE_ALT_SCREEN = 7
|
| 42 |
+
DISABLE_ALT_SCREEN = 8
|
| 43 |
+
CURSOR_UP = 9
|
| 44 |
+
CURSOR_DOWN = 10
|
| 45 |
+
CURSOR_FORWARD = 11
|
| 46 |
+
CURSOR_BACKWARD = 12
|
| 47 |
+
CURSOR_MOVE_TO_COLUMN = 13
|
| 48 |
+
CURSOR_MOVE_TO = 14
|
| 49 |
+
ERASE_IN_LINE = 15
|
| 50 |
+
SET_WINDOW_TITLE = 16
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
ControlCode = Union[
|
| 54 |
+
Tuple[ControlType],
|
| 55 |
+
Tuple[ControlType, Union[int, str]],
|
| 56 |
+
Tuple[ControlType, int, int],
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@rich_repr()
|
| 61 |
+
class Segment(NamedTuple):
|
| 62 |
+
"""A piece of text with associated style. Segments are produced by the Console render process and
|
| 63 |
+
are ultimately converted in to strings to be written to the terminal.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
text (str): A piece of text.
|
| 67 |
+
style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.
|
| 68 |
+
control (Tuple[ControlCode], optional): Optional sequence of control codes.
|
| 69 |
+
|
| 70 |
+
Attributes:
|
| 71 |
+
cell_length (int): The cell length of this Segment.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
text: str
|
| 75 |
+
style: Optional[Style] = None
|
| 76 |
+
control: Optional[Sequence[ControlCode]] = None
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def cell_length(self) -> int:
|
| 80 |
+
"""The number of terminal cells required to display self.text.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
int: A number of cells.
|
| 84 |
+
"""
|
| 85 |
+
text, _style, control = self
|
| 86 |
+
return 0 if control else cell_len(text)
|
| 87 |
+
|
| 88 |
+
def __rich_repr__(self) -> Result:
|
| 89 |
+
yield self.text
|
| 90 |
+
if self.control is None:
|
| 91 |
+
if self.style is not None:
|
| 92 |
+
yield self.style
|
| 93 |
+
else:
|
| 94 |
+
yield self.style
|
| 95 |
+
yield self.control
|
| 96 |
+
|
| 97 |
+
def __bool__(self) -> bool:
|
| 98 |
+
"""Check if the segment contains text."""
|
| 99 |
+
return bool(self.text)
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def is_control(self) -> bool:
|
| 103 |
+
"""Check if the segment contains control codes."""
|
| 104 |
+
return self.control is not None
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
@lru_cache(1024 * 16)
|
| 108 |
+
def _split_cells(cls, segment: "Segment", cut: int) -> Tuple["Segment", "Segment"]:
|
| 109 |
+
"""Split a segment in to two at a given cell position.
|
| 110 |
+
|
| 111 |
+
Note that splitting a double-width character, may result in that character turning
|
| 112 |
+
into two spaces.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
segment (Segment): A segment to split.
|
| 116 |
+
cut (int): A cell position to cut on.
|
| 117 |
+
|
| 118 |
+
Returns:
|
| 119 |
+
A tuple of two segments.
|
| 120 |
+
"""
|
| 121 |
+
text, style, control = segment
|
| 122 |
+
_Segment = Segment
|
| 123 |
+
cell_length = segment.cell_length
|
| 124 |
+
if cut >= cell_length:
|
| 125 |
+
return segment, _Segment("", style, control)
|
| 126 |
+
|
| 127 |
+
cell_size = get_character_cell_size
|
| 128 |
+
|
| 129 |
+
pos = int((cut / cell_length) * len(text))
|
| 130 |
+
|
| 131 |
+
while True:
|
| 132 |
+
before = text[:pos]
|
| 133 |
+
cell_pos = cell_len(before)
|
| 134 |
+
out_by = cell_pos - cut
|
| 135 |
+
if not out_by:
|
| 136 |
+
return (
|
| 137 |
+
_Segment(before, style, control),
|
| 138 |
+
_Segment(text[pos:], style, control),
|
| 139 |
+
)
|
| 140 |
+
if out_by == -1 and cell_size(text[pos]) == 2:
|
| 141 |
+
return (
|
| 142 |
+
_Segment(text[:pos] + " ", style, control),
|
| 143 |
+
_Segment(" " + text[pos + 1 :], style, control),
|
| 144 |
+
)
|
| 145 |
+
if out_by == +1 and cell_size(text[pos - 1]) == 2:
|
| 146 |
+
return (
|
| 147 |
+
_Segment(text[: pos - 1] + " ", style, control),
|
| 148 |
+
_Segment(" " + text[pos:], style, control),
|
| 149 |
+
)
|
| 150 |
+
if cell_pos < cut:
|
| 151 |
+
pos += 1
|
| 152 |
+
else:
|
| 153 |
+
pos -= 1
|
| 154 |
+
|
| 155 |
+
def split_cells(self, cut: int) -> Tuple["Segment", "Segment"]:
|
| 156 |
+
"""Split segment in to two segments at the specified column.
|
| 157 |
+
|
| 158 |
+
If the cut point falls in the middle of a 2-cell wide character then it is replaced
|
| 159 |
+
by two spaces, to preserve the display width of the parent segment.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
cut (int): Offset within the segment to cut.
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
Tuple[Segment, Segment]: Two segments.
|
| 166 |
+
"""
|
| 167 |
+
text, style, control = self
|
| 168 |
+
assert cut >= 0
|
| 169 |
+
|
| 170 |
+
if _is_single_cell_widths(text):
|
| 171 |
+
# Fast path with all 1 cell characters
|
| 172 |
+
if cut >= len(text):
|
| 173 |
+
return self, Segment("", style, control)
|
| 174 |
+
return (
|
| 175 |
+
Segment(text[:cut], style, control),
|
| 176 |
+
Segment(text[cut:], style, control),
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
return self._split_cells(self, cut)
|
| 180 |
+
|
| 181 |
+
@classmethod
|
| 182 |
+
def line(cls) -> "Segment":
|
| 183 |
+
"""Make a new line segment."""
|
| 184 |
+
return cls("\n")
|
| 185 |
+
|
| 186 |
+
@classmethod
|
| 187 |
+
def apply_style(
|
| 188 |
+
cls,
|
| 189 |
+
segments: Iterable["Segment"],
|
| 190 |
+
style: Optional[Style] = None,
|
| 191 |
+
post_style: Optional[Style] = None,
|
| 192 |
+
) -> Iterable["Segment"]:
|
| 193 |
+
"""Apply style(s) to an iterable of segments.
|
| 194 |
+
|
| 195 |
+
Returns an iterable of segments where the style is replaced by ``style + segment.style + post_style``.
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
segments (Iterable[Segment]): Segments to process.
|
| 199 |
+
style (Style, optional): Base style. Defaults to None.
|
| 200 |
+
post_style (Style, optional): Style to apply on top of segment style. Defaults to None.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
Iterable[Segments]: A new iterable of segments (possibly the same iterable).
|
| 204 |
+
"""
|
| 205 |
+
result_segments = segments
|
| 206 |
+
if style:
|
| 207 |
+
apply = style.__add__
|
| 208 |
+
result_segments = (
|
| 209 |
+
cls(text, None if control else apply(_style), control)
|
| 210 |
+
for text, _style, control in result_segments
|
| 211 |
+
)
|
| 212 |
+
if post_style:
|
| 213 |
+
result_segments = (
|
| 214 |
+
cls(
|
| 215 |
+
text,
|
| 216 |
+
(
|
| 217 |
+
None
|
| 218 |
+
if control
|
| 219 |
+
else (_style + post_style if _style else post_style)
|
| 220 |
+
),
|
| 221 |
+
control,
|
| 222 |
+
)
|
| 223 |
+
for text, _style, control in result_segments
|
| 224 |
+
)
|
| 225 |
+
return result_segments
|
| 226 |
+
|
| 227 |
+
@classmethod
|
| 228 |
+
def filter_control(
|
| 229 |
+
cls, segments: Iterable["Segment"], is_control: bool = False
|
| 230 |
+
) -> Iterable["Segment"]:
|
| 231 |
+
"""Filter segments by ``is_control`` attribute.
|
| 232 |
+
|
| 233 |
+
Args:
|
| 234 |
+
segments (Iterable[Segment]): An iterable of Segment instances.
|
| 235 |
+
is_control (bool, optional): is_control flag to match in search.
|
| 236 |
+
|
| 237 |
+
Returns:
|
| 238 |
+
Iterable[Segment]: And iterable of Segment instances.
|
| 239 |
+
|
| 240 |
+
"""
|
| 241 |
+
if is_control:
|
| 242 |
+
return filter(attrgetter("control"), segments)
|
| 243 |
+
else:
|
| 244 |
+
return filterfalse(attrgetter("control"), segments)
|
| 245 |
+
|
| 246 |
+
@classmethod
|
| 247 |
+
def split_lines(cls, segments: Iterable["Segment"]) -> Iterable[List["Segment"]]:
|
| 248 |
+
"""Split a sequence of segments in to a list of lines.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
segments (Iterable[Segment]): Segments potentially containing line feeds.
|
| 252 |
+
|
| 253 |
+
Yields:
|
| 254 |
+
Iterable[List[Segment]]: Iterable of segment lists, one per line.
|
| 255 |
+
"""
|
| 256 |
+
line: List[Segment] = []
|
| 257 |
+
append = line.append
|
| 258 |
+
|
| 259 |
+
for segment in segments:
|
| 260 |
+
if "\n" in segment.text and not segment.control:
|
| 261 |
+
text, style, _ = segment
|
| 262 |
+
while text:
|
| 263 |
+
_text, new_line, text = text.partition("\n")
|
| 264 |
+
if _text:
|
| 265 |
+
append(cls(_text, style))
|
| 266 |
+
if new_line:
|
| 267 |
+
yield line
|
| 268 |
+
line = []
|
| 269 |
+
append = line.append
|
| 270 |
+
else:
|
| 271 |
+
append(segment)
|
| 272 |
+
if line:
|
| 273 |
+
yield line
|
| 274 |
+
|
| 275 |
+
@classmethod
|
| 276 |
+
def split_lines_terminator(
|
| 277 |
+
cls, segments: Iterable["Segment"]
|
| 278 |
+
) -> Iterable[Tuple[List["Segment"], bool]]:
|
| 279 |
+
"""Split a sequence of segments in to a list of lines and a boolean to indicate if there was a new line.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
segments (Iterable[Segment]): Segments potentially containing line feeds.
|
| 283 |
+
|
| 284 |
+
Yields:
|
| 285 |
+
Iterable[List[Segment]]: Iterable of segment lists, one per line.
|
| 286 |
+
"""
|
| 287 |
+
line: List[Segment] = []
|
| 288 |
+
append = line.append
|
| 289 |
+
|
| 290 |
+
for segment in segments:
|
| 291 |
+
if "\n" in segment.text and not segment.control:
|
| 292 |
+
text, style, _ = segment
|
| 293 |
+
while text:
|
| 294 |
+
_text, new_line, text = text.partition("\n")
|
| 295 |
+
if _text:
|
| 296 |
+
append(cls(_text, style))
|
| 297 |
+
if new_line:
|
| 298 |
+
yield (line, True)
|
| 299 |
+
line = []
|
| 300 |
+
append = line.append
|
| 301 |
+
else:
|
| 302 |
+
append(segment)
|
| 303 |
+
if line:
|
| 304 |
+
yield (line, False)
|
| 305 |
+
|
| 306 |
+
@classmethod
|
| 307 |
+
def split_and_crop_lines(
|
| 308 |
+
cls,
|
| 309 |
+
segments: Iterable["Segment"],
|
| 310 |
+
length: int,
|
| 311 |
+
style: Optional[Style] = None,
|
| 312 |
+
pad: bool = True,
|
| 313 |
+
include_new_lines: bool = True,
|
| 314 |
+
) -> Iterable[List["Segment"]]:
|
| 315 |
+
"""Split segments in to lines, and crop lines greater than a given length.
|
| 316 |
+
|
| 317 |
+
Args:
|
| 318 |
+
segments (Iterable[Segment]): An iterable of segments, probably
|
| 319 |
+
generated from console.render.
|
| 320 |
+
length (int): Desired line length.
|
| 321 |
+
style (Style, optional): Style to use for any padding.
|
| 322 |
+
pad (bool): Enable padding of lines that are less than `length`.
|
| 323 |
+
|
| 324 |
+
Returns:
|
| 325 |
+
Iterable[List[Segment]]: An iterable of lines of segments.
|
| 326 |
+
"""
|
| 327 |
+
line: List[Segment] = []
|
| 328 |
+
append = line.append
|
| 329 |
+
|
| 330 |
+
adjust_line_length = cls.adjust_line_length
|
| 331 |
+
new_line_segment = cls("\n")
|
| 332 |
+
|
| 333 |
+
for segment in segments:
|
| 334 |
+
if "\n" in segment.text and not segment.control:
|
| 335 |
+
text, segment_style, _ = segment
|
| 336 |
+
while text:
|
| 337 |
+
_text, new_line, text = text.partition("\n")
|
| 338 |
+
if _text:
|
| 339 |
+
append(cls(_text, segment_style))
|
| 340 |
+
if new_line:
|
| 341 |
+
cropped_line = adjust_line_length(
|
| 342 |
+
line, length, style=style, pad=pad
|
| 343 |
+
)
|
| 344 |
+
if include_new_lines:
|
| 345 |
+
cropped_line.append(new_line_segment)
|
| 346 |
+
yield cropped_line
|
| 347 |
+
line.clear()
|
| 348 |
+
else:
|
| 349 |
+
append(segment)
|
| 350 |
+
if line:
|
| 351 |
+
yield adjust_line_length(line, length, style=style, pad=pad)
|
| 352 |
+
|
| 353 |
+
@classmethod
|
| 354 |
+
def adjust_line_length(
|
| 355 |
+
cls,
|
| 356 |
+
line: List["Segment"],
|
| 357 |
+
length: int,
|
| 358 |
+
style: Optional[Style] = None,
|
| 359 |
+
pad: bool = True,
|
| 360 |
+
) -> List["Segment"]:
|
| 361 |
+
"""Adjust a line to a given width (cropping or padding as required).
|
| 362 |
+
|
| 363 |
+
Args:
|
| 364 |
+
segments (Iterable[Segment]): A list of segments in a single line.
|
| 365 |
+
length (int): The desired width of the line.
|
| 366 |
+
style (Style, optional): The style of padding if used (space on the end). Defaults to None.
|
| 367 |
+
pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.
|
| 368 |
+
|
| 369 |
+
Returns:
|
| 370 |
+
List[Segment]: A line of segments with the desired length.
|
| 371 |
+
"""
|
| 372 |
+
line_length = sum(segment.cell_length for segment in line)
|
| 373 |
+
new_line: List[Segment]
|
| 374 |
+
|
| 375 |
+
if line_length < length:
|
| 376 |
+
if pad:
|
| 377 |
+
new_line = line + [cls(" " * (length - line_length), style)]
|
| 378 |
+
else:
|
| 379 |
+
new_line = line[:]
|
| 380 |
+
elif line_length > length:
|
| 381 |
+
new_line = []
|
| 382 |
+
append = new_line.append
|
| 383 |
+
line_length = 0
|
| 384 |
+
for segment in line:
|
| 385 |
+
segment_length = segment.cell_length
|
| 386 |
+
if line_length + segment_length < length or segment.control:
|
| 387 |
+
append(segment)
|
| 388 |
+
line_length += segment_length
|
| 389 |
+
else:
|
| 390 |
+
text, segment_style, _ = segment
|
| 391 |
+
text = set_cell_size(text, length - line_length)
|
| 392 |
+
append(cls(text, segment_style))
|
| 393 |
+
break
|
| 394 |
+
else:
|
| 395 |
+
new_line = line[:]
|
| 396 |
+
return new_line
|
| 397 |
+
|
| 398 |
+
@classmethod
|
| 399 |
+
def get_line_length(cls, line: List["Segment"]) -> int:
|
| 400 |
+
"""Get the length of list of segments.
|
| 401 |
+
|
| 402 |
+
Args:
|
| 403 |
+
line (List[Segment]): A line encoded as a list of Segments (assumes no '\\\\n' characters),
|
| 404 |
+
|
| 405 |
+
Returns:
|
| 406 |
+
int: The length of the line.
|
| 407 |
+
"""
|
| 408 |
+
_cell_len = cell_len
|
| 409 |
+
return sum(_cell_len(text) for text, style, control in line if not control)
|
| 410 |
+
|
| 411 |
+
@classmethod
|
| 412 |
+
def get_shape(cls, lines: List[List["Segment"]]) -> Tuple[int, int]:
|
| 413 |
+
"""Get the shape (enclosing rectangle) of a list of lines.
|
| 414 |
+
|
| 415 |
+
Args:
|
| 416 |
+
lines (List[List[Segment]]): A list of lines (no '\\\\n' characters).
|
| 417 |
+
|
| 418 |
+
Returns:
|
| 419 |
+
Tuple[int, int]: Width and height in characters.
|
| 420 |
+
"""
|
| 421 |
+
get_line_length = cls.get_line_length
|
| 422 |
+
max_width = max(get_line_length(line) for line in lines) if lines else 0
|
| 423 |
+
return (max_width, len(lines))
|
| 424 |
+
|
| 425 |
+
@classmethod
|
| 426 |
+
def set_shape(
|
| 427 |
+
cls,
|
| 428 |
+
lines: List[List["Segment"]],
|
| 429 |
+
width: int,
|
| 430 |
+
height: Optional[int] = None,
|
| 431 |
+
style: Optional[Style] = None,
|
| 432 |
+
new_lines: bool = False,
|
| 433 |
+
) -> List[List["Segment"]]:
|
| 434 |
+
"""Set the shape of a list of lines (enclosing rectangle).
|
| 435 |
+
|
| 436 |
+
Args:
|
| 437 |
+
lines (List[List[Segment]]): A list of lines.
|
| 438 |
+
width (int): Desired width.
|
| 439 |
+
height (int, optional): Desired height or None for no change.
|
| 440 |
+
style (Style, optional): Style of any padding added.
|
| 441 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 442 |
+
|
| 443 |
+
Returns:
|
| 444 |
+
List[List[Segment]]: New list of lines.
|
| 445 |
+
"""
|
| 446 |
+
_height = height or len(lines)
|
| 447 |
+
|
| 448 |
+
blank = (
|
| 449 |
+
[cls(" " * width + "\n", style)] if new_lines else [cls(" " * width, style)]
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
adjust_line_length = cls.adjust_line_length
|
| 453 |
+
shaped_lines = lines[:_height]
|
| 454 |
+
shaped_lines[:] = [
|
| 455 |
+
adjust_line_length(line, width, style=style) for line in lines
|
| 456 |
+
]
|
| 457 |
+
if len(shaped_lines) < _height:
|
| 458 |
+
shaped_lines.extend([blank] * (_height - len(shaped_lines)))
|
| 459 |
+
return shaped_lines
|
| 460 |
+
|
| 461 |
+
@classmethod
|
| 462 |
+
def align_top(
|
| 463 |
+
cls: Type["Segment"],
|
| 464 |
+
lines: List[List["Segment"]],
|
| 465 |
+
width: int,
|
| 466 |
+
height: int,
|
| 467 |
+
style: Style,
|
| 468 |
+
new_lines: bool = False,
|
| 469 |
+
) -> List[List["Segment"]]:
|
| 470 |
+
"""Aligns lines to top (adds extra lines to bottom as required).
|
| 471 |
+
|
| 472 |
+
Args:
|
| 473 |
+
lines (List[List[Segment]]): A list of lines.
|
| 474 |
+
width (int): Desired width.
|
| 475 |
+
height (int, optional): Desired height or None for no change.
|
| 476 |
+
style (Style): Style of any padding added.
|
| 477 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 478 |
+
|
| 479 |
+
Returns:
|
| 480 |
+
List[List[Segment]]: New list of lines.
|
| 481 |
+
"""
|
| 482 |
+
extra_lines = height - len(lines)
|
| 483 |
+
if not extra_lines:
|
| 484 |
+
return lines[:]
|
| 485 |
+
lines = lines[:height]
|
| 486 |
+
blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
|
| 487 |
+
lines = lines + [[blank]] * extra_lines
|
| 488 |
+
return lines
|
| 489 |
+
|
| 490 |
+
@classmethod
|
| 491 |
+
def align_bottom(
|
| 492 |
+
cls: Type["Segment"],
|
| 493 |
+
lines: List[List["Segment"]],
|
| 494 |
+
width: int,
|
| 495 |
+
height: int,
|
| 496 |
+
style: Style,
|
| 497 |
+
new_lines: bool = False,
|
| 498 |
+
) -> List[List["Segment"]]:
|
| 499 |
+
"""Aligns render to bottom (adds extra lines above as required).
|
| 500 |
+
|
| 501 |
+
Args:
|
| 502 |
+
lines (List[List[Segment]]): A list of lines.
|
| 503 |
+
width (int): Desired width.
|
| 504 |
+
height (int, optional): Desired height or None for no change.
|
| 505 |
+
style (Style): Style of any padding added. Defaults to None.
|
| 506 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 507 |
+
|
| 508 |
+
Returns:
|
| 509 |
+
List[List[Segment]]: New list of lines.
|
| 510 |
+
"""
|
| 511 |
+
extra_lines = height - len(lines)
|
| 512 |
+
if not extra_lines:
|
| 513 |
+
return lines[:]
|
| 514 |
+
lines = lines[:height]
|
| 515 |
+
blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
|
| 516 |
+
lines = [[blank]] * extra_lines + lines
|
| 517 |
+
return lines
|
| 518 |
+
|
| 519 |
+
@classmethod
|
| 520 |
+
def align_middle(
|
| 521 |
+
cls: Type["Segment"],
|
| 522 |
+
lines: List[List["Segment"]],
|
| 523 |
+
width: int,
|
| 524 |
+
height: int,
|
| 525 |
+
style: Style,
|
| 526 |
+
new_lines: bool = False,
|
| 527 |
+
) -> List[List["Segment"]]:
|
| 528 |
+
"""Aligns lines to middle (adds extra lines to above and below as required).
|
| 529 |
+
|
| 530 |
+
Args:
|
| 531 |
+
lines (List[List[Segment]]): A list of lines.
|
| 532 |
+
width (int): Desired width.
|
| 533 |
+
height (int, optional): Desired height or None for no change.
|
| 534 |
+
style (Style): Style of any padding added.
|
| 535 |
+
new_lines (bool, optional): Padded lines should include "\n". Defaults to False.
|
| 536 |
+
|
| 537 |
+
Returns:
|
| 538 |
+
List[List[Segment]]: New list of lines.
|
| 539 |
+
"""
|
| 540 |
+
extra_lines = height - len(lines)
|
| 541 |
+
if not extra_lines:
|
| 542 |
+
return lines[:]
|
| 543 |
+
lines = lines[:height]
|
| 544 |
+
blank = cls(" " * width + "\n", style) if new_lines else cls(" " * width, style)
|
| 545 |
+
top_lines = extra_lines // 2
|
| 546 |
+
bottom_lines = extra_lines - top_lines
|
| 547 |
+
lines = [[blank]] * top_lines + lines + [[blank]] * bottom_lines
|
| 548 |
+
return lines
|
| 549 |
+
|
| 550 |
+
@classmethod
|
| 551 |
+
def simplify(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 552 |
+
"""Simplify an iterable of segments by combining contiguous segments with the same style.
|
| 553 |
+
|
| 554 |
+
Args:
|
| 555 |
+
segments (Iterable[Segment]): An iterable of segments.
|
| 556 |
+
|
| 557 |
+
Returns:
|
| 558 |
+
Iterable[Segment]: A possibly smaller iterable of segments that will render the same way.
|
| 559 |
+
"""
|
| 560 |
+
iter_segments = iter(segments)
|
| 561 |
+
try:
|
| 562 |
+
last_segment = next(iter_segments)
|
| 563 |
+
except StopIteration:
|
| 564 |
+
return
|
| 565 |
+
|
| 566 |
+
_Segment = Segment
|
| 567 |
+
for segment in iter_segments:
|
| 568 |
+
if last_segment.style == segment.style and not segment.control:
|
| 569 |
+
last_segment = _Segment(
|
| 570 |
+
last_segment.text + segment.text, last_segment.style
|
| 571 |
+
)
|
| 572 |
+
else:
|
| 573 |
+
yield last_segment
|
| 574 |
+
last_segment = segment
|
| 575 |
+
yield last_segment
|
| 576 |
+
|
| 577 |
+
@classmethod
|
| 578 |
+
def strip_links(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 579 |
+
"""Remove all links from an iterable of styles.
|
| 580 |
+
|
| 581 |
+
Args:
|
| 582 |
+
segments (Iterable[Segment]): An iterable segments.
|
| 583 |
+
|
| 584 |
+
Yields:
|
| 585 |
+
Segment: Segments with link removed.
|
| 586 |
+
"""
|
| 587 |
+
for segment in segments:
|
| 588 |
+
if segment.control or segment.style is None:
|
| 589 |
+
yield segment
|
| 590 |
+
else:
|
| 591 |
+
text, style, _control = segment
|
| 592 |
+
yield cls(text, style.update_link(None) if style else None)
|
| 593 |
+
|
| 594 |
+
@classmethod
|
| 595 |
+
def strip_styles(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 596 |
+
"""Remove all styles from an iterable of segments.
|
| 597 |
+
|
| 598 |
+
Args:
|
| 599 |
+
segments (Iterable[Segment]): An iterable segments.
|
| 600 |
+
|
| 601 |
+
Yields:
|
| 602 |
+
Segment: Segments with styles replace with None
|
| 603 |
+
"""
|
| 604 |
+
for text, _style, control in segments:
|
| 605 |
+
yield cls(text, None, control)
|
| 606 |
+
|
| 607 |
+
@classmethod
|
| 608 |
+
def remove_color(cls, segments: Iterable["Segment"]) -> Iterable["Segment"]:
|
| 609 |
+
"""Remove all color from an iterable of segments.
|
| 610 |
+
|
| 611 |
+
Args:
|
| 612 |
+
segments (Iterable[Segment]): An iterable segments.
|
| 613 |
+
|
| 614 |
+
Yields:
|
| 615 |
+
Segment: Segments with colorless style.
|
| 616 |
+
"""
|
| 617 |
+
|
| 618 |
+
cache: Dict[Style, Style] = {}
|
| 619 |
+
for text, style, control in segments:
|
| 620 |
+
if style:
|
| 621 |
+
colorless_style = cache.get(style)
|
| 622 |
+
if colorless_style is None:
|
| 623 |
+
colorless_style = style.without_color
|
| 624 |
+
cache[style] = colorless_style
|
| 625 |
+
yield cls(text, colorless_style, control)
|
| 626 |
+
else:
|
| 627 |
+
yield cls(text, None, control)
|
| 628 |
+
|
| 629 |
+
@classmethod
|
| 630 |
+
def divide(
|
| 631 |
+
cls, segments: Iterable["Segment"], cuts: Iterable[int]
|
| 632 |
+
) -> Iterable[List["Segment"]]:
|
| 633 |
+
"""Divides an iterable of segments in to portions.
|
| 634 |
+
|
| 635 |
+
Args:
|
| 636 |
+
cuts (Iterable[int]): Cell positions where to divide.
|
| 637 |
+
|
| 638 |
+
Yields:
|
| 639 |
+
[Iterable[List[Segment]]]: An iterable of Segments in List.
|
| 640 |
+
"""
|
| 641 |
+
split_segments: List["Segment"] = []
|
| 642 |
+
add_segment = split_segments.append
|
| 643 |
+
|
| 644 |
+
iter_cuts = iter(cuts)
|
| 645 |
+
|
| 646 |
+
while True:
|
| 647 |
+
cut = next(iter_cuts, -1)
|
| 648 |
+
if cut == -1:
|
| 649 |
+
return
|
| 650 |
+
if cut != 0:
|
| 651 |
+
break
|
| 652 |
+
yield []
|
| 653 |
+
pos = 0
|
| 654 |
+
|
| 655 |
+
segments_clear = split_segments.clear
|
| 656 |
+
segments_copy = split_segments.copy
|
| 657 |
+
|
| 658 |
+
_cell_len = cached_cell_len
|
| 659 |
+
for segment in segments:
|
| 660 |
+
text, _style, control = segment
|
| 661 |
+
while text:
|
| 662 |
+
end_pos = pos if control else pos + _cell_len(text)
|
| 663 |
+
if end_pos < cut:
|
| 664 |
+
add_segment(segment)
|
| 665 |
+
pos = end_pos
|
| 666 |
+
break
|
| 667 |
+
|
| 668 |
+
if end_pos == cut:
|
| 669 |
+
add_segment(segment)
|
| 670 |
+
yield segments_copy()
|
| 671 |
+
segments_clear()
|
| 672 |
+
pos = end_pos
|
| 673 |
+
|
| 674 |
+
cut = next(iter_cuts, -1)
|
| 675 |
+
if cut == -1:
|
| 676 |
+
if split_segments:
|
| 677 |
+
yield segments_copy()
|
| 678 |
+
return
|
| 679 |
+
|
| 680 |
+
break
|
| 681 |
+
|
| 682 |
+
else:
|
| 683 |
+
before, segment = segment.split_cells(cut - pos)
|
| 684 |
+
text, _style, control = segment
|
| 685 |
+
add_segment(before)
|
| 686 |
+
yield segments_copy()
|
| 687 |
+
segments_clear()
|
| 688 |
+
pos = cut
|
| 689 |
+
|
| 690 |
+
cut = next(iter_cuts, -1)
|
| 691 |
+
if cut == -1:
|
| 692 |
+
if split_segments:
|
| 693 |
+
yield segments_copy()
|
| 694 |
+
return
|
| 695 |
+
|
| 696 |
+
yield segments_copy()
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
class Segments:
|
| 700 |
+
"""A simple renderable to render an iterable of segments. This class may be useful if
|
| 701 |
+
you want to print segments outside of a __rich_console__ method.
|
| 702 |
+
|
| 703 |
+
Args:
|
| 704 |
+
segments (Iterable[Segment]): An iterable of segments.
|
| 705 |
+
new_lines (bool, optional): Add new lines between segments. Defaults to False.
|
| 706 |
+
"""
|
| 707 |
+
|
| 708 |
+
def __init__(self, segments: Iterable[Segment], new_lines: bool = False) -> None:
|
| 709 |
+
self.segments = list(segments)
|
| 710 |
+
self.new_lines = new_lines
|
| 711 |
+
|
| 712 |
+
def __rich_console__(
|
| 713 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 714 |
+
) -> "RenderResult":
|
| 715 |
+
if self.new_lines:
|
| 716 |
+
line = Segment.line()
|
| 717 |
+
for segment in self.segments:
|
| 718 |
+
yield segment
|
| 719 |
+
yield line
|
| 720 |
+
else:
|
| 721 |
+
yield from self.segments
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
class SegmentLines:
|
| 725 |
+
def __init__(self, lines: Iterable[List[Segment]], new_lines: bool = False) -> None:
|
| 726 |
+
"""A simple renderable containing a number of lines of segments. May be used as an intermediate
|
| 727 |
+
in rendering process.
|
| 728 |
+
|
| 729 |
+
Args:
|
| 730 |
+
lines (Iterable[List[Segment]]): Lists of segments forming lines.
|
| 731 |
+
new_lines (bool, optional): Insert new lines after each line. Defaults to False.
|
| 732 |
+
"""
|
| 733 |
+
self.lines = list(lines)
|
| 734 |
+
self.new_lines = new_lines
|
| 735 |
+
|
| 736 |
+
def __rich_console__(
|
| 737 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 738 |
+
) -> "RenderResult":
|
| 739 |
+
if self.new_lines:
|
| 740 |
+
new_line = Segment.line()
|
| 741 |
+
for line in self.lines:
|
| 742 |
+
yield from line
|
| 743 |
+
yield new_line
|
| 744 |
+
else:
|
| 745 |
+
for line in self.lines:
|
| 746 |
+
yield from line
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
if __name__ == "__main__": # pragma: no cover
|
| 750 |
+
from rich.console import Console
|
| 751 |
+
from rich.syntax import Syntax
|
| 752 |
+
from rich.text import Text
|
| 753 |
+
|
| 754 |
+
code = """from rich.console import Console
|
| 755 |
+
console = Console()
|
| 756 |
+
text = Text.from_markup("Hello, [bold magenta]World[/]!")
|
| 757 |
+
console.print(text)"""
|
| 758 |
+
|
| 759 |
+
text = Text.from_markup("Hello, [bold magenta]World[/]!")
|
| 760 |
+
|
| 761 |
+
console = Console()
|
| 762 |
+
|
| 763 |
+
console.rule("rich.Segment")
|
| 764 |
+
console.print(
|
| 765 |
+
"A Segment is the last step in the Rich render process before generating text with ANSI codes."
|
| 766 |
+
)
|
| 767 |
+
console.print("\nConsider the following code:\n")
|
| 768 |
+
console.print(Syntax(code, "python", line_numbers=True))
|
| 769 |
+
console.print()
|
| 770 |
+
console.print(
|
| 771 |
+
"When you call [b]print()[/b], Rich [i]renders[/i] the object in to the following:\n"
|
| 772 |
+
)
|
| 773 |
+
fragments = list(console.render(text))
|
| 774 |
+
console.print(fragments)
|
| 775 |
+
console.print()
|
| 776 |
+
console.print("The Segments are then processed to produce the following output:\n")
|
| 777 |
+
console.print(text)
|
| 778 |
+
console.print(
|
| 779 |
+
"\nYou will only need to know this if you are implementing your own Rich renderables."
|
| 780 |
+
)
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/spinner.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING, List, Optional, Union, cast
|
| 2 |
+
|
| 3 |
+
from ._spinners import SPINNERS
|
| 4 |
+
from .measure import Measurement
|
| 5 |
+
from .table import Table
|
| 6 |
+
from .text import Text
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
| 10 |
+
from .style import StyleType
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Spinner:
|
| 14 |
+
"""A spinner animation.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
name (str): Name of spinner (run python -m rich.spinner).
|
| 18 |
+
text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "".
|
| 19 |
+
style (StyleType, optional): Style for spinner animation. Defaults to None.
|
| 20 |
+
speed (float, optional): Speed factor for animation. Defaults to 1.0.
|
| 21 |
+
|
| 22 |
+
Raises:
|
| 23 |
+
KeyError: If name isn't one of the supported spinner animations.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
name: str,
|
| 29 |
+
text: "RenderableType" = "",
|
| 30 |
+
*,
|
| 31 |
+
style: Optional["StyleType"] = None,
|
| 32 |
+
speed: float = 1.0,
|
| 33 |
+
) -> None:
|
| 34 |
+
try:
|
| 35 |
+
spinner = SPINNERS[name]
|
| 36 |
+
except KeyError:
|
| 37 |
+
raise KeyError(f"no spinner called {name!r}")
|
| 38 |
+
self.text: "Union[RenderableType, Text]" = (
|
| 39 |
+
Text.from_markup(text) if isinstance(text, str) else text
|
| 40 |
+
)
|
| 41 |
+
self.name = name
|
| 42 |
+
self.frames = cast(List[str], spinner["frames"])[:]
|
| 43 |
+
self.interval = cast(float, spinner["interval"])
|
| 44 |
+
self.start_time: Optional[float] = None
|
| 45 |
+
self.style = style
|
| 46 |
+
self.speed = speed
|
| 47 |
+
self.frame_no_offset: float = 0.0
|
| 48 |
+
self._update_speed = 0.0
|
| 49 |
+
|
| 50 |
+
def __rich_console__(
|
| 51 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 52 |
+
) -> "RenderResult":
|
| 53 |
+
yield self.render(console.get_time())
|
| 54 |
+
|
| 55 |
+
def __rich_measure__(
|
| 56 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 57 |
+
) -> Measurement:
|
| 58 |
+
text = self.render(0)
|
| 59 |
+
return Measurement.get(console, options, text)
|
| 60 |
+
|
| 61 |
+
def render(self, time: float) -> "RenderableType":
|
| 62 |
+
"""Render the spinner for a given time.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
time (float): Time in seconds.
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
RenderableType: A renderable containing animation frame.
|
| 69 |
+
"""
|
| 70 |
+
if self.start_time is None:
|
| 71 |
+
self.start_time = time
|
| 72 |
+
|
| 73 |
+
frame_no = ((time - self.start_time) * self.speed) / (
|
| 74 |
+
self.interval / 1000.0
|
| 75 |
+
) + self.frame_no_offset
|
| 76 |
+
frame = Text(
|
| 77 |
+
self.frames[int(frame_no) % len(self.frames)], style=self.style or ""
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
if self._update_speed:
|
| 81 |
+
self.frame_no_offset = frame_no
|
| 82 |
+
self.start_time = time
|
| 83 |
+
self.speed = self._update_speed
|
| 84 |
+
self._update_speed = 0.0
|
| 85 |
+
|
| 86 |
+
if not self.text:
|
| 87 |
+
return frame
|
| 88 |
+
elif isinstance(self.text, (str, Text)):
|
| 89 |
+
return Text.assemble(frame, " ", self.text)
|
| 90 |
+
else:
|
| 91 |
+
table = Table.grid(padding=1)
|
| 92 |
+
table.add_row(frame, self.text)
|
| 93 |
+
return table
|
| 94 |
+
|
| 95 |
+
def update(
|
| 96 |
+
self,
|
| 97 |
+
*,
|
| 98 |
+
text: "RenderableType" = "",
|
| 99 |
+
style: Optional["StyleType"] = None,
|
| 100 |
+
speed: Optional[float] = None,
|
| 101 |
+
) -> None:
|
| 102 |
+
"""Updates attributes of a spinner after it has been started.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "".
|
| 106 |
+
style (StyleType, optional): Style for spinner animation. Defaults to None.
|
| 107 |
+
speed (float, optional): Speed factor for animation. Defaults to None.
|
| 108 |
+
"""
|
| 109 |
+
if text:
|
| 110 |
+
self.text = Text.from_markup(text) if isinstance(text, str) else text
|
| 111 |
+
if style:
|
| 112 |
+
self.style = style
|
| 113 |
+
if speed:
|
| 114 |
+
self._update_speed = speed
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__": # pragma: no cover
|
| 118 |
+
from time import sleep
|
| 119 |
+
|
| 120 |
+
from .console import Group
|
| 121 |
+
from .live import Live
|
| 122 |
+
|
| 123 |
+
all_spinners = Group(
|
| 124 |
+
*[
|
| 125 |
+
Spinner(spinner_name, text=Text(repr(spinner_name), style="green"))
|
| 126 |
+
for spinner_name in sorted(SPINNERS.keys())
|
| 127 |
+
]
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
with Live(all_spinners, refresh_per_second=20) as live:
|
| 131 |
+
while True:
|
| 132 |
+
sleep(0.1)
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/status.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import TracebackType
|
| 2 |
+
from typing import Optional, Type
|
| 3 |
+
|
| 4 |
+
from .console import Console, RenderableType
|
| 5 |
+
from .jupyter import JupyterMixin
|
| 6 |
+
from .live import Live
|
| 7 |
+
from .spinner import Spinner
|
| 8 |
+
from .style import StyleType
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Status(JupyterMixin):
|
| 12 |
+
"""Displays a status indicator with a 'spinner' animation.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
status (RenderableType): A status renderable (str or Text typically).
|
| 16 |
+
console (Console, optional): Console instance to use, or None for global console. Defaults to None.
|
| 17 |
+
spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
|
| 18 |
+
spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
|
| 19 |
+
speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
|
| 20 |
+
refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
status: RenderableType,
|
| 26 |
+
*,
|
| 27 |
+
console: Optional[Console] = None,
|
| 28 |
+
spinner: str = "dots",
|
| 29 |
+
spinner_style: StyleType = "status.spinner",
|
| 30 |
+
speed: float = 1.0,
|
| 31 |
+
refresh_per_second: float = 12.5,
|
| 32 |
+
):
|
| 33 |
+
self.status = status
|
| 34 |
+
self.spinner_style = spinner_style
|
| 35 |
+
self.speed = speed
|
| 36 |
+
self._spinner = Spinner(spinner, text=status, style=spinner_style, speed=speed)
|
| 37 |
+
self._live = Live(
|
| 38 |
+
self.renderable,
|
| 39 |
+
console=console,
|
| 40 |
+
refresh_per_second=refresh_per_second,
|
| 41 |
+
transient=True,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def renderable(self) -> Spinner:
|
| 46 |
+
return self._spinner
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def console(self) -> "Console":
|
| 50 |
+
"""Get the Console used by the Status objects."""
|
| 51 |
+
return self._live.console
|
| 52 |
+
|
| 53 |
+
def update(
|
| 54 |
+
self,
|
| 55 |
+
status: Optional[RenderableType] = None,
|
| 56 |
+
*,
|
| 57 |
+
spinner: Optional[str] = None,
|
| 58 |
+
spinner_style: Optional[StyleType] = None,
|
| 59 |
+
speed: Optional[float] = None,
|
| 60 |
+
) -> None:
|
| 61 |
+
"""Update status.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
status (Optional[RenderableType], optional): New status renderable or None for no change. Defaults to None.
|
| 65 |
+
spinner (Optional[str], optional): New spinner or None for no change. Defaults to None.
|
| 66 |
+
spinner_style (Optional[StyleType], optional): New spinner style or None for no change. Defaults to None.
|
| 67 |
+
speed (Optional[float], optional): Speed factor for spinner animation or None for no change. Defaults to None.
|
| 68 |
+
"""
|
| 69 |
+
if status is not None:
|
| 70 |
+
self.status = status
|
| 71 |
+
if spinner_style is not None:
|
| 72 |
+
self.spinner_style = spinner_style
|
| 73 |
+
if speed is not None:
|
| 74 |
+
self.speed = speed
|
| 75 |
+
if spinner is not None:
|
| 76 |
+
self._spinner = Spinner(
|
| 77 |
+
spinner, text=self.status, style=self.spinner_style, speed=self.speed
|
| 78 |
+
)
|
| 79 |
+
self._live.update(self.renderable, refresh=True)
|
| 80 |
+
else:
|
| 81 |
+
self._spinner.update(
|
| 82 |
+
text=self.status, style=self.spinner_style, speed=self.speed
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def start(self) -> None:
|
| 86 |
+
"""Start the status animation."""
|
| 87 |
+
self._live.start()
|
| 88 |
+
|
| 89 |
+
def stop(self) -> None:
|
| 90 |
+
"""Stop the spinner animation."""
|
| 91 |
+
self._live.stop()
|
| 92 |
+
|
| 93 |
+
def __rich__(self) -> RenderableType:
|
| 94 |
+
return self.renderable
|
| 95 |
+
|
| 96 |
+
def __enter__(self) -> "Status":
|
| 97 |
+
self.start()
|
| 98 |
+
return self
|
| 99 |
+
|
| 100 |
+
def __exit__(
|
| 101 |
+
self,
|
| 102 |
+
exc_type: Optional[Type[BaseException]],
|
| 103 |
+
exc_val: Optional[BaseException],
|
| 104 |
+
exc_tb: Optional[TracebackType],
|
| 105 |
+
) -> None:
|
| 106 |
+
self.stop()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__": # pragma: no cover
|
| 110 |
+
from time import sleep
|
| 111 |
+
|
| 112 |
+
from .console import Console
|
| 113 |
+
|
| 114 |
+
console = Console()
|
| 115 |
+
with console.status("[magenta]Covid detector booting up") as status:
|
| 116 |
+
sleep(3)
|
| 117 |
+
console.log("Importing advanced AI")
|
| 118 |
+
sleep(3)
|
| 119 |
+
console.log("Advanced Covid AI Ready")
|
| 120 |
+
sleep(3)
|
| 121 |
+
status.update(status="[bold blue] Scanning for Covid", spinner="earth")
|
| 122 |
+
sleep(3)
|
| 123 |
+
console.log("Found 10,000,000,000 copies of Covid32.exe")
|
| 124 |
+
sleep(3)
|
| 125 |
+
status.update(
|
| 126 |
+
status="[bold red]Moving Covid32.exe to Trash",
|
| 127 |
+
spinner="bouncingBall",
|
| 128 |
+
spinner_style="yellow",
|
| 129 |
+
)
|
| 130 |
+
sleep(5)
|
| 131 |
+
console.print("[bold green]Covid deleted successfully")
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/style.py
ADDED
|
@@ -0,0 +1,796 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from functools import lru_cache
|
| 3 |
+
from itertools import count
|
| 4 |
+
from operator import attrgetter
|
| 5 |
+
from pickle import dumps, loads
|
| 6 |
+
from random import getrandbits
|
| 7 |
+
from typing import Any, Dict, Iterable, List, Optional, Type, Union, cast
|
| 8 |
+
|
| 9 |
+
from . import errors
|
| 10 |
+
from .color import Color, ColorParseError, ColorSystem, blend_rgb
|
| 11 |
+
from .repr import Result, rich_repr
|
| 12 |
+
from .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme
|
| 13 |
+
|
| 14 |
+
_hash_getter = attrgetter(
|
| 15 |
+
"_color", "_bgcolor", "_attributes", "_set_attributes", "_link", "_meta"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
# Style instances and style definitions are often interchangeable
|
| 19 |
+
StyleType = Union[str, "Style"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_id_generator = count(getrandbits(24))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class _Bit:
|
| 26 |
+
"""A descriptor to get/set a style attribute bit."""
|
| 27 |
+
|
| 28 |
+
__slots__ = ["bit"]
|
| 29 |
+
|
| 30 |
+
def __init__(self, bit_no: int) -> None:
|
| 31 |
+
self.bit = 1 << bit_no
|
| 32 |
+
|
| 33 |
+
def __get__(self, obj: "Style", objtype: Type["Style"]) -> Optional[bool]:
|
| 34 |
+
if obj._set_attributes & self.bit:
|
| 35 |
+
return obj._attributes & self.bit != 0
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@rich_repr
|
| 40 |
+
class Style:
|
| 41 |
+
"""A terminal style.
|
| 42 |
+
|
| 43 |
+
A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such
|
| 44 |
+
as bold, italic etc. The attributes have 3 states: they can either be on
|
| 45 |
+
(``True``), off (``False``), or not set (``None``).
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
color (Union[Color, str], optional): Color of terminal text. Defaults to None.
|
| 49 |
+
bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.
|
| 50 |
+
bold (bool, optional): Enable bold text. Defaults to None.
|
| 51 |
+
dim (bool, optional): Enable dim text. Defaults to None.
|
| 52 |
+
italic (bool, optional): Enable italic text. Defaults to None.
|
| 53 |
+
underline (bool, optional): Enable underlined text. Defaults to None.
|
| 54 |
+
blink (bool, optional): Enabled blinking text. Defaults to None.
|
| 55 |
+
blink2 (bool, optional): Enable fast blinking text. Defaults to None.
|
| 56 |
+
reverse (bool, optional): Enabled reverse text. Defaults to None.
|
| 57 |
+
conceal (bool, optional): Enable concealed text. Defaults to None.
|
| 58 |
+
strike (bool, optional): Enable strikethrough text. Defaults to None.
|
| 59 |
+
underline2 (bool, optional): Enable doubly underlined text. Defaults to None.
|
| 60 |
+
frame (bool, optional): Enable framed text. Defaults to None.
|
| 61 |
+
encircle (bool, optional): Enable encircled text. Defaults to None.
|
| 62 |
+
overline (bool, optional): Enable overlined text. Defaults to None.
|
| 63 |
+
link (str, link): Link URL. Defaults to None.
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
_color: Optional[Color]
|
| 68 |
+
_bgcolor: Optional[Color]
|
| 69 |
+
_attributes: int
|
| 70 |
+
_set_attributes: int
|
| 71 |
+
_hash: Optional[int]
|
| 72 |
+
_null: bool
|
| 73 |
+
_meta: Optional[bytes]
|
| 74 |
+
|
| 75 |
+
__slots__ = [
|
| 76 |
+
"_color",
|
| 77 |
+
"_bgcolor",
|
| 78 |
+
"_attributes",
|
| 79 |
+
"_set_attributes",
|
| 80 |
+
"_link",
|
| 81 |
+
"_link_id",
|
| 82 |
+
"_ansi",
|
| 83 |
+
"_style_definition",
|
| 84 |
+
"_hash",
|
| 85 |
+
"_null",
|
| 86 |
+
"_meta",
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
+
# maps bits on to SGR parameter
|
| 90 |
+
_style_map = {
|
| 91 |
+
0: "1",
|
| 92 |
+
1: "2",
|
| 93 |
+
2: "3",
|
| 94 |
+
3: "4",
|
| 95 |
+
4: "5",
|
| 96 |
+
5: "6",
|
| 97 |
+
6: "7",
|
| 98 |
+
7: "8",
|
| 99 |
+
8: "9",
|
| 100 |
+
9: "21",
|
| 101 |
+
10: "51",
|
| 102 |
+
11: "52",
|
| 103 |
+
12: "53",
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
STYLE_ATTRIBUTES = {
|
| 107 |
+
"dim": "dim",
|
| 108 |
+
"d": "dim",
|
| 109 |
+
"bold": "bold",
|
| 110 |
+
"b": "bold",
|
| 111 |
+
"italic": "italic",
|
| 112 |
+
"i": "italic",
|
| 113 |
+
"underline": "underline",
|
| 114 |
+
"u": "underline",
|
| 115 |
+
"blink": "blink",
|
| 116 |
+
"blink2": "blink2",
|
| 117 |
+
"reverse": "reverse",
|
| 118 |
+
"r": "reverse",
|
| 119 |
+
"conceal": "conceal",
|
| 120 |
+
"c": "conceal",
|
| 121 |
+
"strike": "strike",
|
| 122 |
+
"s": "strike",
|
| 123 |
+
"underline2": "underline2",
|
| 124 |
+
"uu": "underline2",
|
| 125 |
+
"frame": "frame",
|
| 126 |
+
"encircle": "encircle",
|
| 127 |
+
"overline": "overline",
|
| 128 |
+
"o": "overline",
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
def __init__(
|
| 132 |
+
self,
|
| 133 |
+
*,
|
| 134 |
+
color: Optional[Union[Color, str]] = None,
|
| 135 |
+
bgcolor: Optional[Union[Color, str]] = None,
|
| 136 |
+
bold: Optional[bool] = None,
|
| 137 |
+
dim: Optional[bool] = None,
|
| 138 |
+
italic: Optional[bool] = None,
|
| 139 |
+
underline: Optional[bool] = None,
|
| 140 |
+
blink: Optional[bool] = None,
|
| 141 |
+
blink2: Optional[bool] = None,
|
| 142 |
+
reverse: Optional[bool] = None,
|
| 143 |
+
conceal: Optional[bool] = None,
|
| 144 |
+
strike: Optional[bool] = None,
|
| 145 |
+
underline2: Optional[bool] = None,
|
| 146 |
+
frame: Optional[bool] = None,
|
| 147 |
+
encircle: Optional[bool] = None,
|
| 148 |
+
overline: Optional[bool] = None,
|
| 149 |
+
link: Optional[str] = None,
|
| 150 |
+
meta: Optional[Dict[str, Any]] = None,
|
| 151 |
+
):
|
| 152 |
+
self._ansi: Optional[str] = None
|
| 153 |
+
self._style_definition: Optional[str] = None
|
| 154 |
+
|
| 155 |
+
def _make_color(color: Union[Color, str]) -> Color:
|
| 156 |
+
return color if isinstance(color, Color) else Color.parse(color)
|
| 157 |
+
|
| 158 |
+
self._color = None if color is None else _make_color(color)
|
| 159 |
+
self._bgcolor = None if bgcolor is None else _make_color(bgcolor)
|
| 160 |
+
self._set_attributes = sum(
|
| 161 |
+
(
|
| 162 |
+
bold is not None,
|
| 163 |
+
dim is not None and 2,
|
| 164 |
+
italic is not None and 4,
|
| 165 |
+
underline is not None and 8,
|
| 166 |
+
blink is not None and 16,
|
| 167 |
+
blink2 is not None and 32,
|
| 168 |
+
reverse is not None and 64,
|
| 169 |
+
conceal is not None and 128,
|
| 170 |
+
strike is not None and 256,
|
| 171 |
+
underline2 is not None and 512,
|
| 172 |
+
frame is not None and 1024,
|
| 173 |
+
encircle is not None and 2048,
|
| 174 |
+
overline is not None and 4096,
|
| 175 |
+
)
|
| 176 |
+
)
|
| 177 |
+
self._attributes = (
|
| 178 |
+
sum(
|
| 179 |
+
(
|
| 180 |
+
bold and 1 or 0,
|
| 181 |
+
dim and 2 or 0,
|
| 182 |
+
italic and 4 or 0,
|
| 183 |
+
underline and 8 or 0,
|
| 184 |
+
blink and 16 or 0,
|
| 185 |
+
blink2 and 32 or 0,
|
| 186 |
+
reverse and 64 or 0,
|
| 187 |
+
conceal and 128 or 0,
|
| 188 |
+
strike and 256 or 0,
|
| 189 |
+
underline2 and 512 or 0,
|
| 190 |
+
frame and 1024 or 0,
|
| 191 |
+
encircle and 2048 or 0,
|
| 192 |
+
overline and 4096 or 0,
|
| 193 |
+
)
|
| 194 |
+
)
|
| 195 |
+
if self._set_attributes
|
| 196 |
+
else 0
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
self._link = link
|
| 200 |
+
self._meta = None if meta is None else dumps(meta)
|
| 201 |
+
self._link_id = (
|
| 202 |
+
f"{next(_id_generator)}{hash(self._meta)}" if (link or meta) else ""
|
| 203 |
+
)
|
| 204 |
+
self._hash: Optional[int] = None
|
| 205 |
+
self._null = not (self._set_attributes or color or bgcolor or link or meta)
|
| 206 |
+
|
| 207 |
+
@classmethod
|
| 208 |
+
def null(cls) -> "Style":
|
| 209 |
+
"""Create an 'null' style, equivalent to Style(), but more performant."""
|
| 210 |
+
return NULL_STYLE
|
| 211 |
+
|
| 212 |
+
@classmethod
|
| 213 |
+
def from_color(
|
| 214 |
+
cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None
|
| 215 |
+
) -> "Style":
|
| 216 |
+
"""Create a new style with colors and no attributes.
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None.
|
| 220 |
+
bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None.
|
| 221 |
+
"""
|
| 222 |
+
style: Style = cls.__new__(Style)
|
| 223 |
+
style._ansi = None
|
| 224 |
+
style._style_definition = None
|
| 225 |
+
style._color = color
|
| 226 |
+
style._bgcolor = bgcolor
|
| 227 |
+
style._set_attributes = 0
|
| 228 |
+
style._attributes = 0
|
| 229 |
+
style._link = None
|
| 230 |
+
style._link_id = ""
|
| 231 |
+
style._meta = None
|
| 232 |
+
style._null = not (color or bgcolor)
|
| 233 |
+
style._hash = None
|
| 234 |
+
return style
|
| 235 |
+
|
| 236 |
+
@classmethod
|
| 237 |
+
def from_meta(cls, meta: Optional[Dict[str, Any]]) -> "Style":
|
| 238 |
+
"""Create a new style with meta data.
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None.
|
| 242 |
+
"""
|
| 243 |
+
style: Style = cls.__new__(Style)
|
| 244 |
+
style._ansi = None
|
| 245 |
+
style._style_definition = None
|
| 246 |
+
style._color = None
|
| 247 |
+
style._bgcolor = None
|
| 248 |
+
style._set_attributes = 0
|
| 249 |
+
style._attributes = 0
|
| 250 |
+
style._link = None
|
| 251 |
+
style._meta = dumps(meta)
|
| 252 |
+
style._link_id = f"{next(_id_generator)}{hash(style._meta)}"
|
| 253 |
+
style._hash = None
|
| 254 |
+
style._null = not (meta)
|
| 255 |
+
return style
|
| 256 |
+
|
| 257 |
+
@classmethod
|
| 258 |
+
def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> "Style":
|
| 259 |
+
"""Create a blank style with meta information.
|
| 260 |
+
|
| 261 |
+
Example:
|
| 262 |
+
style = Style.on(click=self.on_click)
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
meta (Optional[Dict[str, Any]], optional): An optional dict of meta information.
|
| 266 |
+
**handlers (Any): Keyword arguments are translated in to handlers.
|
| 267 |
+
|
| 268 |
+
Returns:
|
| 269 |
+
Style: A Style with meta information attached.
|
| 270 |
+
"""
|
| 271 |
+
meta = {} if meta is None else meta
|
| 272 |
+
meta.update({f"@{key}": value for key, value in handlers.items()})
|
| 273 |
+
return cls.from_meta(meta)
|
| 274 |
+
|
| 275 |
+
bold = _Bit(0)
|
| 276 |
+
dim = _Bit(1)
|
| 277 |
+
italic = _Bit(2)
|
| 278 |
+
underline = _Bit(3)
|
| 279 |
+
blink = _Bit(4)
|
| 280 |
+
blink2 = _Bit(5)
|
| 281 |
+
reverse = _Bit(6)
|
| 282 |
+
conceal = _Bit(7)
|
| 283 |
+
strike = _Bit(8)
|
| 284 |
+
underline2 = _Bit(9)
|
| 285 |
+
frame = _Bit(10)
|
| 286 |
+
encircle = _Bit(11)
|
| 287 |
+
overline = _Bit(12)
|
| 288 |
+
|
| 289 |
+
@property
|
| 290 |
+
def link_id(self) -> str:
|
| 291 |
+
"""Get a link id, used in ansi code for links."""
|
| 292 |
+
return self._link_id
|
| 293 |
+
|
| 294 |
+
def __str__(self) -> str:
|
| 295 |
+
"""Re-generate style definition from attributes."""
|
| 296 |
+
if self._style_definition is None:
|
| 297 |
+
attributes: List[str] = []
|
| 298 |
+
append = attributes.append
|
| 299 |
+
bits = self._set_attributes
|
| 300 |
+
if bits & 0b0000000001111:
|
| 301 |
+
if bits & 1:
|
| 302 |
+
append("bold" if self.bold else "not bold")
|
| 303 |
+
if bits & (1 << 1):
|
| 304 |
+
append("dim" if self.dim else "not dim")
|
| 305 |
+
if bits & (1 << 2):
|
| 306 |
+
append("italic" if self.italic else "not italic")
|
| 307 |
+
if bits & (1 << 3):
|
| 308 |
+
append("underline" if self.underline else "not underline")
|
| 309 |
+
if bits & 0b0000111110000:
|
| 310 |
+
if bits & (1 << 4):
|
| 311 |
+
append("blink" if self.blink else "not blink")
|
| 312 |
+
if bits & (1 << 5):
|
| 313 |
+
append("blink2" if self.blink2 else "not blink2")
|
| 314 |
+
if bits & (1 << 6):
|
| 315 |
+
append("reverse" if self.reverse else "not reverse")
|
| 316 |
+
if bits & (1 << 7):
|
| 317 |
+
append("conceal" if self.conceal else "not conceal")
|
| 318 |
+
if bits & (1 << 8):
|
| 319 |
+
append("strike" if self.strike else "not strike")
|
| 320 |
+
if bits & 0b1111000000000:
|
| 321 |
+
if bits & (1 << 9):
|
| 322 |
+
append("underline2" if self.underline2 else "not underline2")
|
| 323 |
+
if bits & (1 << 10):
|
| 324 |
+
append("frame" if self.frame else "not frame")
|
| 325 |
+
if bits & (1 << 11):
|
| 326 |
+
append("encircle" if self.encircle else "not encircle")
|
| 327 |
+
if bits & (1 << 12):
|
| 328 |
+
append("overline" if self.overline else "not overline")
|
| 329 |
+
if self._color is not None:
|
| 330 |
+
append(self._color.name)
|
| 331 |
+
if self._bgcolor is not None:
|
| 332 |
+
append("on")
|
| 333 |
+
append(self._bgcolor.name)
|
| 334 |
+
if self._link:
|
| 335 |
+
append("link")
|
| 336 |
+
append(self._link)
|
| 337 |
+
self._style_definition = " ".join(attributes) or "none"
|
| 338 |
+
return self._style_definition
|
| 339 |
+
|
| 340 |
+
def __bool__(self) -> bool:
|
| 341 |
+
"""A Style is false if it has no attributes, colors, or links."""
|
| 342 |
+
return not self._null
|
| 343 |
+
|
| 344 |
+
def _make_ansi_codes(self, color_system: ColorSystem) -> str:
|
| 345 |
+
"""Generate ANSI codes for this style.
|
| 346 |
+
|
| 347 |
+
Args:
|
| 348 |
+
color_system (ColorSystem): Color system.
|
| 349 |
+
|
| 350 |
+
Returns:
|
| 351 |
+
str: String containing codes.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
if self._ansi is None:
|
| 355 |
+
sgr: List[str] = []
|
| 356 |
+
append = sgr.append
|
| 357 |
+
_style_map = self._style_map
|
| 358 |
+
attributes = self._attributes & self._set_attributes
|
| 359 |
+
if attributes:
|
| 360 |
+
if attributes & 1:
|
| 361 |
+
append(_style_map[0])
|
| 362 |
+
if attributes & 2:
|
| 363 |
+
append(_style_map[1])
|
| 364 |
+
if attributes & 4:
|
| 365 |
+
append(_style_map[2])
|
| 366 |
+
if attributes & 8:
|
| 367 |
+
append(_style_map[3])
|
| 368 |
+
if attributes & 0b0000111110000:
|
| 369 |
+
for bit in range(4, 9):
|
| 370 |
+
if attributes & (1 << bit):
|
| 371 |
+
append(_style_map[bit])
|
| 372 |
+
if attributes & 0b1111000000000:
|
| 373 |
+
for bit in range(9, 13):
|
| 374 |
+
if attributes & (1 << bit):
|
| 375 |
+
append(_style_map[bit])
|
| 376 |
+
if self._color is not None:
|
| 377 |
+
sgr.extend(self._color.downgrade(color_system).get_ansi_codes())
|
| 378 |
+
if self._bgcolor is not None:
|
| 379 |
+
sgr.extend(
|
| 380 |
+
self._bgcolor.downgrade(color_system).get_ansi_codes(
|
| 381 |
+
foreground=False
|
| 382 |
+
)
|
| 383 |
+
)
|
| 384 |
+
self._ansi = ";".join(sgr)
|
| 385 |
+
return self._ansi
|
| 386 |
+
|
| 387 |
+
@classmethod
|
| 388 |
+
@lru_cache(maxsize=1024)
|
| 389 |
+
def normalize(cls, style: str) -> str:
|
| 390 |
+
"""Normalize a style definition so that styles with the same effect have the same string
|
| 391 |
+
representation.
|
| 392 |
+
|
| 393 |
+
Args:
|
| 394 |
+
style (str): A style definition.
|
| 395 |
+
|
| 396 |
+
Returns:
|
| 397 |
+
str: Normal form of style definition.
|
| 398 |
+
"""
|
| 399 |
+
try:
|
| 400 |
+
return str(cls.parse(style))
|
| 401 |
+
except errors.StyleSyntaxError:
|
| 402 |
+
return style.strip().lower()
|
| 403 |
+
|
| 404 |
+
@classmethod
|
| 405 |
+
def pick_first(cls, *values: Optional[StyleType]) -> StyleType:
|
| 406 |
+
"""Pick first non-None style."""
|
| 407 |
+
for value in values:
|
| 408 |
+
if value is not None:
|
| 409 |
+
return value
|
| 410 |
+
raise ValueError("expected at least one non-None style")
|
| 411 |
+
|
| 412 |
+
def __rich_repr__(self) -> Result:
|
| 413 |
+
yield "color", self.color, None
|
| 414 |
+
yield "bgcolor", self.bgcolor, None
|
| 415 |
+
yield "bold", self.bold, None,
|
| 416 |
+
yield "dim", self.dim, None,
|
| 417 |
+
yield "italic", self.italic, None
|
| 418 |
+
yield "underline", self.underline, None,
|
| 419 |
+
yield "blink", self.blink, None
|
| 420 |
+
yield "blink2", self.blink2, None
|
| 421 |
+
yield "reverse", self.reverse, None
|
| 422 |
+
yield "conceal", self.conceal, None
|
| 423 |
+
yield "strike", self.strike, None
|
| 424 |
+
yield "underline2", self.underline2, None
|
| 425 |
+
yield "frame", self.frame, None
|
| 426 |
+
yield "encircle", self.encircle, None
|
| 427 |
+
yield "link", self.link, None
|
| 428 |
+
if self._meta:
|
| 429 |
+
yield "meta", self.meta
|
| 430 |
+
|
| 431 |
+
def __eq__(self, other: Any) -> bool:
|
| 432 |
+
if not isinstance(other, Style):
|
| 433 |
+
return NotImplemented
|
| 434 |
+
return self.__hash__() == other.__hash__()
|
| 435 |
+
|
| 436 |
+
def __ne__(self, other: Any) -> bool:
|
| 437 |
+
if not isinstance(other, Style):
|
| 438 |
+
return NotImplemented
|
| 439 |
+
return self.__hash__() != other.__hash__()
|
| 440 |
+
|
| 441 |
+
def __hash__(self) -> int:
|
| 442 |
+
if self._hash is not None:
|
| 443 |
+
return self._hash
|
| 444 |
+
self._hash = hash(_hash_getter(self))
|
| 445 |
+
return self._hash
|
| 446 |
+
|
| 447 |
+
@property
|
| 448 |
+
def color(self) -> Optional[Color]:
|
| 449 |
+
"""The foreground color or None if it is not set."""
|
| 450 |
+
return self._color
|
| 451 |
+
|
| 452 |
+
@property
|
| 453 |
+
def bgcolor(self) -> Optional[Color]:
|
| 454 |
+
"""The background color or None if it is not set."""
|
| 455 |
+
return self._bgcolor
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def link(self) -> Optional[str]:
|
| 459 |
+
"""Link text, if set."""
|
| 460 |
+
return self._link
|
| 461 |
+
|
| 462 |
+
@property
|
| 463 |
+
def transparent_background(self) -> bool:
|
| 464 |
+
"""Check if the style specified a transparent background."""
|
| 465 |
+
return self.bgcolor is None or self.bgcolor.is_default
|
| 466 |
+
|
| 467 |
+
@property
|
| 468 |
+
def background_style(self) -> "Style":
|
| 469 |
+
"""A Style with background only."""
|
| 470 |
+
return Style(bgcolor=self.bgcolor)
|
| 471 |
+
|
| 472 |
+
@property
|
| 473 |
+
def meta(self) -> Dict[str, Any]:
|
| 474 |
+
"""Get meta information (can not be changed after construction)."""
|
| 475 |
+
return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))
|
| 476 |
+
|
| 477 |
+
@property
|
| 478 |
+
def without_color(self) -> "Style":
|
| 479 |
+
"""Get a copy of the style with color removed."""
|
| 480 |
+
if self._null:
|
| 481 |
+
return NULL_STYLE
|
| 482 |
+
style: Style = self.__new__(Style)
|
| 483 |
+
style._ansi = None
|
| 484 |
+
style._style_definition = None
|
| 485 |
+
style._color = None
|
| 486 |
+
style._bgcolor = None
|
| 487 |
+
style._attributes = self._attributes
|
| 488 |
+
style._set_attributes = self._set_attributes
|
| 489 |
+
style._link = self._link
|
| 490 |
+
style._link_id = f"{next(_id_generator)}" if self._link else ""
|
| 491 |
+
style._null = False
|
| 492 |
+
style._meta = None
|
| 493 |
+
style._hash = None
|
| 494 |
+
return style
|
| 495 |
+
|
| 496 |
+
@classmethod
|
| 497 |
+
@lru_cache(maxsize=4096)
|
| 498 |
+
def parse(cls, style_definition: str) -> "Style":
|
| 499 |
+
"""Parse a style definition.
|
| 500 |
+
|
| 501 |
+
Args:
|
| 502 |
+
style_definition (str): A string containing a style.
|
| 503 |
+
|
| 504 |
+
Raises:
|
| 505 |
+
errors.StyleSyntaxError: If the style definition syntax is invalid.
|
| 506 |
+
|
| 507 |
+
Returns:
|
| 508 |
+
`Style`: A Style instance.
|
| 509 |
+
"""
|
| 510 |
+
if style_definition.strip() == "none" or not style_definition:
|
| 511 |
+
return cls.null()
|
| 512 |
+
|
| 513 |
+
STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES
|
| 514 |
+
color: Optional[str] = None
|
| 515 |
+
bgcolor: Optional[str] = None
|
| 516 |
+
attributes: Dict[str, Optional[Any]] = {}
|
| 517 |
+
link: Optional[str] = None
|
| 518 |
+
|
| 519 |
+
words = iter(style_definition.split())
|
| 520 |
+
for original_word in words:
|
| 521 |
+
word = original_word.lower()
|
| 522 |
+
if word == "on":
|
| 523 |
+
word = next(words, "")
|
| 524 |
+
if not word:
|
| 525 |
+
raise errors.StyleSyntaxError("color expected after 'on'")
|
| 526 |
+
try:
|
| 527 |
+
Color.parse(word)
|
| 528 |
+
except ColorParseError as error:
|
| 529 |
+
raise errors.StyleSyntaxError(
|
| 530 |
+
f"unable to parse {word!r} as background color; {error}"
|
| 531 |
+
) from None
|
| 532 |
+
bgcolor = word
|
| 533 |
+
|
| 534 |
+
elif word == "not":
|
| 535 |
+
word = next(words, "")
|
| 536 |
+
attribute = STYLE_ATTRIBUTES.get(word)
|
| 537 |
+
if attribute is None:
|
| 538 |
+
raise errors.StyleSyntaxError(
|
| 539 |
+
f"expected style attribute after 'not', found {word!r}"
|
| 540 |
+
)
|
| 541 |
+
attributes[attribute] = False
|
| 542 |
+
|
| 543 |
+
elif word == "link":
|
| 544 |
+
word = next(words, "")
|
| 545 |
+
if not word:
|
| 546 |
+
raise errors.StyleSyntaxError("URL expected after 'link'")
|
| 547 |
+
link = word
|
| 548 |
+
|
| 549 |
+
elif word in STYLE_ATTRIBUTES:
|
| 550 |
+
attributes[STYLE_ATTRIBUTES[word]] = True
|
| 551 |
+
|
| 552 |
+
else:
|
| 553 |
+
try:
|
| 554 |
+
Color.parse(word)
|
| 555 |
+
except ColorParseError as error:
|
| 556 |
+
raise errors.StyleSyntaxError(
|
| 557 |
+
f"unable to parse {word!r} as color; {error}"
|
| 558 |
+
) from None
|
| 559 |
+
color = word
|
| 560 |
+
style = Style(color=color, bgcolor=bgcolor, link=link, **attributes)
|
| 561 |
+
return style
|
| 562 |
+
|
| 563 |
+
@lru_cache(maxsize=1024)
|
| 564 |
+
def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str:
|
| 565 |
+
"""Get a CSS style rule."""
|
| 566 |
+
theme = theme or DEFAULT_TERMINAL_THEME
|
| 567 |
+
css: List[str] = []
|
| 568 |
+
append = css.append
|
| 569 |
+
|
| 570 |
+
color = self.color
|
| 571 |
+
bgcolor = self.bgcolor
|
| 572 |
+
if self.reverse:
|
| 573 |
+
color, bgcolor = bgcolor, color
|
| 574 |
+
if self.dim:
|
| 575 |
+
foreground_color = (
|
| 576 |
+
theme.foreground_color if color is None else color.get_truecolor(theme)
|
| 577 |
+
)
|
| 578 |
+
color = Color.from_triplet(
|
| 579 |
+
blend_rgb(foreground_color, theme.background_color, 0.5)
|
| 580 |
+
)
|
| 581 |
+
if color is not None:
|
| 582 |
+
theme_color = color.get_truecolor(theme)
|
| 583 |
+
append(f"color: {theme_color.hex}")
|
| 584 |
+
append(f"text-decoration-color: {theme_color.hex}")
|
| 585 |
+
if bgcolor is not None:
|
| 586 |
+
theme_color = bgcolor.get_truecolor(theme, foreground=False)
|
| 587 |
+
append(f"background-color: {theme_color.hex}")
|
| 588 |
+
if self.bold:
|
| 589 |
+
append("font-weight: bold")
|
| 590 |
+
if self.italic:
|
| 591 |
+
append("font-style: italic")
|
| 592 |
+
if self.underline:
|
| 593 |
+
append("text-decoration: underline")
|
| 594 |
+
if self.strike:
|
| 595 |
+
append("text-decoration: line-through")
|
| 596 |
+
if self.overline:
|
| 597 |
+
append("text-decoration: overline")
|
| 598 |
+
return "; ".join(css)
|
| 599 |
+
|
| 600 |
+
@classmethod
|
| 601 |
+
def combine(cls, styles: Iterable["Style"]) -> "Style":
|
| 602 |
+
"""Combine styles and get result.
|
| 603 |
+
|
| 604 |
+
Args:
|
| 605 |
+
styles (Iterable[Style]): Styles to combine.
|
| 606 |
+
|
| 607 |
+
Returns:
|
| 608 |
+
Style: A new style instance.
|
| 609 |
+
"""
|
| 610 |
+
iter_styles = iter(styles)
|
| 611 |
+
return sum(iter_styles, next(iter_styles))
|
| 612 |
+
|
| 613 |
+
@classmethod
|
| 614 |
+
def chain(cls, *styles: "Style") -> "Style":
|
| 615 |
+
"""Combine styles from positional argument in to a single style.
|
| 616 |
+
|
| 617 |
+
Args:
|
| 618 |
+
*styles (Iterable[Style]): Styles to combine.
|
| 619 |
+
|
| 620 |
+
Returns:
|
| 621 |
+
Style: A new style instance.
|
| 622 |
+
"""
|
| 623 |
+
iter_styles = iter(styles)
|
| 624 |
+
return sum(iter_styles, next(iter_styles))
|
| 625 |
+
|
| 626 |
+
def copy(self) -> "Style":
|
| 627 |
+
"""Get a copy of this style.
|
| 628 |
+
|
| 629 |
+
Returns:
|
| 630 |
+
Style: A new Style instance with identical attributes.
|
| 631 |
+
"""
|
| 632 |
+
if self._null:
|
| 633 |
+
return NULL_STYLE
|
| 634 |
+
style: Style = self.__new__(Style)
|
| 635 |
+
style._ansi = self._ansi
|
| 636 |
+
style._style_definition = self._style_definition
|
| 637 |
+
style._color = self._color
|
| 638 |
+
style._bgcolor = self._bgcolor
|
| 639 |
+
style._attributes = self._attributes
|
| 640 |
+
style._set_attributes = self._set_attributes
|
| 641 |
+
style._link = self._link
|
| 642 |
+
style._link_id = f"{next(_id_generator)}" if self._link else ""
|
| 643 |
+
style._hash = self._hash
|
| 644 |
+
style._null = False
|
| 645 |
+
style._meta = self._meta
|
| 646 |
+
return style
|
| 647 |
+
|
| 648 |
+
@lru_cache(maxsize=128)
|
| 649 |
+
def clear_meta_and_links(self) -> "Style":
|
| 650 |
+
"""Get a copy of this style with link and meta information removed.
|
| 651 |
+
|
| 652 |
+
Returns:
|
| 653 |
+
Style: New style object.
|
| 654 |
+
"""
|
| 655 |
+
if self._null:
|
| 656 |
+
return NULL_STYLE
|
| 657 |
+
style: Style = self.__new__(Style)
|
| 658 |
+
style._ansi = self._ansi
|
| 659 |
+
style._style_definition = self._style_definition
|
| 660 |
+
style._color = self._color
|
| 661 |
+
style._bgcolor = self._bgcolor
|
| 662 |
+
style._attributes = self._attributes
|
| 663 |
+
style._set_attributes = self._set_attributes
|
| 664 |
+
style._link = None
|
| 665 |
+
style._link_id = ""
|
| 666 |
+
style._hash = None
|
| 667 |
+
style._null = False
|
| 668 |
+
style._meta = None
|
| 669 |
+
return style
|
| 670 |
+
|
| 671 |
+
def update_link(self, link: Optional[str] = None) -> "Style":
|
| 672 |
+
"""Get a copy with a different value for link.
|
| 673 |
+
|
| 674 |
+
Args:
|
| 675 |
+
link (str, optional): New value for link. Defaults to None.
|
| 676 |
+
|
| 677 |
+
Returns:
|
| 678 |
+
Style: A new Style instance.
|
| 679 |
+
"""
|
| 680 |
+
style: Style = self.__new__(Style)
|
| 681 |
+
style._ansi = self._ansi
|
| 682 |
+
style._style_definition = self._style_definition
|
| 683 |
+
style._color = self._color
|
| 684 |
+
style._bgcolor = self._bgcolor
|
| 685 |
+
style._attributes = self._attributes
|
| 686 |
+
style._set_attributes = self._set_attributes
|
| 687 |
+
style._link = link
|
| 688 |
+
style._link_id = f"{next(_id_generator)}" if link else ""
|
| 689 |
+
style._hash = None
|
| 690 |
+
style._null = False
|
| 691 |
+
style._meta = self._meta
|
| 692 |
+
return style
|
| 693 |
+
|
| 694 |
+
def render(
|
| 695 |
+
self,
|
| 696 |
+
text: str = "",
|
| 697 |
+
*,
|
| 698 |
+
color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,
|
| 699 |
+
legacy_windows: bool = False,
|
| 700 |
+
) -> str:
|
| 701 |
+
"""Render the ANSI codes for the style.
|
| 702 |
+
|
| 703 |
+
Args:
|
| 704 |
+
text (str, optional): A string to style. Defaults to "".
|
| 705 |
+
color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.
|
| 706 |
+
|
| 707 |
+
Returns:
|
| 708 |
+
str: A string containing ANSI style codes.
|
| 709 |
+
"""
|
| 710 |
+
if not text or color_system is None:
|
| 711 |
+
return text
|
| 712 |
+
attrs = self._ansi or self._make_ansi_codes(color_system)
|
| 713 |
+
rendered = f"\x1b[{attrs}m{text}\x1b[0m" if attrs else text
|
| 714 |
+
if self._link and not legacy_windows:
|
| 715 |
+
rendered = (
|
| 716 |
+
f"\x1b]8;id={self._link_id};{self._link}\x1b\\{rendered}\x1b]8;;\x1b\\"
|
| 717 |
+
)
|
| 718 |
+
return rendered
|
| 719 |
+
|
| 720 |
+
def test(self, text: Optional[str] = None) -> None:
|
| 721 |
+
"""Write text with style directly to terminal.
|
| 722 |
+
|
| 723 |
+
This method is for testing purposes only.
|
| 724 |
+
|
| 725 |
+
Args:
|
| 726 |
+
text (Optional[str], optional): Text to style or None for style name.
|
| 727 |
+
|
| 728 |
+
"""
|
| 729 |
+
text = text or str(self)
|
| 730 |
+
sys.stdout.write(f"{self.render(text)}\n")
|
| 731 |
+
|
| 732 |
+
@lru_cache(maxsize=1024)
|
| 733 |
+
def _add(self, style: Optional["Style"]) -> "Style":
|
| 734 |
+
if style is None or style._null:
|
| 735 |
+
return self
|
| 736 |
+
if self._null:
|
| 737 |
+
return style
|
| 738 |
+
new_style: Style = self.__new__(Style)
|
| 739 |
+
new_style._ansi = None
|
| 740 |
+
new_style._style_definition = None
|
| 741 |
+
new_style._color = style._color or self._color
|
| 742 |
+
new_style._bgcolor = style._bgcolor or self._bgcolor
|
| 743 |
+
new_style._attributes = (self._attributes & ~style._set_attributes) | (
|
| 744 |
+
style._attributes & style._set_attributes
|
| 745 |
+
)
|
| 746 |
+
new_style._set_attributes = self._set_attributes | style._set_attributes
|
| 747 |
+
new_style._link = style._link or self._link
|
| 748 |
+
new_style._link_id = style._link_id or self._link_id
|
| 749 |
+
new_style._null = style._null
|
| 750 |
+
if self._meta and style._meta:
|
| 751 |
+
new_style._meta = dumps({**self.meta, **style.meta})
|
| 752 |
+
else:
|
| 753 |
+
new_style._meta = self._meta or style._meta
|
| 754 |
+
new_style._hash = None
|
| 755 |
+
return new_style
|
| 756 |
+
|
| 757 |
+
def __add__(self, style: Optional["Style"]) -> "Style":
|
| 758 |
+
combined_style = self._add(style)
|
| 759 |
+
return combined_style.copy() if combined_style.link else combined_style
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
NULL_STYLE = Style()
|
| 763 |
+
|
| 764 |
+
|
| 765 |
+
class StyleStack:
|
| 766 |
+
"""A stack of styles."""
|
| 767 |
+
|
| 768 |
+
__slots__ = ["_stack"]
|
| 769 |
+
|
| 770 |
+
def __init__(self, default_style: "Style") -> None:
|
| 771 |
+
self._stack: List[Style] = [default_style]
|
| 772 |
+
|
| 773 |
+
def __repr__(self) -> str:
|
| 774 |
+
return f"<stylestack {self._stack!r}>"
|
| 775 |
+
|
| 776 |
+
@property
|
| 777 |
+
def current(self) -> Style:
|
| 778 |
+
"""Get the Style at the top of the stack."""
|
| 779 |
+
return self._stack[-1]
|
| 780 |
+
|
| 781 |
+
def push(self, style: Style) -> None:
|
| 782 |
+
"""Push a new style on to the stack.
|
| 783 |
+
|
| 784 |
+
Args:
|
| 785 |
+
style (Style): New style to combine with current style.
|
| 786 |
+
"""
|
| 787 |
+
self._stack.append(self._stack[-1] + style)
|
| 788 |
+
|
| 789 |
+
def pop(self) -> Style:
|
| 790 |
+
"""Pop last style and discard.
|
| 791 |
+
|
| 792 |
+
Returns:
|
| 793 |
+
Style: New current style (also available as stack.current)
|
| 794 |
+
"""
|
| 795 |
+
self._stack.pop()
|
| 796 |
+
return self._stack[-1]
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/styled.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from .measure import Measurement
|
| 4 |
+
from .segment import Segment
|
| 5 |
+
from .style import StyleType
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from .console import Console, ConsoleOptions, RenderResult, RenderableType
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Styled:
|
| 12 |
+
"""Apply a style to a renderable.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
renderable (RenderableType): Any renderable.
|
| 16 |
+
style (StyleType): A style to apply across the entire renderable.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, renderable: "RenderableType", style: "StyleType") -> None:
|
| 20 |
+
self.renderable = renderable
|
| 21 |
+
self.style = style
|
| 22 |
+
|
| 23 |
+
def __rich_console__(
|
| 24 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 25 |
+
) -> "RenderResult":
|
| 26 |
+
style = console.get_style(self.style)
|
| 27 |
+
rendered_segments = console.render(self.renderable, options)
|
| 28 |
+
segments = Segment.apply_style(rendered_segments, style)
|
| 29 |
+
return segments
|
| 30 |
+
|
| 31 |
+
def __rich_measure__(
|
| 32 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 33 |
+
) -> Measurement:
|
| 34 |
+
return Measurement.get(console, options, self.renderable)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if __name__ == "__main__": # pragma: no cover
|
| 38 |
+
from rich import print
|
| 39 |
+
from rich.panel import Panel
|
| 40 |
+
|
| 41 |
+
panel = Styled(Panel("hello"), "on blue")
|
| 42 |
+
print(panel)
|
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/syntax.py
ADDED
|
@@ -0,0 +1,988 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os.path
|
| 4 |
+
import re
|
| 5 |
+
import sys
|
| 6 |
+
import textwrap
|
| 7 |
+
from abc import ABC, abstractmethod
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import (
|
| 10 |
+
TYPE_CHECKING,
|
| 11 |
+
Any,
|
| 12 |
+
Dict,
|
| 13 |
+
Iterable,
|
| 14 |
+
List,
|
| 15 |
+
NamedTuple,
|
| 16 |
+
Optional,
|
| 17 |
+
Sequence,
|
| 18 |
+
Set,
|
| 19 |
+
Tuple,
|
| 20 |
+
Type,
|
| 21 |
+
Union,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
from pygments.lexer import Lexer
|
| 25 |
+
from pygments.lexers import get_lexer_by_name, guess_lexer_for_filename
|
| 26 |
+
from pygments.style import Style as PygmentsStyle
|
| 27 |
+
from pygments.styles import get_style_by_name
|
| 28 |
+
from pygments.token import (
|
| 29 |
+
Comment,
|
| 30 |
+
Error,
|
| 31 |
+
Generic,
|
| 32 |
+
Keyword,
|
| 33 |
+
Name,
|
| 34 |
+
Number,
|
| 35 |
+
Operator,
|
| 36 |
+
String,
|
| 37 |
+
Token,
|
| 38 |
+
Whitespace,
|
| 39 |
+
)
|
| 40 |
+
from pygments.util import ClassNotFound
|
| 41 |
+
|
| 42 |
+
if TYPE_CHECKING:
|
| 43 |
+
from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
|
| 44 |
+
|
| 45 |
+
from rich.containers import Lines
|
| 46 |
+
from rich.padding import Padding, PaddingDimensions
|
| 47 |
+
|
| 48 |
+
from ._loop import loop_first
|
| 49 |
+
from .cells import cell_len
|
| 50 |
+
from .color import Color, blend_rgb
|
| 51 |
+
from .jupyter import JupyterMixin
|
| 52 |
+
from .measure import Measurement
|
| 53 |
+
from .segment import Segment, Segments
|
| 54 |
+
from .style import Style, StyleType
|
| 55 |
+
from .text import Text
|
| 56 |
+
|
| 57 |
+
TokenType = Tuple[str, ...]
|
| 58 |
+
|
| 59 |
+
WINDOWS = sys.platform == "win32"
|
| 60 |
+
DEFAULT_THEME = "monokai"
|
| 61 |
+
|
| 62 |
+
# The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py
|
| 63 |
+
# A few modifications were made
|
| 64 |
+
|
| 65 |
+
ANSI_LIGHT: Dict[TokenType, Style] = {
|
| 66 |
+
Token: Style(),
|
| 67 |
+
Whitespace: Style(color="white"),
|
| 68 |
+
Comment: Style(dim=True),
|
| 69 |
+
Comment.Preproc: Style(color="cyan"),
|
| 70 |
+
Keyword: Style(color="blue"),
|
| 71 |
+
Keyword.Type: Style(color="cyan"),
|
| 72 |
+
Operator.Word: Style(color="magenta"),
|
| 73 |
+
Name.Builtin: Style(color="cyan"),
|
| 74 |
+
Name.Function: Style(color="green"),
|
| 75 |
+
Name.Namespace: Style(color="cyan", underline=True),
|
| 76 |
+
Name.Class: Style(color="green", underline=True),
|
| 77 |
+
Name.Exception: Style(color="cyan"),
|
| 78 |
+
Name.Decorator: Style(color="magenta", bold=True),
|
| 79 |
+
Name.Variable: Style(color="red"),
|
| 80 |
+
Name.Constant: Style(color="red"),
|
| 81 |
+
Name.Attribute: Style(color="cyan"),
|
| 82 |
+
Name.Tag: Style(color="bright_blue"),
|
| 83 |
+
String: Style(color="yellow"),
|
| 84 |
+
Number: Style(color="blue"),
|
| 85 |
+
Generic.Deleted: Style(color="bright_red"),
|
| 86 |
+
Generic.Inserted: Style(color="green"),
|
| 87 |
+
Generic.Heading: Style(bold=True),
|
| 88 |
+
Generic.Subheading: Style(color="magenta", bold=True),
|
| 89 |
+
Generic.Prompt: Style(bold=True),
|
| 90 |
+
Generic.Error: Style(color="bright_red"),
|
| 91 |
+
Error: Style(color="red", underline=True),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
ANSI_DARK: Dict[TokenType, Style] = {
|
| 95 |
+
Token: Style(),
|
| 96 |
+
Whitespace: Style(color="bright_black"),
|
| 97 |
+
Comment: Style(dim=True),
|
| 98 |
+
Comment.Preproc: Style(color="bright_cyan"),
|
| 99 |
+
Keyword: Style(color="bright_blue"),
|
| 100 |
+
Keyword.Type: Style(color="bright_cyan"),
|
| 101 |
+
Operator.Word: Style(color="bright_magenta"),
|
| 102 |
+
Name.Builtin: Style(color="bright_cyan"),
|
| 103 |
+
Name.Function: Style(color="bright_green"),
|
| 104 |
+
Name.Namespace: Style(color="bright_cyan", underline=True),
|
| 105 |
+
Name.Class: Style(color="bright_green", underline=True),
|
| 106 |
+
Name.Exception: Style(color="bright_cyan"),
|
| 107 |
+
Name.Decorator: Style(color="bright_magenta", bold=True),
|
| 108 |
+
Name.Variable: Style(color="bright_red"),
|
| 109 |
+
Name.Constant: Style(color="bright_red"),
|
| 110 |
+
Name.Attribute: Style(color="bright_cyan"),
|
| 111 |
+
Name.Tag: Style(color="bright_blue"),
|
| 112 |
+
String: Style(color="yellow"),
|
| 113 |
+
Number: Style(color="bright_blue"),
|
| 114 |
+
Generic.Deleted: Style(color="bright_red"),
|
| 115 |
+
Generic.Inserted: Style(color="bright_green"),
|
| 116 |
+
Generic.Heading: Style(bold=True),
|
| 117 |
+
Generic.Subheading: Style(color="bright_magenta", bold=True),
|
| 118 |
+
Generic.Prompt: Style(bold=True),
|
| 119 |
+
Generic.Error: Style(color="bright_red"),
|
| 120 |
+
Error: Style(color="red", underline=True),
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
RICH_SYNTAX_THEMES = {"ansi_light": ANSI_LIGHT, "ansi_dark": ANSI_DARK}
|
| 124 |
+
NUMBERS_COLUMN_DEFAULT_PADDING = 2
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class SyntaxTheme(ABC):
|
| 128 |
+
"""Base class for a syntax theme."""
|
| 129 |
+
|
| 130 |
+
@abstractmethod
|
| 131 |
+
def get_style_for_token(self, token_type: TokenType) -> Style:
|
| 132 |
+
"""Get a style for a given Pygments token."""
|
| 133 |
+
raise NotImplementedError # pragma: no cover
|
| 134 |
+
|
| 135 |
+
@abstractmethod
|
| 136 |
+
def get_background_style(self) -> Style:
|
| 137 |
+
"""Get the background color."""
|
| 138 |
+
raise NotImplementedError # pragma: no cover
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class PygmentsSyntaxTheme(SyntaxTheme):
|
| 142 |
+
"""Syntax theme that delegates to Pygments theme."""
|
| 143 |
+
|
| 144 |
+
def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:
|
| 145 |
+
self._style_cache: Dict[TokenType, Style] = {}
|
| 146 |
+
if isinstance(theme, str):
|
| 147 |
+
try:
|
| 148 |
+
self._pygments_style_class = get_style_by_name(theme)
|
| 149 |
+
except ClassNotFound:
|
| 150 |
+
self._pygments_style_class = get_style_by_name("default")
|
| 151 |
+
else:
|
| 152 |
+
self._pygments_style_class = theme
|
| 153 |
+
|
| 154 |
+
self._background_color = self._pygments_style_class.background_color
|
| 155 |
+
self._background_style = Style(bgcolor=self._background_color)
|
| 156 |
+
|
| 157 |
+
def get_style_for_token(self, token_type: TokenType) -> Style:
|
| 158 |
+
"""Get a style from a Pygments class."""
|
| 159 |
+
try:
|
| 160 |
+
return self._style_cache[token_type]
|
| 161 |
+
except KeyError:
|
| 162 |
+
try:
|
| 163 |
+
pygments_style = self._pygments_style_class.style_for_token(token_type)
|
| 164 |
+
except KeyError:
|
| 165 |
+
style = Style.null()
|
| 166 |
+
else:
|
| 167 |
+
color = pygments_style["color"]
|
| 168 |
+
bgcolor = pygments_style["bgcolor"]
|
| 169 |
+
style = Style(
|
| 170 |
+
color="#" + color if color else "#000000",
|
| 171 |
+
bgcolor="#" + bgcolor if bgcolor else self._background_color,
|
| 172 |
+
bold=pygments_style["bold"],
|
| 173 |
+
italic=pygments_style["italic"],
|
| 174 |
+
underline=pygments_style["underline"],
|
| 175 |
+
)
|
| 176 |
+
self._style_cache[token_type] = style
|
| 177 |
+
return style
|
| 178 |
+
|
| 179 |
+
def get_background_style(self) -> Style:
|
| 180 |
+
return self._background_style
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class ANSISyntaxTheme(SyntaxTheme):
|
| 184 |
+
"""Syntax theme to use standard colors."""
|
| 185 |
+
|
| 186 |
+
def __init__(self, style_map: Dict[TokenType, Style]) -> None:
|
| 187 |
+
self.style_map = style_map
|
| 188 |
+
self._missing_style = Style.null()
|
| 189 |
+
self._background_style = Style.null()
|
| 190 |
+
self._style_cache: Dict[TokenType, Style] = {}
|
| 191 |
+
|
| 192 |
+
def get_style_for_token(self, token_type: TokenType) -> Style:
|
| 193 |
+
"""Look up style in the style map."""
|
| 194 |
+
try:
|
| 195 |
+
return self._style_cache[token_type]
|
| 196 |
+
except KeyError:
|
| 197 |
+
# Styles form a hierarchy
|
| 198 |
+
# We need to go from most to least specific
|
| 199 |
+
# e.g. ("foo", "bar", "baz") to ("foo", "bar") to ("foo",)
|
| 200 |
+
get_style = self.style_map.get
|
| 201 |
+
token = tuple(token_type)
|
| 202 |
+
style = self._missing_style
|
| 203 |
+
while token:
|
| 204 |
+
_style = get_style(token)
|
| 205 |
+
if _style is not None:
|
| 206 |
+
style = _style
|
| 207 |
+
break
|
| 208 |
+
token = token[:-1]
|
| 209 |
+
self._style_cache[token_type] = style
|
| 210 |
+
return style
|
| 211 |
+
|
| 212 |
+
def get_background_style(self) -> Style:
|
| 213 |
+
return self._background_style
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
SyntaxPosition = Tuple[int, int]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class _SyntaxHighlightRange(NamedTuple):
|
| 220 |
+
"""
|
| 221 |
+
A range to highlight in a Syntax object.
|
| 222 |
+
`start` and `end` are 2-integers tuples, where the first integer is the line number
|
| 223 |
+
(starting from 1) and the second integer is the column index (starting from 0).
|
| 224 |
+
"""
|
| 225 |
+
|
| 226 |
+
style: StyleType
|
| 227 |
+
start: SyntaxPosition
|
| 228 |
+
end: SyntaxPosition
|
| 229 |
+
style_before: bool = False
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class PaddingProperty:
|
| 233 |
+
"""Descriptor to get and set padding."""
|
| 234 |
+
|
| 235 |
+
def __get__(self, obj: Syntax, objtype: Type[Syntax]) -> Tuple[int, int, int, int]:
|
| 236 |
+
"""Space around the Syntax."""
|
| 237 |
+
return obj._padding
|
| 238 |
+
|
| 239 |
+
def __set__(self, obj: Syntax, padding: PaddingDimensions) -> None:
|
| 240 |
+
obj._padding = Padding.unpack(padding)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class Syntax(JupyterMixin):
|
| 244 |
+
"""Construct a Syntax object to render syntax highlighted code.
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
code (str): Code to highlight.
|
| 248 |
+
lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)
|
| 249 |
+
theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai".
|
| 250 |
+
dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.
|
| 251 |
+
line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
|
| 252 |
+
start_line (int, optional): Starting number for line numbers. Defaults to 1.
|
| 253 |
+
line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render.
|
| 254 |
+
A value of None in the tuple indicates the range is open in that direction.
|
| 255 |
+
highlight_lines (Set[int]): A set of line numbers to highlight.
|
| 256 |
+
code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
|
| 257 |
+
tab_size (int, optional): Size of tabs. Defaults to 4.
|
| 258 |
+
word_wrap (bool, optional): Enable word wrapping.
|
| 259 |
+
background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
|
| 260 |
+
indent_guides (bool, optional): Show indent guides. Defaults to False.
|
| 261 |
+
padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
_pygments_style_class: Type[PygmentsStyle]
|
| 265 |
+
_theme: SyntaxTheme
|
| 266 |
+
|
| 267 |
+
@classmethod
|
| 268 |
+
def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:
|
| 269 |
+
"""Get a syntax theme instance."""
|
| 270 |
+
if isinstance(name, SyntaxTheme):
|
| 271 |
+
return name
|
| 272 |
+
theme: SyntaxTheme
|
| 273 |
+
if name in RICH_SYNTAX_THEMES:
|
| 274 |
+
theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])
|
| 275 |
+
else:
|
| 276 |
+
theme = PygmentsSyntaxTheme(name)
|
| 277 |
+
return theme
|
| 278 |
+
|
| 279 |
+
def __init__(
|
| 280 |
+
self,
|
| 281 |
+
code: str,
|
| 282 |
+
lexer: Union[Lexer, str],
|
| 283 |
+
*,
|
| 284 |
+
theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
|
| 285 |
+
dedent: bool = False,
|
| 286 |
+
line_numbers: bool = False,
|
| 287 |
+
start_line: int = 1,
|
| 288 |
+
line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
|
| 289 |
+
highlight_lines: Optional[Set[int]] = None,
|
| 290 |
+
code_width: Optional[int] = None,
|
| 291 |
+
tab_size: int = 4,
|
| 292 |
+
word_wrap: bool = False,
|
| 293 |
+
background_color: Optional[str] = None,
|
| 294 |
+
indent_guides: bool = False,
|
| 295 |
+
padding: PaddingDimensions = 0,
|
| 296 |
+
) -> None:
|
| 297 |
+
self.code = code
|
| 298 |
+
self._lexer = lexer
|
| 299 |
+
self.dedent = dedent
|
| 300 |
+
self.line_numbers = line_numbers
|
| 301 |
+
self.start_line = start_line
|
| 302 |
+
self.line_range = line_range
|
| 303 |
+
self.highlight_lines = highlight_lines or set()
|
| 304 |
+
self.code_width = code_width
|
| 305 |
+
self.tab_size = tab_size
|
| 306 |
+
self.word_wrap = word_wrap
|
| 307 |
+
self.background_color = background_color
|
| 308 |
+
self.background_style = (
|
| 309 |
+
Style(bgcolor=background_color) if background_color else Style()
|
| 310 |
+
)
|
| 311 |
+
self.indent_guides = indent_guides
|
| 312 |
+
self._padding = Padding.unpack(padding)
|
| 313 |
+
|
| 314 |
+
self._theme = self.get_theme(theme)
|
| 315 |
+
self._stylized_ranges: List[_SyntaxHighlightRange] = []
|
| 316 |
+
|
| 317 |
+
padding = PaddingProperty()
|
| 318 |
+
|
| 319 |
+
@classmethod
|
| 320 |
+
def from_path(
|
| 321 |
+
cls,
|
| 322 |
+
path: str,
|
| 323 |
+
encoding: str = "utf-8",
|
| 324 |
+
lexer: Optional[Union[Lexer, str]] = None,
|
| 325 |
+
theme: Union[str, SyntaxTheme] = DEFAULT_THEME,
|
| 326 |
+
dedent: bool = False,
|
| 327 |
+
line_numbers: bool = False,
|
| 328 |
+
line_range: Optional[Tuple[int, int]] = None,
|
| 329 |
+
start_line: int = 1,
|
| 330 |
+
highlight_lines: Optional[Set[int]] = None,
|
| 331 |
+
code_width: Optional[int] = None,
|
| 332 |
+
tab_size: int = 4,
|
| 333 |
+
word_wrap: bool = False,
|
| 334 |
+
background_color: Optional[str] = None,
|
| 335 |
+
indent_guides: bool = False,
|
| 336 |
+
padding: PaddingDimensions = 0,
|
| 337 |
+
) -> "Syntax":
|
| 338 |
+
"""Construct a Syntax object from a file.
|
| 339 |
+
|
| 340 |
+
Args:
|
| 341 |
+
path (str): Path to file to highlight.
|
| 342 |
+
encoding (str): Encoding of file.
|
| 343 |
+
lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content.
|
| 344 |
+
theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs".
|
| 345 |
+
dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.
|
| 346 |
+
line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.
|
| 347 |
+
start_line (int, optional): Starting number for line numbers. Defaults to 1.
|
| 348 |
+
line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.
|
| 349 |
+
highlight_lines (Set[int]): A set of line numbers to highlight.
|
| 350 |
+
code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.
|
| 351 |
+
tab_size (int, optional): Size of tabs. Defaults to 4.
|
| 352 |
+
word_wrap (bool, optional): Enable word wrapping of code.
|
| 353 |
+
background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.
|
| 354 |
+
indent_guides (bool, optional): Show indent guides. Defaults to False.
|
| 355 |
+
padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).
|
| 356 |
+
|
| 357 |
+
Returns:
|
| 358 |
+
[Syntax]: A Syntax object that may be printed to the console
|
| 359 |
+
"""
|
| 360 |
+
code = Path(path).read_text(encoding=encoding)
|
| 361 |
+
|
| 362 |
+
if not lexer:
|
| 363 |
+
lexer = cls.guess_lexer(path, code=code)
|
| 364 |
+
|
| 365 |
+
return cls(
|
| 366 |
+
code,
|
| 367 |
+
lexer,
|
| 368 |
+
theme=theme,
|
| 369 |
+
dedent=dedent,
|
| 370 |
+
line_numbers=line_numbers,
|
| 371 |
+
line_range=line_range,
|
| 372 |
+
start_line=start_line,
|
| 373 |
+
highlight_lines=highlight_lines,
|
| 374 |
+
code_width=code_width,
|
| 375 |
+
tab_size=tab_size,
|
| 376 |
+
word_wrap=word_wrap,
|
| 377 |
+
background_color=background_color,
|
| 378 |
+
indent_guides=indent_guides,
|
| 379 |
+
padding=padding,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
@classmethod
|
| 383 |
+
def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:
|
| 384 |
+
"""Guess the alias of the Pygments lexer to use based on a path and an optional string of code.
|
| 385 |
+
If code is supplied, it will use a combination of the code and the filename to determine the
|
| 386 |
+
best lexer to use. For example, if the file is ``index.html`` and the file contains Django
|
| 387 |
+
templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no
|
| 388 |
+
templating language is used, the "html" lexer will be used. If no string of code
|
| 389 |
+
is supplied, the lexer will be chosen based on the file extension..
|
| 390 |
+
|
| 391 |
+
Args:
|
| 392 |
+
path (AnyStr): The path to the file containing the code you wish to know the lexer for.
|
| 393 |
+
code (str, optional): Optional string of code that will be used as a fallback if no lexer
|
| 394 |
+
is found for the supplied path.
|
| 395 |
+
|
| 396 |
+
Returns:
|
| 397 |
+
str: The name of the Pygments lexer that best matches the supplied path/code.
|
| 398 |
+
"""
|
| 399 |
+
lexer: Optional[Lexer] = None
|
| 400 |
+
lexer_name = "default"
|
| 401 |
+
if code:
|
| 402 |
+
try:
|
| 403 |
+
lexer = guess_lexer_for_filename(path, code)
|
| 404 |
+
except ClassNotFound:
|
| 405 |
+
pass
|
| 406 |
+
|
| 407 |
+
if not lexer:
|
| 408 |
+
try:
|
| 409 |
+
_, ext = os.path.splitext(path)
|
| 410 |
+
if ext:
|
| 411 |
+
extension = ext.lstrip(".").lower()
|
| 412 |
+
lexer = get_lexer_by_name(extension)
|
| 413 |
+
except ClassNotFound:
|
| 414 |
+
pass
|
| 415 |
+
|
| 416 |
+
if lexer:
|
| 417 |
+
if lexer.aliases:
|
| 418 |
+
lexer_name = lexer.aliases[0]
|
| 419 |
+
else:
|
| 420 |
+
lexer_name = lexer.name
|
| 421 |
+
|
| 422 |
+
return lexer_name
|
| 423 |
+
|
| 424 |
+
def _get_base_style(self) -> Style:
|
| 425 |
+
"""Get the base style."""
|
| 426 |
+
default_style = self._theme.get_background_style() + self.background_style
|
| 427 |
+
return default_style
|
| 428 |
+
|
| 429 |
+
def _get_token_color(self, token_type: TokenType) -> Optional[Color]:
|
| 430 |
+
"""Get a color (if any) for the given token.
|
| 431 |
+
|
| 432 |
+
Args:
|
| 433 |
+
token_type (TokenType): A token type tuple from Pygments.
|
| 434 |
+
|
| 435 |
+
Returns:
|
| 436 |
+
Optional[Color]: Color from theme, or None for no color.
|
| 437 |
+
"""
|
| 438 |
+
style = self._theme.get_style_for_token(token_type)
|
| 439 |
+
return style.color
|
| 440 |
+
|
| 441 |
+
@property
|
| 442 |
+
def lexer(self) -> Optional[Lexer]:
|
| 443 |
+
"""The lexer for this syntax, or None if no lexer was found.
|
| 444 |
+
|
| 445 |
+
Tries to find the lexer by name if a string was passed to the constructor.
|
| 446 |
+
"""
|
| 447 |
+
|
| 448 |
+
if isinstance(self._lexer, Lexer):
|
| 449 |
+
return self._lexer
|
| 450 |
+
try:
|
| 451 |
+
return get_lexer_by_name(
|
| 452 |
+
self._lexer,
|
| 453 |
+
stripnl=False,
|
| 454 |
+
ensurenl=True,
|
| 455 |
+
tabsize=self.tab_size,
|
| 456 |
+
)
|
| 457 |
+
except ClassNotFound:
|
| 458 |
+
return None
|
| 459 |
+
|
| 460 |
+
@property
|
| 461 |
+
def default_lexer(self) -> Lexer:
|
| 462 |
+
"""A Pygments Lexer to use if one is not specified or invalid."""
|
| 463 |
+
return get_lexer_by_name(
|
| 464 |
+
"text",
|
| 465 |
+
stripnl=False,
|
| 466 |
+
ensurenl=True,
|
| 467 |
+
tabsize=self.tab_size,
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
def highlight(
|
| 471 |
+
self,
|
| 472 |
+
code: str,
|
| 473 |
+
line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,
|
| 474 |
+
) -> Text:
|
| 475 |
+
"""Highlight code and return a Text instance.
|
| 476 |
+
|
| 477 |
+
Args:
|
| 478 |
+
code (str): Code to highlight.
|
| 479 |
+
line_range(Tuple[int, int], optional): Optional line range to highlight.
|
| 480 |
+
|
| 481 |
+
Returns:
|
| 482 |
+
Text: A text instance containing highlighted syntax.
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
base_style = self._get_base_style()
|
| 486 |
+
justify: JustifyMethod = (
|
| 487 |
+
"default" if base_style.transparent_background else "left"
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
text = Text(
|
| 491 |
+
justify=justify,
|
| 492 |
+
style=base_style,
|
| 493 |
+
tab_size=self.tab_size,
|
| 494 |
+
no_wrap=not self.word_wrap,
|
| 495 |
+
)
|
| 496 |
+
_get_theme_style = self._theme.get_style_for_token
|
| 497 |
+
|
| 498 |
+
lexer = self.lexer or self.default_lexer
|
| 499 |
+
|
| 500 |
+
if lexer is None:
|
| 501 |
+
text.append(code)
|
| 502 |
+
else:
|
| 503 |
+
if line_range:
|
| 504 |
+
# More complicated path to only stylize a portion of the code
|
| 505 |
+
# This speeds up further operations as there are less spans to process
|
| 506 |
+
line_start, line_end = line_range
|
| 507 |
+
|
| 508 |
+
def line_tokenize() -> Iterable[Tuple[Any, str]]:
|
| 509 |
+
"""Split tokens to one per line."""
|
| 510 |
+
assert lexer # required to make MyPy happy - we know lexer is not None at this point
|
| 511 |
+
|
| 512 |
+
for token_type, token in lexer.get_tokens(code):
|
| 513 |
+
while token:
|
| 514 |
+
line_token, new_line, token = token.partition("\n")
|
| 515 |
+
yield token_type, line_token + new_line
|
| 516 |
+
|
| 517 |
+
def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:
|
| 518 |
+
"""Convert tokens to spans."""
|
| 519 |
+
tokens = iter(line_tokenize())
|
| 520 |
+
line_no = 0
|
| 521 |
+
_line_start = line_start - 1 if line_start else 0
|
| 522 |
+
|
| 523 |
+
# Skip over tokens until line start
|
| 524 |
+
while line_no < _line_start:
|
| 525 |
+
try:
|
| 526 |
+
_token_type, token = next(tokens)
|
| 527 |
+
except StopIteration:
|
| 528 |
+
break
|
| 529 |
+
yield (token, None)
|
| 530 |
+
if token.endswith("\n"):
|
| 531 |
+
line_no += 1
|
| 532 |
+
# Generate spans until line end
|
| 533 |
+
for token_type, token in tokens:
|
| 534 |
+
yield (token, _get_theme_style(token_type))
|
| 535 |
+
if token.endswith("\n"):
|
| 536 |
+
line_no += 1
|
| 537 |
+
if line_end and line_no >= line_end:
|
| 538 |
+
break
|
| 539 |
+
|
| 540 |
+
text.append_tokens(tokens_to_spans())
|
| 541 |
+
|
| 542 |
+
else:
|
| 543 |
+
text.append_tokens(
|
| 544 |
+
(token, _get_theme_style(token_type))
|
| 545 |
+
for token_type, token in lexer.get_tokens(code)
|
| 546 |
+
)
|
| 547 |
+
if self.background_color is not None:
|
| 548 |
+
text.stylize(f"on {self.background_color}")
|
| 549 |
+
|
| 550 |
+
if self._stylized_ranges:
|
| 551 |
+
self._apply_stylized_ranges(text)
|
| 552 |
+
|
| 553 |
+
return text
|
| 554 |
+
|
| 555 |
+
def stylize_range(
|
| 556 |
+
self,
|
| 557 |
+
style: StyleType,
|
| 558 |
+
start: SyntaxPosition,
|
| 559 |
+
end: SyntaxPosition,
|
| 560 |
+
style_before: bool = False,
|
| 561 |
+
) -> None:
|
| 562 |
+
"""
|
| 563 |
+
Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered.
|
| 564 |
+
Line numbers are 1-based, while column indexes are 0-based.
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
style (StyleType): The style to apply.
|
| 568 |
+
start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`.
|
| 569 |
+
end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`.
|
| 570 |
+
style_before (bool): Apply the style before any existing styles.
|
| 571 |
+
"""
|
| 572 |
+
self._stylized_ranges.append(
|
| 573 |
+
_SyntaxHighlightRange(style, start, end, style_before)
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
def _get_line_numbers_color(self, blend: float = 0.3) -> Color:
|
| 577 |
+
background_style = self._theme.get_background_style() + self.background_style
|
| 578 |
+
background_color = background_style.bgcolor
|
| 579 |
+
if background_color is None or background_color.is_system_defined:
|
| 580 |
+
return Color.default()
|
| 581 |
+
foreground_color = self._get_token_color(Token.Text)
|
| 582 |
+
if foreground_color is None or foreground_color.is_system_defined:
|
| 583 |
+
return foreground_color or Color.default()
|
| 584 |
+
new_color = blend_rgb(
|
| 585 |
+
background_color.get_truecolor(),
|
| 586 |
+
foreground_color.get_truecolor(),
|
| 587 |
+
cross_fade=blend,
|
| 588 |
+
)
|
| 589 |
+
return Color.from_triplet(new_color)
|
| 590 |
+
|
| 591 |
+
@property
|
| 592 |
+
def _numbers_column_width(self) -> int:
|
| 593 |
+
"""Get the number of characters used to render the numbers column."""
|
| 594 |
+
column_width = 0
|
| 595 |
+
if self.line_numbers:
|
| 596 |
+
column_width = (
|
| 597 |
+
len(str(self.start_line + self.code.count("\n")))
|
| 598 |
+
+ NUMBERS_COLUMN_DEFAULT_PADDING
|
| 599 |
+
)
|
| 600 |
+
return column_width
|
| 601 |
+
|
| 602 |
+
def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:
|
| 603 |
+
"""Get background, number, and highlight styles for line numbers."""
|
| 604 |
+
background_style = self._get_base_style()
|
| 605 |
+
if background_style.transparent_background:
|
| 606 |
+
return Style.null(), Style(dim=True), Style.null()
|
| 607 |
+
if console.color_system in ("256", "truecolor"):
|
| 608 |
+
number_style = Style.chain(
|
| 609 |
+
background_style,
|
| 610 |
+
self._theme.get_style_for_token(Token.Text),
|
| 611 |
+
Style(color=self._get_line_numbers_color()),
|
| 612 |
+
self.background_style,
|
| 613 |
+
)
|
| 614 |
+
highlight_number_style = Style.chain(
|
| 615 |
+
background_style,
|
| 616 |
+
self._theme.get_style_for_token(Token.Text),
|
| 617 |
+
Style(bold=True, color=self._get_line_numbers_color(0.9)),
|
| 618 |
+
self.background_style,
|
| 619 |
+
)
|
| 620 |
+
else:
|
| 621 |
+
number_style = background_style + Style(dim=True)
|
| 622 |
+
highlight_number_style = background_style + Style(dim=False)
|
| 623 |
+
return background_style, number_style, highlight_number_style
|
| 624 |
+
|
| 625 |
+
def __rich_measure__(
|
| 626 |
+
self, console: "Console", options: "ConsoleOptions"
|
| 627 |
+
) -> "Measurement":
|
| 628 |
+
_, right, _, left = self.padding
|
| 629 |
+
padding = left + right
|
| 630 |
+
if self.code_width is not None:
|
| 631 |
+
width = self.code_width + self._numbers_column_width + padding + 1
|
| 632 |
+
return Measurement(self._numbers_column_width, width)
|
| 633 |
+
lines = self.code.splitlines()
|
| 634 |
+
width = (
|
| 635 |
+
self._numbers_column_width
|
| 636 |
+
+ padding
|
| 637 |
+
+ (max(cell_len(line) for line in lines) if lines else 0)
|
| 638 |
+
)
|
| 639 |
+
if self.line_numbers:
|
| 640 |
+
width += 1
|
| 641 |
+
return Measurement(self._numbers_column_width, width)
|
| 642 |
+
|
| 643 |
+
def __rich_console__(
|
| 644 |
+
self, console: Console, options: ConsoleOptions
|
| 645 |
+
) -> RenderResult:
|
| 646 |
+
segments = Segments(self._get_syntax(console, options))
|
| 647 |
+
if any(self.padding):
|
| 648 |
+
yield Padding(segments, style=self._get_base_style(), pad=self.padding)
|
| 649 |
+
else:
|
| 650 |
+
yield segments
|
| 651 |
+
|
| 652 |
+
def _get_syntax(
|
| 653 |
+
self,
|
| 654 |
+
console: Console,
|
| 655 |
+
options: ConsoleOptions,
|
| 656 |
+
) -> Iterable[Segment]:
|
| 657 |
+
"""
|
| 658 |
+
Get the Segments for the Syntax object, excluding any vertical/horizontal padding
|
| 659 |
+
"""
|
| 660 |
+
transparent_background = self._get_base_style().transparent_background
|
| 661 |
+
_pad_top, pad_right, _pad_bottom, pad_left = self.padding
|
| 662 |
+
horizontal_padding = pad_left + pad_right
|
| 663 |
+
code_width = (
|
| 664 |
+
(
|
| 665 |
+
(options.max_width - self._numbers_column_width - 1)
|
| 666 |
+
if self.line_numbers
|
| 667 |
+
else options.max_width
|
| 668 |
+
)
|
| 669 |
+
- horizontal_padding
|
| 670 |
+
if self.code_width is None
|
| 671 |
+
else self.code_width
|
| 672 |
+
)
|
| 673 |
+
code_width = max(0, code_width)
|
| 674 |
+
|
| 675 |
+
ends_on_nl, processed_code = self._process_code(self.code)
|
| 676 |
+
text = self.highlight(processed_code, self.line_range)
|
| 677 |
+
|
| 678 |
+
if not self.line_numbers and not self.word_wrap and not self.line_range:
|
| 679 |
+
if not ends_on_nl:
|
| 680 |
+
text.remove_suffix("\n")
|
| 681 |
+
# Simple case of just rendering text
|
| 682 |
+
style = (
|
| 683 |
+
self._get_base_style()
|
| 684 |
+
+ self._theme.get_style_for_token(Comment)
|
| 685 |
+
+ Style(dim=True)
|
| 686 |
+
+ self.background_style
|
| 687 |
+
)
|
| 688 |
+
if self.indent_guides and not options.ascii_only:
|
| 689 |
+
text = text.with_indent_guides(self.tab_size, style=style)
|
| 690 |
+
text.overflow = "crop"
|
| 691 |
+
if style.transparent_background:
|
| 692 |
+
yield from console.render(
|
| 693 |
+
text, options=options.update(width=code_width)
|
| 694 |
+
)
|
| 695 |
+
else:
|
| 696 |
+
syntax_lines = console.render_lines(
|
| 697 |
+
text,
|
| 698 |
+
options.update(width=code_width, height=None, justify="left"),
|
| 699 |
+
style=self.background_style,
|
| 700 |
+
pad=True,
|
| 701 |
+
new_lines=True,
|
| 702 |
+
)
|
| 703 |
+
for syntax_line in syntax_lines:
|
| 704 |
+
yield from syntax_line
|
| 705 |
+
return
|
| 706 |
+
|
| 707 |
+
start_line, end_line = self.line_range or (None, None)
|
| 708 |
+
line_offset = 0
|
| 709 |
+
if start_line:
|
| 710 |
+
line_offset = max(0, start_line - 1)
|
| 711 |
+
lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl)
|
| 712 |
+
if self.line_range:
|
| 713 |
+
if line_offset > len(lines):
|
| 714 |
+
return
|
| 715 |
+
lines = lines[line_offset:end_line]
|
| 716 |
+
|
| 717 |
+
if self.indent_guides and not options.ascii_only:
|
| 718 |
+
style = (
|
| 719 |
+
self._get_base_style()
|
| 720 |
+
+ self._theme.get_style_for_token(Comment)
|
| 721 |
+
+ Style(dim=True)
|
| 722 |
+
+ self.background_style
|
| 723 |
+
)
|
| 724 |
+
lines = (
|
| 725 |
+
Text("\n")
|
| 726 |
+
.join(lines)
|
| 727 |
+
.with_indent_guides(self.tab_size, style=style + Style(italic=False))
|
| 728 |
+
.split("\n", allow_blank=True)
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
numbers_column_width = self._numbers_column_width
|
| 732 |
+
render_options = options.update(width=code_width)
|
| 733 |
+
|
| 734 |
+
highlight_line = self.highlight_lines.__contains__
|
| 735 |
+
_Segment = Segment
|
| 736 |
+
new_line = _Segment("\n")
|
| 737 |
+
|
| 738 |
+
line_pointer = "> " if options.legacy_windows else "❱ "
|
| 739 |
+
|
| 740 |
+
(
|
| 741 |
+
background_style,
|
| 742 |
+
number_style,
|
| 743 |
+
highlight_number_style,
|
| 744 |
+
) = self._get_number_styles(console)
|
| 745 |
+
|
| 746 |
+
for line_no, line in enumerate(lines, self.start_line + line_offset):
|
| 747 |
+
if self.word_wrap:
|
| 748 |
+
wrapped_lines = console.render_lines(
|
| 749 |
+
line,
|
| 750 |
+
render_options.update(height=None, justify="left"),
|
| 751 |
+
style=background_style,
|
| 752 |
+
pad=not transparent_background,
|
| 753 |
+
)
|
| 754 |
+
else:
|
| 755 |
+
segments = list(line.render(console, end=""))
|
| 756 |
+
if options.no_wrap:
|
| 757 |
+
wrapped_lines = [segments]
|
| 758 |
+
else:
|
| 759 |
+
wrapped_lines = [
|
| 760 |
+
_Segment.adjust_line_length(
|
| 761 |
+
segments,
|
| 762 |
+
render_options.max_width,
|
| 763 |
+
style=background_style,
|
| 764 |
+
pad=not transparent_background,
|
| 765 |
+
)
|
| 766 |
+
]
|
| 767 |
+
|
| 768 |
+
if self.line_numbers:
|
| 769 |
+
wrapped_line_left_pad = _Segment(
|
| 770 |
+
" " * numbers_column_width + " ", background_style
|
| 771 |
+
)
|
| 772 |
+
for first, wrapped_line in loop_first(wrapped_lines):
|
| 773 |
+
if first:
|
| 774 |
+
line_column = str(line_no).rjust(numbers_column_width - 2) + " "
|
| 775 |
+
if highlight_line(line_no):
|
| 776 |
+
yield _Segment(line_pointer, Style(color="red"))
|
| 777 |
+
yield _Segment(line_column, highlight_number_style)
|
| 778 |
+
else:
|
| 779 |
+
yield _Segment(" ", highlight_number_style)
|
| 780 |
+
yield _Segment(line_column, number_style)
|
| 781 |
+
else:
|
| 782 |
+
yield wrapped_line_left_pad
|
| 783 |
+
yield from wrapped_line
|
| 784 |
+
yield new_line
|
| 785 |
+
else:
|
| 786 |
+
for wrapped_line in wrapped_lines:
|
| 787 |
+
yield from wrapped_line
|
| 788 |
+
yield new_line
|
| 789 |
+
|
| 790 |
+
def _apply_stylized_ranges(self, text: Text) -> None:
|
| 791 |
+
"""
|
| 792 |
+
Apply stylized ranges to a text instance,
|
| 793 |
+
using the given code to determine the right portion to apply the style to.
|
| 794 |
+
|
| 795 |
+
Args:
|
| 796 |
+
text (Text): Text instance to apply the style to.
|
| 797 |
+
"""
|
| 798 |
+
code = text.plain
|
| 799 |
+
newlines_offsets = [
|
| 800 |
+
# Let's add outer boundaries at each side of the list:
|
| 801 |
+
0,
|
| 802 |
+
# N.B. using "\n" here is much faster than using metacharacters such as "^" or "\Z":
|
| 803 |
+
*[
|
| 804 |
+
match.start() + 1
|
| 805 |
+
for match in re.finditer("\n", code, flags=re.MULTILINE)
|
| 806 |
+
],
|
| 807 |
+
len(code) + 1,
|
| 808 |
+
]
|
| 809 |
+
|
| 810 |
+
for stylized_range in self._stylized_ranges:
|
| 811 |
+
start = _get_code_index_for_syntax_position(
|
| 812 |
+
newlines_offsets, stylized_range.start
|
| 813 |
+
)
|
| 814 |
+
end = _get_code_index_for_syntax_position(
|
| 815 |
+
newlines_offsets, stylized_range.end
|
| 816 |
+
)
|
| 817 |
+
if start is not None and end is not None:
|
| 818 |
+
if stylized_range.style_before:
|
| 819 |
+
text.stylize_before(stylized_range.style, start, end)
|
| 820 |
+
else:
|
| 821 |
+
text.stylize(stylized_range.style, start, end)
|
| 822 |
+
|
| 823 |
+
def _process_code(self, code: str) -> Tuple[bool, str]:
|
| 824 |
+
"""
|
| 825 |
+
Applies various processing to a raw code string
|
| 826 |
+
(normalises it so it always ends with a line return, dedents it if necessary, etc.)
|
| 827 |
+
|
| 828 |
+
Args:
|
| 829 |
+
code (str): The raw code string to process
|
| 830 |
+
|
| 831 |
+
Returns:
|
| 832 |
+
Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return,
|
| 833 |
+
while the string is the processed code.
|
| 834 |
+
"""
|
| 835 |
+
ends_on_nl = code.endswith("\n")
|
| 836 |
+
processed_code = code if ends_on_nl else code + "\n"
|
| 837 |
+
processed_code = (
|
| 838 |
+
textwrap.dedent(processed_code) if self.dedent else processed_code
|
| 839 |
+
)
|
| 840 |
+
processed_code = processed_code.expandtabs(self.tab_size)
|
| 841 |
+
return ends_on_nl, processed_code
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
def _get_code_index_for_syntax_position(
|
| 845 |
+
newlines_offsets: Sequence[int], position: SyntaxPosition
|
| 846 |
+
) -> Optional[int]:
|
| 847 |
+
"""
|
| 848 |
+
Returns the index of the code string for the given positions.
|
| 849 |
+
|
| 850 |
+
Args:
|
| 851 |
+
newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet.
|
| 852 |
+
position (SyntaxPosition): The position to search for.
|
| 853 |
+
|
| 854 |
+
Returns:
|
| 855 |
+
Optional[int]: The index of the code string for this position, or `None`
|
| 856 |
+
if the given position's line number is out of range (if it's the column that is out of range
|
| 857 |
+
we silently clamp its value so that it reaches the end of the line)
|
| 858 |
+
"""
|
| 859 |
+
lines_count = len(newlines_offsets)
|
| 860 |
+
|
| 861 |
+
line_number, column_index = position
|
| 862 |
+
if line_number > lines_count or len(newlines_offsets) < (line_number + 1):
|
| 863 |
+
return None # `line_number` is out of range
|
| 864 |
+
line_index = line_number - 1
|
| 865 |
+
line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1
|
| 866 |
+
# If `column_index` is out of range: let's silently clamp it:
|
| 867 |
+
column_index = min(line_length, column_index)
|
| 868 |
+
return newlines_offsets[line_index] + column_index
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
if __name__ == "__main__": # pragma: no cover
|
| 872 |
+
import argparse
|
| 873 |
+
import sys
|
| 874 |
+
|
| 875 |
+
parser = argparse.ArgumentParser(
|
| 876 |
+
description="Render syntax to the console with Rich"
|
| 877 |
+
)
|
| 878 |
+
parser.add_argument(
|
| 879 |
+
"path",
|
| 880 |
+
metavar="PATH",
|
| 881 |
+
help="path to file, or - for stdin",
|
| 882 |
+
)
|
| 883 |
+
parser.add_argument(
|
| 884 |
+
"-c",
|
| 885 |
+
"--force-color",
|
| 886 |
+
dest="force_color",
|
| 887 |
+
action="store_true",
|
| 888 |
+
default=None,
|
| 889 |
+
help="force color for non-terminals",
|
| 890 |
+
)
|
| 891 |
+
parser.add_argument(
|
| 892 |
+
"-i",
|
| 893 |
+
"--indent-guides",
|
| 894 |
+
dest="indent_guides",
|
| 895 |
+
action="store_true",
|
| 896 |
+
default=False,
|
| 897 |
+
help="display indent guides",
|
| 898 |
+
)
|
| 899 |
+
parser.add_argument(
|
| 900 |
+
"-l",
|
| 901 |
+
"--line-numbers",
|
| 902 |
+
dest="line_numbers",
|
| 903 |
+
action="store_true",
|
| 904 |
+
help="render line numbers",
|
| 905 |
+
)
|
| 906 |
+
parser.add_argument(
|
| 907 |
+
"-w",
|
| 908 |
+
"--width",
|
| 909 |
+
type=int,
|
| 910 |
+
dest="width",
|
| 911 |
+
default=None,
|
| 912 |
+
help="width of output (default will auto-detect)",
|
| 913 |
+
)
|
| 914 |
+
parser.add_argument(
|
| 915 |
+
"-r",
|
| 916 |
+
"--wrap",
|
| 917 |
+
dest="word_wrap",
|
| 918 |
+
action="store_true",
|
| 919 |
+
default=False,
|
| 920 |
+
help="word wrap long lines",
|
| 921 |
+
)
|
| 922 |
+
parser.add_argument(
|
| 923 |
+
"-s",
|
| 924 |
+
"--soft-wrap",
|
| 925 |
+
action="store_true",
|
| 926 |
+
dest="soft_wrap",
|
| 927 |
+
default=False,
|
| 928 |
+
help="enable soft wrapping mode",
|
| 929 |
+
)
|
| 930 |
+
parser.add_argument(
|
| 931 |
+
"-t", "--theme", dest="theme", default="monokai", help="pygments theme"
|
| 932 |
+
)
|
| 933 |
+
parser.add_argument(
|
| 934 |
+
"-b",
|
| 935 |
+
"--background-color",
|
| 936 |
+
dest="background_color",
|
| 937 |
+
default=None,
|
| 938 |
+
help="Override background color",
|
| 939 |
+
)
|
| 940 |
+
parser.add_argument(
|
| 941 |
+
"-x",
|
| 942 |
+
"--lexer",
|
| 943 |
+
default=None,
|
| 944 |
+
dest="lexer_name",
|
| 945 |
+
help="Lexer name",
|
| 946 |
+
)
|
| 947 |
+
parser.add_argument(
|
| 948 |
+
"-p", "--padding", type=int, default=0, dest="padding", help="Padding"
|
| 949 |
+
)
|
| 950 |
+
parser.add_argument(
|
| 951 |
+
"--highlight-line",
|
| 952 |
+
type=int,
|
| 953 |
+
default=None,
|
| 954 |
+
dest="highlight_line",
|
| 955 |
+
help="The line number (not index!) to highlight",
|
| 956 |
+
)
|
| 957 |
+
args = parser.parse_args()
|
| 958 |
+
|
| 959 |
+
from rich.console import Console
|
| 960 |
+
|
| 961 |
+
console = Console(force_terminal=args.force_color, width=args.width)
|
| 962 |
+
|
| 963 |
+
if args.path == "-":
|
| 964 |
+
code = sys.stdin.read()
|
| 965 |
+
syntax = Syntax(
|
| 966 |
+
code=code,
|
| 967 |
+
lexer=args.lexer_name,
|
| 968 |
+
line_numbers=args.line_numbers,
|
| 969 |
+
word_wrap=args.word_wrap,
|
| 970 |
+
theme=args.theme,
|
| 971 |
+
background_color=args.background_color,
|
| 972 |
+
indent_guides=args.indent_guides,
|
| 973 |
+
padding=args.padding,
|
| 974 |
+
highlight_lines={args.highlight_line},
|
| 975 |
+
)
|
| 976 |
+
else:
|
| 977 |
+
syntax = Syntax.from_path(
|
| 978 |
+
args.path,
|
| 979 |
+
lexer=args.lexer_name,
|
| 980 |
+
line_numbers=args.line_numbers,
|
| 981 |
+
word_wrap=args.word_wrap,
|
| 982 |
+
theme=args.theme,
|
| 983 |
+
background_color=args.background_color,
|
| 984 |
+
indent_guides=args.indent_guides,
|
| 985 |
+
padding=args.padding,
|
| 986 |
+
highlight_lines={args.highlight_line},
|
| 987 |
+
)
|
| 988 |
+
console.print(syntax, soft_wrap=args.soft_wrap)
|