Amar-Aly commited on
Commit
8e535fb
·
verified ·
1 Parent(s): 9f27be9

Add files using upload-large-folder tool

Browse files
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/errors.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ConsoleError(Exception):
2
+ """An error in console operation."""
3
+
4
+
5
+ class StyleError(Exception):
6
+ """An error in styles."""
7
+
8
+
9
+ class StyleSyntaxError(ConsoleError):
10
+ """Style was badly formatted."""
11
+
12
+
13
+ class MissingStyle(StyleError):
14
+ """No such style."""
15
+
16
+
17
+ class StyleStackError(ConsoleError):
18
+ """Style stack is invalid."""
19
+
20
+
21
+ class NotRenderableError(ConsoleError):
22
+ """Object is not renderable."""
23
+
24
+
25
+ class MarkupError(ConsoleError):
26
+ """Markup was badly formatted."""
27
+
28
+
29
+ class LiveError(ConsoleError):
30
+ """Error related to Live display."""
31
+
32
+
33
+ class NoAltScreen(ConsoleError):
34
+ """Alt screen mode was required."""
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/file_proxy.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from typing import IO, TYPE_CHECKING, Any, List
3
+
4
+ from .ansi import AnsiDecoder
5
+ from .text import Text
6
+
7
+ if TYPE_CHECKING:
8
+ from .console import Console
9
+
10
+
11
+ class FileProxy(io.TextIOBase):
12
+ """Wraps a file (e.g. sys.stdout) and redirects writes to a console."""
13
+
14
+ def __init__(self, console: "Console", file: IO[str]) -> None:
15
+ self.__console = console
16
+ self.__file = file
17
+ self.__buffer: List[str] = []
18
+ self.__ansi_decoder = AnsiDecoder()
19
+
20
+ @property
21
+ def rich_proxied_file(self) -> IO[str]:
22
+ """Get proxied file."""
23
+ return self.__file
24
+
25
+ def __getattr__(self, name: str) -> Any:
26
+ return getattr(self.__file, name)
27
+
28
+ def write(self, text: str) -> int:
29
+ if not isinstance(text, str):
30
+ raise TypeError(f"write() argument must be str, not {type(text).__name__}")
31
+ buffer = self.__buffer
32
+ lines: List[str] = []
33
+ while text:
34
+ line, new_line, text = text.partition("\n")
35
+ if new_line:
36
+ lines.append("".join(buffer) + line)
37
+ buffer.clear()
38
+ else:
39
+ buffer.append(line)
40
+ break
41
+ if lines:
42
+ console = self.__console
43
+ with console:
44
+ output = Text("\n").join(
45
+ self.__ansi_decoder.decode_line(line) for line in lines
46
+ )
47
+ console.print(output)
48
+ return len(text)
49
+
50
+ def flush(self) -> None:
51
+ output = "".join(self.__buffer)
52
+ if output:
53
+ self.__console.print(output)
54
+ del self.__buffer[:]
55
+
56
+ def fileno(self) -> int:
57
+ return self.__file.fileno()
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/filesize.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2
2
+
3
+ The functions declared in this module should cover the different
4
+ use cases needed to generate a string representation of a file size
5
+ using several different units. Since there are many standards regarding
6
+ file size units, three different functions have been implemented.
7
+
8
+ See Also:
9
+ * `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_
10
+
11
+ """
12
+
13
+ __all__ = ["decimal"]
14
+
15
+ from typing import Iterable, List, Optional, Tuple
16
+
17
+
18
+ def _to_str(
19
+ size: int,
20
+ suffixes: Iterable[str],
21
+ base: int,
22
+ *,
23
+ precision: Optional[int] = 1,
24
+ separator: Optional[str] = " ",
25
+ ) -> str:
26
+ if size == 1:
27
+ return "1 byte"
28
+ elif size < base:
29
+ return f"{size:,} bytes"
30
+
31
+ for i, suffix in enumerate(suffixes, 2): # noqa: B007
32
+ unit = base**i
33
+ if size < unit:
34
+ break
35
+ return "{:,.{precision}f}{separator}{}".format(
36
+ (base * size / unit),
37
+ suffix,
38
+ precision=precision,
39
+ separator=separator,
40
+ )
41
+
42
+
43
+ def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:
44
+ """Pick a suffix and base for the given size."""
45
+ for i, suffix in enumerate(suffixes):
46
+ unit = base**i
47
+ if size < unit * base:
48
+ break
49
+ return unit, suffix
50
+
51
+
52
+ def decimal(
53
+ size: int,
54
+ *,
55
+ precision: Optional[int] = 1,
56
+ separator: Optional[str] = " ",
57
+ ) -> str:
58
+ """Convert a filesize in to a string (powers of 1000, SI prefixes).
59
+
60
+ In this convention, ``1000 B = 1 kB``.
61
+
62
+ This is typically the format used to advertise the storage
63
+ capacity of USB flash drives and the like (*256 MB* meaning
64
+ actually a storage capacity of more than *256 000 000 B*),
65
+ or used by **Mac OS X** since v10.6 to report file sizes.
66
+
67
+ Arguments:
68
+ int (size): A file size.
69
+ int (precision): The number of decimal places to include (default = 1).
70
+ str (separator): The string to separate the value from the units (default = " ").
71
+
72
+ Returns:
73
+ `str`: A string containing a abbreviated file size and units.
74
+
75
+ Example:
76
+ >>> filesize.decimal(30000)
77
+ '30.0 kB'
78
+ >>> filesize.decimal(30000, precision=2, separator="")
79
+ '30.00kB'
80
+
81
+ """
82
+ return _to_str(
83
+ size,
84
+ ("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"),
85
+ 1000,
86
+ precision=precision,
87
+ separator=separator,
88
+ )
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/highlighter.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from abc import ABC, abstractmethod
3
+ from typing import ClassVar, Sequence, Union
4
+
5
+ from .text import Span, Text
6
+
7
+
8
+ def _combine_regex(*regexes: str) -> str:
9
+ """Combine a number of regexes in to a single regex.
10
+
11
+ Returns:
12
+ str: New regex with all regexes ORed together.
13
+ """
14
+ return "|".join(regexes)
15
+
16
+
17
+ class Highlighter(ABC):
18
+ """Abstract base class for highlighters."""
19
+
20
+ def __call__(self, text: Union[str, Text]) -> Text:
21
+ """Highlight a str or Text instance.
22
+
23
+ Args:
24
+ text (Union[str, ~Text]): Text to highlight.
25
+
26
+ Raises:
27
+ TypeError: If not called with text or str.
28
+
29
+ Returns:
30
+ Text: A test instance with highlighting applied.
31
+ """
32
+ if isinstance(text, str):
33
+ highlight_text = Text(text)
34
+ elif isinstance(text, Text):
35
+ highlight_text = text.copy()
36
+ else:
37
+ raise TypeError(f"str or Text instance required, not {text!r}")
38
+ self.highlight(highlight_text)
39
+ return highlight_text
40
+
41
+ @abstractmethod
42
+ def highlight(self, text: Text) -> None:
43
+ """Apply highlighting in place to text.
44
+
45
+ Args:
46
+ text (~Text): A text object highlight.
47
+ """
48
+
49
+
50
+ class NullHighlighter(Highlighter):
51
+ """A highlighter object that doesn't highlight.
52
+
53
+ May be used to disable highlighting entirely.
54
+
55
+ """
56
+
57
+ def highlight(self, text: Text) -> None:
58
+ """Nothing to do"""
59
+
60
+
61
+ class RegexHighlighter(Highlighter):
62
+ """Applies highlighting from a list of regular expressions."""
63
+
64
+ highlights: ClassVar[Sequence[str]] = []
65
+ base_style: ClassVar[str] = ""
66
+
67
+ def highlight(self, text: Text) -> None:
68
+ """Highlight :class:`rich.text.Text` using regular expressions.
69
+
70
+ Args:
71
+ text (~Text): Text to highlighted.
72
+
73
+ """
74
+
75
+ highlight_regex = text.highlight_regex
76
+ for re_highlight in self.highlights:
77
+ highlight_regex(re_highlight, style_prefix=self.base_style)
78
+
79
+
80
+ class ReprHighlighter(RegexHighlighter):
81
+ """Highlights the text typically produced from ``__repr__`` methods."""
82
+
83
+ base_style = "repr."
84
+ highlights: ClassVar[Sequence[str]] = [
85
+ r"(?P<tag_start><)(?P<tag_name>[-\w.:|]*)(?P<tag_contents>[\w\W]*)(?P<tag_end>>)",
86
+ r'(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>"?[\w_]+"?)?',
87
+ r"(?P<brace>[][{}()])",
88
+ _combine_regex(
89
+ r"(?P<ipv4>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})",
90
+ r"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})",
91
+ r"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})",
92
+ r"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})",
93
+ r"(?P<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})",
94
+ r"(?P<call>[\w.]*?)\(",
95
+ r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b",
96
+ r"(?P<ellipsis>\.\.\.)",
97
+ r"(?P<number_complex>(?<!\w)(?:\-?[0-9]+\.?[0-9]*(?:e[-+]?\d+?)?)(?:[-+](?:[0-9]+\.?[0-9]*(?:e[-+]?\d+)?))?j)",
98
+ r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[-+]?\d+?)?\b|0x[0-9a-fA-F]*)",
99
+ r"(?P<path>\B(/[-\w._+]+)*\/)(?P<filename>[-\w._+]*)?",
100
+ r"(?<![\\\w])(?P<str>b?'''.*?(?<!\\)'''|b?'.*?(?<!\\)'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
101
+ r"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~@]*)",
102
+ ),
103
+ ]
104
+
105
+
106
+ class JSONHighlighter(RegexHighlighter):
107
+ """Highlights JSON"""
108
+
109
+ # Captures the start and end of JSON strings, handling escaped quotes
110
+ JSON_STR = r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")"
111
+ JSON_WHITESPACE = {" ", "\n", "\r", "\t"}
112
+
113
+ base_style: ClassVar[str] = "json."
114
+ highlights: ClassVar[Sequence[str]] = [
115
+ _combine_regex(
116
+ r"(?P<brace>[\{\[\(\)\]\}])",
117
+ r"\b(?P<bool_true>true)\b|\b(?P<bool_false>false)\b|\b(?P<null>null)\b",
118
+ r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)",
119
+ JSON_STR,
120
+ ),
121
+ ]
122
+
123
+ def highlight(self, text: Text) -> None:
124
+ super().highlight(text)
125
+
126
+ # Additional work to handle highlighting JSON keys
127
+ plain = text.plain
128
+ append = text.spans.append
129
+ whitespace = self.JSON_WHITESPACE
130
+ for match in re.finditer(self.JSON_STR, plain):
131
+ start, end = match.span()
132
+ cursor = end
133
+ while cursor < len(plain):
134
+ char = plain[cursor]
135
+ cursor += 1
136
+ if char == ":":
137
+ append(Span(start, end, "json.key"))
138
+ elif char in whitespace:
139
+ continue
140
+ break
141
+
142
+
143
+ class ISO8601Highlighter(RegexHighlighter):
144
+ """Highlights the ISO8601 date time strings.
145
+ Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html
146
+ """
147
+
148
+ base_style: ClassVar[str] = "iso8601."
149
+ highlights: ClassVar[Sequence[str]] = [
150
+ #
151
+ # Dates
152
+ #
153
+ # Calendar month (e.g. 2008-08). The hyphen is required
154
+ r"^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$",
155
+ # Calendar date w/o hyphens (e.g. 20080830)
156
+ r"^(?P<date>(?P<year>[0-9]{4})(?P<month>1[0-2]|0[1-9])(?P<day>3[01]|0[1-9]|[12][0-9]))$",
157
+ # Ordinal date (e.g. 2008-243). The hyphen is optional
158
+ r"^(?P<date>(?P<year>[0-9]{4})-?(?P<day>36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$",
159
+ #
160
+ # Weeks
161
+ #
162
+ # Week of the year (e.g., 2008-W35). The hyphen is optional
163
+ r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9]))$",
164
+ # Week date (e.g., 2008-W35-6). The hyphens are optional
165
+ r"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9])-?(?P<day>[1-7]))$",
166
+ #
167
+ # Times
168
+ #
169
+ # Hours and minutes (e.g., 17:21). The colon is optional
170
+ r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):?(?P<minute>[0-5][0-9]))$",
171
+ # Hours, minutes, and seconds w/o colons (e.g., 172159)
172
+ r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))$",
173
+ # Time zone designator (e.g., Z, +07 or +07:00). The colons and the minutes are optional
174
+ r"^(?P<timezone>(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?))$",
175
+ # Hours, minutes, and seconds with time zone designator (e.g., 17:21:59+07:00).
176
+ # All the colons are optional. The minutes in the time zone designator are also optional
177
+ r"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$",
178
+ #
179
+ # Date and Time
180
+ #
181
+ # Calendar date with hours, minutes, and seconds (e.g., 2008-08-30 17:21:59 or 20080830 172159).
182
+ # A space is required between the date and the time. The hyphens and colons are optional.
183
+ # This regex matches dates and times that specify some hyphens or colons but omit others.
184
+ # This does not follow ISO 8601
185
+ r"^(?P<date>(?P<year>[0-9]{4})(?P<hyphen>-)?(?P<month>1[0-2]|0[1-9])(?(hyphen)-)(?P<day>3[01]|0[1-9]|[12][0-9])) (?P<time>(?P<hour>2[0-3]|[01][0-9])(?(hyphen):)(?P<minute>[0-5][0-9])(?(hyphen):)(?P<second>[0-5][0-9]))$",
186
+ #
187
+ # XML Schema dates and times
188
+ #
189
+ # Date, with optional time zone (e.g., 2008-08-30 or 2008-08-30+07:00).
190
+ # Hyphens are required. This is the XML Schema 'date' type
191
+ r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$",
192
+ # Time, with optional fractional seconds and time zone (e.g., 01:45:36 or 01:45:36.123+07:00).
193
+ # There is no limit on the number of digits for the fractional seconds. This is the XML Schema 'time' type
194
+ r"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<frac>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$",
195
+ # Date and time, with optional fractional seconds and time zone (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z).
196
+ # This is the XML Schema 'dateTime' type
197
+ r"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))T(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<ms>\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$",
198
+ ]
199
+
200
+
201
+ if __name__ == "__main__": # pragma: no cover
202
+ from .console import Console
203
+
204
+ console = Console()
205
+ console.print("[bold green]hello world![/bold green]")
206
+ console.print("'[bold green]hello world![/bold green]'")
207
+
208
+ console.print(" /foo")
209
+ console.print("/foo/")
210
+ console.print("/foo/bar")
211
+ console.print("foo/bar/baz")
212
+
213
+ console.print("/foo/bar/baz?foo=bar+egg&egg=baz")
214
+ console.print("/foo/bar/baz/")
215
+ console.print("/foo/bar/baz/egg")
216
+ console.print("/foo/bar/baz/egg.py")
217
+ console.print("/foo/bar/baz/egg.py word")
218
+ console.print(" /foo/bar/baz/egg.py word")
219
+ console.print("foo /foo/bar/baz/egg.py word")
220
+ console.print("foo /foo/bar/ba._++z/egg+.py word")
221
+ console.print("https://example.org?foo=bar#header")
222
+
223
+ console.print(1234567.34)
224
+ console.print(1 / 2)
225
+ console.print(-1 / 123123123123)
226
+
227
+ console.print(
228
+ "127.0.1.1 bar 192.168.1.4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 foo"
229
+ )
230
+ import json
231
+
232
+ console.print_json(json.dumps(obj={"name": "apple", "count": 1}), indent=None)
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/json.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from json import loads, dumps
3
+ from typing import Any, Callable, Optional, Union
4
+
5
+ from .text import Text
6
+ from .highlighter import JSONHighlighter, NullHighlighter
7
+
8
+
9
+ class JSON:
10
+ """A renderable which pretty prints JSON.
11
+
12
+ Args:
13
+ json (str): JSON encoded data.
14
+ indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
15
+ highlight (bool, optional): Enable highlighting. Defaults to True.
16
+ skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
17
+ ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
18
+ check_circular (bool, optional): Check for circular references. Defaults to True.
19
+ allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
20
+ default (Callable, optional): A callable that converts values that can not be encoded
21
+ in to something that can be JSON encoded. Defaults to None.
22
+ sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ json: str,
28
+ indent: Union[None, int, str] = 2,
29
+ highlight: bool = True,
30
+ skip_keys: bool = False,
31
+ ensure_ascii: bool = False,
32
+ check_circular: bool = True,
33
+ allow_nan: bool = True,
34
+ default: Optional[Callable[[Any], Any]] = None,
35
+ sort_keys: bool = False,
36
+ ) -> None:
37
+ data = loads(json)
38
+ json = dumps(
39
+ data,
40
+ indent=indent,
41
+ skipkeys=skip_keys,
42
+ ensure_ascii=ensure_ascii,
43
+ check_circular=check_circular,
44
+ allow_nan=allow_nan,
45
+ default=default,
46
+ sort_keys=sort_keys,
47
+ )
48
+ highlighter = JSONHighlighter() if highlight else NullHighlighter()
49
+ self.text = highlighter(json)
50
+ self.text.no_wrap = True
51
+ self.text.overflow = None
52
+
53
+ @classmethod
54
+ def from_data(
55
+ cls,
56
+ data: Any,
57
+ indent: Union[None, int, str] = 2,
58
+ highlight: bool = True,
59
+ skip_keys: bool = False,
60
+ ensure_ascii: bool = False,
61
+ check_circular: bool = True,
62
+ allow_nan: bool = True,
63
+ default: Optional[Callable[[Any], Any]] = None,
64
+ sort_keys: bool = False,
65
+ ) -> "JSON":
66
+ """Encodes a JSON object from arbitrary data.
67
+
68
+ Args:
69
+ data (Any): An object that may be encoded in to JSON
70
+ indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
71
+ highlight (bool, optional): Enable highlighting. Defaults to True.
72
+ default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None.
73
+ skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
74
+ ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
75
+ check_circular (bool, optional): Check for circular references. Defaults to True.
76
+ allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
77
+ default (Callable, optional): A callable that converts values that can not be encoded
78
+ in to something that can be JSON encoded. Defaults to None.
79
+ sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
80
+
81
+ Returns:
82
+ JSON: New JSON object from the given data.
83
+ """
84
+ json_instance: "JSON" = cls.__new__(cls)
85
+ json = dumps(
86
+ data,
87
+ indent=indent,
88
+ skipkeys=skip_keys,
89
+ ensure_ascii=ensure_ascii,
90
+ check_circular=check_circular,
91
+ allow_nan=allow_nan,
92
+ default=default,
93
+ sort_keys=sort_keys,
94
+ )
95
+ highlighter = JSONHighlighter() if highlight else NullHighlighter()
96
+ json_instance.text = highlighter(json)
97
+ json_instance.text.no_wrap = True
98
+ json_instance.text.overflow = None
99
+ return json_instance
100
+
101
+ def __rich__(self) -> Text:
102
+ return self.text
103
+
104
+
105
+ if __name__ == "__main__":
106
+ import argparse
107
+ import sys
108
+
109
+ parser = argparse.ArgumentParser(description="Pretty print json")
110
+ parser.add_argument(
111
+ "path",
112
+ metavar="PATH",
113
+ help="path to file, or - for stdin",
114
+ )
115
+ parser.add_argument(
116
+ "-i",
117
+ "--indent",
118
+ metavar="SPACES",
119
+ type=int,
120
+ help="Number of spaces in an indent",
121
+ default=2,
122
+ )
123
+ args = parser.parse_args()
124
+
125
+ from rich.console import Console
126
+
127
+ console = Console()
128
+ error_console = Console(stderr=True)
129
+
130
+ try:
131
+ if args.path == "-":
132
+ json_data = sys.stdin.read()
133
+ else:
134
+ json_data = Path(args.path).read_text()
135
+ except Exception as error:
136
+ error_console.print(f"Unable to read {args.path!r}; {error}")
137
+ sys.exit(-1)
138
+
139
+ console.print(JSON(json_data, indent=args.indent), soft_wrap=True)
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/jupyter.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence
2
+
3
+ if TYPE_CHECKING:
4
+ from rich.console import ConsoleRenderable
5
+
6
+ from . import get_console
7
+ from .segment import Segment
8
+ from .terminal_theme import DEFAULT_TERMINAL_THEME
9
+
10
+ if TYPE_CHECKING:
11
+ from rich.console import ConsoleRenderable
12
+
13
+ JUPYTER_HTML_FORMAT = """\
14
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
15
+ """
16
+
17
+
18
+ class JupyterRenderable:
19
+ """A shim to write html to Jupyter notebook."""
20
+
21
+ def __init__(self, html: str, text: str) -> None:
22
+ self.html = html
23
+ self.text = text
24
+
25
+ def _repr_mimebundle_(
26
+ self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any
27
+ ) -> Dict[str, str]:
28
+ data = {"text/plain": self.text, "text/html": self.html}
29
+ if include:
30
+ data = {k: v for (k, v) in data.items() if k in include}
31
+ if exclude:
32
+ data = {k: v for (k, v) in data.items() if k not in exclude}
33
+ return data
34
+
35
+
36
+ class JupyterMixin:
37
+ """Add to an Rich renderable to make it render in Jupyter notebook."""
38
+
39
+ __slots__ = ()
40
+
41
+ def _repr_mimebundle_(
42
+ self: "ConsoleRenderable",
43
+ include: Sequence[str],
44
+ exclude: Sequence[str],
45
+ **kwargs: Any,
46
+ ) -> Dict[str, str]:
47
+ console = get_console()
48
+ segments = list(console.render(self, console.options))
49
+ html = _render_segments(segments)
50
+ text = console._render_buffer(segments)
51
+ data = {"text/plain": text, "text/html": html}
52
+ if include:
53
+ data = {k: v for (k, v) in data.items() if k in include}
54
+ if exclude:
55
+ data = {k: v for (k, v) in data.items() if k not in exclude}
56
+ return data
57
+
58
+
59
+ def _render_segments(segments: Iterable[Segment]) -> str:
60
+ def escape(text: str) -> str:
61
+ """Escape html."""
62
+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
63
+
64
+ fragments: List[str] = []
65
+ append_fragment = fragments.append
66
+ theme = DEFAULT_TERMINAL_THEME
67
+ for text, style, control in Segment.simplify(segments):
68
+ if control:
69
+ continue
70
+ text = escape(text)
71
+ if style:
72
+ rule = style.get_html_style(theme)
73
+ text = f'<span style="{rule}">{text}</span>' if rule else text
74
+ if style.link:
75
+ text = f'<a href="{style.link}" target="_blank">{text}</a>'
76
+ append_fragment(text)
77
+
78
+ code = "".join(fragments)
79
+ html = JUPYTER_HTML_FORMAT.format(code=code)
80
+
81
+ return html
82
+
83
+
84
+ def display(segments: Iterable[Segment], text: str) -> None:
85
+ """Render segments to Jupyter."""
86
+ html = _render_segments(segments)
87
+ jupyter_renderable = JupyterRenderable(html, text)
88
+ try:
89
+ from IPython.display import display as ipython_display
90
+
91
+ ipython_display(jupyter_renderable)
92
+ except ModuleNotFoundError:
93
+ # Handle the case where the Console has force_jupyter=True,
94
+ # but IPython is not installed.
95
+ pass
96
+
97
+
98
+ def print(*args: Any, **kwargs: Any) -> None:
99
+ """Proxy for Console print."""
100
+ console = get_console()
101
+ return console.print(*args, **kwargs)
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/layout.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from itertools import islice
3
+ from operator import itemgetter
4
+ from threading import RLock
5
+ from typing import (
6
+ TYPE_CHECKING,
7
+ Dict,
8
+ Iterable,
9
+ List,
10
+ NamedTuple,
11
+ Optional,
12
+ Sequence,
13
+ Tuple,
14
+ Union,
15
+ )
16
+
17
+ from ._ratio import ratio_resolve
18
+ from .align import Align
19
+ from .console import Console, ConsoleOptions, RenderableType, RenderResult
20
+ from .highlighter import ReprHighlighter
21
+ from .panel import Panel
22
+ from .pretty import Pretty
23
+ from .region import Region
24
+ from .repr import Result, rich_repr
25
+ from .segment import Segment
26
+ from .style import StyleType
27
+
28
+ if TYPE_CHECKING:
29
+ from rich.tree import Tree
30
+
31
+
32
+ class LayoutRender(NamedTuple):
33
+ """An individual layout render."""
34
+
35
+ region: Region
36
+ render: List[List[Segment]]
37
+
38
+
39
+ RegionMap = Dict["Layout", Region]
40
+ RenderMap = Dict["Layout", LayoutRender]
41
+
42
+
43
+ class LayoutError(Exception):
44
+ """Layout related error."""
45
+
46
+
47
+ class NoSplitter(LayoutError):
48
+ """Requested splitter does not exist."""
49
+
50
+
51
+ class _Placeholder:
52
+ """An internal renderable used as a Layout placeholder."""
53
+
54
+ highlighter = ReprHighlighter()
55
+
56
+ def __init__(self, layout: "Layout", style: StyleType = "") -> None:
57
+ self.layout = layout
58
+ self.style = style
59
+
60
+ def __rich_console__(
61
+ self, console: Console, options: ConsoleOptions
62
+ ) -> RenderResult:
63
+ width = options.max_width
64
+ height = options.height or options.size.height
65
+ layout = self.layout
66
+ title = (
67
+ f"{layout.name!r} ({width} x {height})"
68
+ if layout.name
69
+ else f"({width} x {height})"
70
+ )
71
+ yield Panel(
72
+ Align.center(Pretty(layout), vertical="middle"),
73
+ style=self.style,
74
+ title=self.highlighter(title),
75
+ border_style="blue",
76
+ height=height,
77
+ )
78
+
79
+
80
+ class Splitter(ABC):
81
+ """Base class for a splitter."""
82
+
83
+ name: str = ""
84
+
85
+ @abstractmethod
86
+ def get_tree_icon(self) -> str:
87
+ """Get the icon (emoji) used in layout.tree"""
88
+
89
+ @abstractmethod
90
+ def divide(
91
+ self, children: Sequence["Layout"], region: Region
92
+ ) -> Iterable[Tuple["Layout", Region]]:
93
+ """Divide a region amongst several child layouts.
94
+
95
+ Args:
96
+ children (Sequence(Layout)): A number of child layouts.
97
+ region (Region): A rectangular region to divide.
98
+ """
99
+
100
+
101
+ class RowSplitter(Splitter):
102
+ """Split a layout region in to rows."""
103
+
104
+ name = "row"
105
+
106
+ def get_tree_icon(self) -> str:
107
+ return "[layout.tree.row]⬌"
108
+
109
+ def divide(
110
+ self, children: Sequence["Layout"], region: Region
111
+ ) -> Iterable[Tuple["Layout", Region]]:
112
+ x, y, width, height = region
113
+ render_widths = ratio_resolve(width, children)
114
+ offset = 0
115
+ _Region = Region
116
+ for child, child_width in zip(children, render_widths):
117
+ yield child, _Region(x + offset, y, child_width, height)
118
+ offset += child_width
119
+
120
+
121
+ class ColumnSplitter(Splitter):
122
+ """Split a layout region in to columns."""
123
+
124
+ name = "column"
125
+
126
+ def get_tree_icon(self) -> str:
127
+ return "[layout.tree.column]⬍"
128
+
129
+ def divide(
130
+ self, children: Sequence["Layout"], region: Region
131
+ ) -> Iterable[Tuple["Layout", Region]]:
132
+ x, y, width, height = region
133
+ render_heights = ratio_resolve(height, children)
134
+ offset = 0
135
+ _Region = Region
136
+ for child, child_height in zip(children, render_heights):
137
+ yield child, _Region(x, y + offset, width, child_height)
138
+ offset += child_height
139
+
140
+
141
+ @rich_repr
142
+ class Layout:
143
+ """A renderable to divide a fixed height in to rows or columns.
144
+
145
+ Args:
146
+ renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None.
147
+ name (str, optional): Optional identifier for Layout. Defaults to None.
148
+ size (int, optional): Optional fixed size of layout. Defaults to None.
149
+ minimum_size (int, optional): Minimum size of layout. Defaults to 1.
150
+ ratio (int, optional): Optional ratio for flexible layout. Defaults to 1.
151
+ visible (bool, optional): Visibility of layout. Defaults to True.
152
+ """
153
+
154
+ splitters = {"row": RowSplitter, "column": ColumnSplitter}
155
+
156
+ def __init__(
157
+ self,
158
+ renderable: Optional[RenderableType] = None,
159
+ *,
160
+ name: Optional[str] = None,
161
+ size: Optional[int] = None,
162
+ minimum_size: int = 1,
163
+ ratio: int = 1,
164
+ visible: bool = True,
165
+ ) -> None:
166
+ self._renderable = renderable or _Placeholder(self)
167
+ self.size = size
168
+ self.minimum_size = minimum_size
169
+ self.ratio = ratio
170
+ self.name = name
171
+ self.visible = visible
172
+ self.splitter: Splitter = self.splitters["column"]()
173
+ self._children: List[Layout] = []
174
+ self._render_map: RenderMap = {}
175
+ self._lock = RLock()
176
+
177
+ def __rich_repr__(self) -> Result:
178
+ yield "name", self.name, None
179
+ yield "size", self.size, None
180
+ yield "minimum_size", self.minimum_size, 1
181
+ yield "ratio", self.ratio, 1
182
+
183
+ @property
184
+ def renderable(self) -> RenderableType:
185
+ """Layout renderable."""
186
+ return self if self._children else self._renderable
187
+
188
+ @property
189
+ def children(self) -> List["Layout"]:
190
+ """Gets (visible) layout children."""
191
+ return [child for child in self._children if child.visible]
192
+
193
+ @property
194
+ def map(self) -> RenderMap:
195
+ """Get a map of the last render."""
196
+ return self._render_map
197
+
198
+ def get(self, name: str) -> Optional["Layout"]:
199
+ """Get a named layout, or None if it doesn't exist.
200
+
201
+ Args:
202
+ name (str): Name of layout.
203
+
204
+ Returns:
205
+ Optional[Layout]: Layout instance or None if no layout was found.
206
+ """
207
+ if self.name == name:
208
+ return self
209
+ else:
210
+ for child in self._children:
211
+ named_layout = child.get(name)
212
+ if named_layout is not None:
213
+ return named_layout
214
+ return None
215
+
216
+ def __getitem__(self, name: str) -> "Layout":
217
+ layout = self.get(name)
218
+ if layout is None:
219
+ raise KeyError(f"No layout with name {name!r}")
220
+ return layout
221
+
222
+ @property
223
+ def tree(self) -> "Tree":
224
+ """Get a tree renderable to show layout structure."""
225
+ from rich.styled import Styled
226
+ from rich.table import Table
227
+ from rich.tree import Tree
228
+
229
+ def summary(layout: "Layout") -> Table:
230
+ icon = layout.splitter.get_tree_icon()
231
+
232
+ table = Table.grid(padding=(0, 1, 0, 0))
233
+
234
+ text: RenderableType = (
235
+ Pretty(layout) if layout.visible else Styled(Pretty(layout), "dim")
236
+ )
237
+ table.add_row(icon, text)
238
+ _summary = table
239
+ return _summary
240
+
241
+ layout = self
242
+ tree = Tree(
243
+ summary(layout),
244
+ guide_style=f"layout.tree.{layout.splitter.name}",
245
+ highlight=True,
246
+ )
247
+
248
+ def recurse(tree: "Tree", layout: "Layout") -> None:
249
+ for child in layout._children:
250
+ recurse(
251
+ tree.add(
252
+ summary(child),
253
+ guide_style=f"layout.tree.{child.splitter.name}",
254
+ ),
255
+ child,
256
+ )
257
+
258
+ recurse(tree, self)
259
+ return tree
260
+
261
+ def split(
262
+ self,
263
+ *layouts: Union["Layout", RenderableType],
264
+ splitter: Union[Splitter, str] = "column",
265
+ ) -> None:
266
+ """Split the layout in to multiple sub-layouts.
267
+
268
+ Args:
269
+ *layouts (Layout): Positional arguments should be (sub) Layout instances.
270
+ splitter (Union[Splitter, str]): Splitter instance or name of splitter.
271
+ """
272
+ _layouts = [
273
+ layout if isinstance(layout, Layout) else Layout(layout)
274
+ for layout in layouts
275
+ ]
276
+ try:
277
+ self.splitter = (
278
+ splitter
279
+ if isinstance(splitter, Splitter)
280
+ else self.splitters[splitter]()
281
+ )
282
+ except KeyError:
283
+ raise NoSplitter(f"No splitter called {splitter!r}")
284
+ self._children[:] = _layouts
285
+
286
+ def add_split(self, *layouts: Union["Layout", RenderableType]) -> None:
287
+ """Add a new layout(s) to existing split.
288
+
289
+ Args:
290
+ *layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.
291
+
292
+ """
293
+ _layouts = (
294
+ layout if isinstance(layout, Layout) else Layout(layout)
295
+ for layout in layouts
296
+ )
297
+ self._children.extend(_layouts)
298
+
299
+ def split_row(self, *layouts: Union["Layout", RenderableType]) -> None:
300
+ """Split the layout in to a row (layouts side by side).
301
+
302
+ Args:
303
+ *layouts (Layout): Positional arguments should be (sub) Layout instances.
304
+ """
305
+ self.split(*layouts, splitter="row")
306
+
307
+ def split_column(self, *layouts: Union["Layout", RenderableType]) -> None:
308
+ """Split the layout in to a column (layouts stacked on top of each other).
309
+
310
+ Args:
311
+ *layouts (Layout): Positional arguments should be (sub) Layout instances.
312
+ """
313
+ self.split(*layouts, splitter="column")
314
+
315
+ def unsplit(self) -> None:
316
+ """Reset splits to initial state."""
317
+ del self._children[:]
318
+
319
+ def update(self, renderable: RenderableType) -> None:
320
+ """Update renderable.
321
+
322
+ Args:
323
+ renderable (RenderableType): New renderable object.
324
+ """
325
+ with self._lock:
326
+ self._renderable = renderable
327
+
328
+ def refresh_screen(self, console: "Console", layout_name: str) -> None:
329
+ """Refresh a sub-layout.
330
+
331
+ Args:
332
+ console (Console): Console instance where Layout is to be rendered.
333
+ layout_name (str): Name of layout.
334
+ """
335
+ with self._lock:
336
+ layout = self[layout_name]
337
+ region, _lines = self._render_map[layout]
338
+ (x, y, width, height) = region
339
+ lines = console.render_lines(
340
+ layout, console.options.update_dimensions(width, height)
341
+ )
342
+ self._render_map[layout] = LayoutRender(region, lines)
343
+ console.update_screen_lines(lines, x, y)
344
+
345
+ def _make_region_map(self, width: int, height: int) -> RegionMap:
346
+ """Create a dict that maps layout on to Region."""
347
+ stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]
348
+ push = stack.append
349
+ pop = stack.pop
350
+ layout_regions: List[Tuple[Layout, Region]] = []
351
+ append_layout_region = layout_regions.append
352
+ while stack:
353
+ append_layout_region(pop())
354
+ layout, region = layout_regions[-1]
355
+ children = layout.children
356
+ if children:
357
+ for child_and_region in layout.splitter.divide(children, region):
358
+ push(child_and_region)
359
+
360
+ region_map = {
361
+ layout: region
362
+ for layout, region in sorted(layout_regions, key=itemgetter(1))
363
+ }
364
+ return region_map
365
+
366
+ def render(self, console: Console, options: ConsoleOptions) -> RenderMap:
367
+ """Render the sub_layouts.
368
+
369
+ Args:
370
+ console (Console): Console instance.
371
+ options (ConsoleOptions): Console options.
372
+
373
+ Returns:
374
+ RenderMap: A dict that maps Layout on to a tuple of Region, lines
375
+ """
376
+ render_width = options.max_width
377
+ render_height = options.height or console.height
378
+ region_map = self._make_region_map(render_width, render_height)
379
+ layout_regions = [
380
+ (layout, region)
381
+ for layout, region in region_map.items()
382
+ if not layout.children
383
+ ]
384
+ render_map: Dict["Layout", "LayoutRender"] = {}
385
+ render_lines = console.render_lines
386
+ update_dimensions = options.update_dimensions
387
+
388
+ for layout, region in layout_regions:
389
+ lines = render_lines(
390
+ layout.renderable, update_dimensions(region.width, region.height)
391
+ )
392
+ render_map[layout] = LayoutRender(region, lines)
393
+ return render_map
394
+
395
+ def __rich_console__(
396
+ self, console: Console, options: ConsoleOptions
397
+ ) -> RenderResult:
398
+ with self._lock:
399
+ width = options.max_width or console.width
400
+ height = options.height or console.height
401
+ render_map = self.render(console, options.update_dimensions(width, height))
402
+ self._render_map = render_map
403
+ layout_lines: List[List[Segment]] = [[] for _ in range(height)]
404
+ _islice = islice
405
+ for region, lines in render_map.values():
406
+ _x, y, _layout_width, layout_height = region
407
+ for row, line in zip(
408
+ _islice(layout_lines, y, y + layout_height), lines
409
+ ):
410
+ row.extend(line)
411
+
412
+ new_line = Segment.line()
413
+ for layout_row in layout_lines:
414
+ yield from layout_row
415
+ yield new_line
416
+
417
+
418
+ if __name__ == "__main__":
419
+ from rich.console import Console
420
+
421
+ console = Console()
422
+ layout = Layout()
423
+
424
+ layout.split_column(
425
+ Layout(name="header", size=3),
426
+ Layout(ratio=1, name="main"),
427
+ Layout(size=10, name="footer"),
428
+ )
429
+
430
+ layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
431
+
432
+ layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
433
+
434
+ layout["s2"].split_column(
435
+ Layout(name="top"), Layout(name="middle"), Layout(name="bottom")
436
+ )
437
+
438
+ layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2"))
439
+
440
+ layout["content"].update("foo")
441
+
442
+ console.print(layout)
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/live.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from threading import Event, RLock, Thread
5
+ from types import TracebackType
6
+ from typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, TextIO, Type, cast
7
+
8
+ from . import get_console
9
+ from .console import Console, ConsoleRenderable, Group, RenderableType, RenderHook
10
+ from .control import Control
11
+ from .file_proxy import FileProxy
12
+ from .jupyter import JupyterMixin
13
+ from .live_render import LiveRender, VerticalOverflowMethod
14
+ from .screen import Screen
15
+ from .text import Text
16
+
17
+ if TYPE_CHECKING:
18
+ # Can be replaced with `from typing import Self` in Python 3.11+
19
+ from typing_extensions import Self # pragma: no cover
20
+
21
+
22
+ class _RefreshThread(Thread):
23
+ """A thread that calls refresh() at regular intervals."""
24
+
25
+ def __init__(self, live: "Live", refresh_per_second: float) -> None:
26
+ self.live = live
27
+ self.refresh_per_second = refresh_per_second
28
+ self.done = Event()
29
+ super().__init__(daemon=True)
30
+
31
+ def stop(self) -> None:
32
+ self.done.set()
33
+
34
+ def run(self) -> None:
35
+ while not self.done.wait(1 / self.refresh_per_second):
36
+ with self.live._lock:
37
+ if not self.done.is_set():
38
+ self.live.refresh()
39
+
40
+
41
+ class Live(JupyterMixin, RenderHook):
42
+ """Renders an auto-updating live display of any given renderable.
43
+
44
+ Args:
45
+ renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.
46
+ console (Console, optional): Optional Console instance. Defaults to an internal Console instance writing to stdout.
47
+ screen (bool, optional): Enable alternate screen mode. Defaults to False.
48
+ auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True
49
+ refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4.
50
+ transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False.
51
+ redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
52
+ redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True.
53
+ vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to "ellipsis".
54
+ get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None.
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ renderable: Optional[RenderableType] = None,
60
+ *,
61
+ console: Optional[Console] = None,
62
+ screen: bool = False,
63
+ auto_refresh: bool = True,
64
+ refresh_per_second: float = 4,
65
+ transient: bool = False,
66
+ redirect_stdout: bool = True,
67
+ redirect_stderr: bool = True,
68
+ vertical_overflow: VerticalOverflowMethod = "ellipsis",
69
+ get_renderable: Optional[Callable[[], RenderableType]] = None,
70
+ ) -> None:
71
+ assert refresh_per_second > 0, "refresh_per_second must be > 0"
72
+ self._renderable = renderable
73
+ self.console = console if console is not None else get_console()
74
+ self._screen = screen
75
+ self._alt_screen = False
76
+
77
+ self._redirect_stdout = redirect_stdout
78
+ self._redirect_stderr = redirect_stderr
79
+ self._restore_stdout: Optional[IO[str]] = None
80
+ self._restore_stderr: Optional[IO[str]] = None
81
+
82
+ self._lock = RLock()
83
+ self.ipy_widget: Optional[Any] = None
84
+ self.auto_refresh = auto_refresh
85
+ self._started: bool = False
86
+ self.transient = True if screen else transient
87
+
88
+ self._refresh_thread: Optional[_RefreshThread] = None
89
+ self.refresh_per_second = refresh_per_second
90
+
91
+ self.vertical_overflow = vertical_overflow
92
+ self._get_renderable = get_renderable
93
+ self._live_render = LiveRender(
94
+ self.get_renderable(), vertical_overflow=vertical_overflow
95
+ )
96
+ self._nested = False
97
+
98
+ @property
99
+ def is_started(self) -> bool:
100
+ """Check if live display has been started."""
101
+ return self._started
102
+
103
+ def get_renderable(self) -> RenderableType:
104
+ renderable = (
105
+ self._get_renderable()
106
+ if self._get_renderable is not None
107
+ else self._renderable
108
+ )
109
+ return renderable or ""
110
+
111
+ def start(self, refresh: bool = False) -> None:
112
+ """Start live rendering display.
113
+
114
+ Args:
115
+ refresh (bool, optional): Also refresh. Defaults to False.
116
+ """
117
+ with self._lock:
118
+ if self._started:
119
+ return
120
+ self._started = True
121
+
122
+ if not self.console.set_live(self):
123
+ self._nested = True
124
+ return
125
+
126
+ if self._screen:
127
+ self._alt_screen = self.console.set_alt_screen(True)
128
+ self.console.show_cursor(False)
129
+ self._enable_redirect_io()
130
+ self.console.push_render_hook(self)
131
+ if refresh:
132
+ try:
133
+ self.refresh()
134
+ except Exception:
135
+ # If refresh fails, we want to stop the redirection of sys.stderr,
136
+ # so the error stacktrace is properly displayed in the terminal.
137
+ # (or, if the code that calls Rich captures the exception and wants to display something,
138
+ # let this be displayed in the terminal).
139
+ self.stop()
140
+ raise
141
+ if self.auto_refresh:
142
+ self._refresh_thread = _RefreshThread(self, self.refresh_per_second)
143
+ self._refresh_thread.start()
144
+
145
+ def stop(self) -> None:
146
+ """Stop live rendering display."""
147
+ with self._lock:
148
+ if not self._started:
149
+ return
150
+ self._started = False
151
+ self.console.clear_live()
152
+ if self._nested:
153
+ if not self.transient:
154
+ self.console.print(self.renderable)
155
+ return
156
+
157
+ if self.auto_refresh and self._refresh_thread is not None:
158
+ self._refresh_thread.stop()
159
+ self._refresh_thread = None
160
+ # allow it to fully render on the last even if overflow
161
+ self.vertical_overflow = "visible"
162
+ with self.console:
163
+ try:
164
+ if not self._alt_screen and not self.console.is_jupyter:
165
+ self.refresh()
166
+ finally:
167
+ self._disable_redirect_io()
168
+ self.console.pop_render_hook()
169
+ if (
170
+ not self._alt_screen
171
+ and self.console.is_terminal
172
+ and self._live_render.last_render_height
173
+ ):
174
+ self.console.line()
175
+ self.console.show_cursor(True)
176
+ if self._alt_screen:
177
+ self.console.set_alt_screen(False)
178
+ if self.transient and not self._alt_screen:
179
+ self.console.control(self._live_render.restore_cursor())
180
+ if self.ipy_widget is not None and self.transient:
181
+ self.ipy_widget.close() # pragma: no cover
182
+
183
+ def __enter__(self) -> Self:
184
+ self.start(refresh=self._renderable is not None)
185
+ return self
186
+
187
+ def __exit__(
188
+ self,
189
+ exc_type: Optional[Type[BaseException]],
190
+ exc_val: Optional[BaseException],
191
+ exc_tb: Optional[TracebackType],
192
+ ) -> None:
193
+ self.stop()
194
+
195
+ def _enable_redirect_io(self) -> None:
196
+ """Enable redirecting of stdout / stderr."""
197
+ if self.console.is_terminal or self.console.is_jupyter:
198
+ if self._redirect_stdout and not isinstance(sys.stdout, FileProxy):
199
+ self._restore_stdout = sys.stdout
200
+ sys.stdout = cast("TextIO", FileProxy(self.console, sys.stdout))
201
+ if self._redirect_stderr and not isinstance(sys.stderr, FileProxy):
202
+ self._restore_stderr = sys.stderr
203
+ sys.stderr = cast("TextIO", FileProxy(self.console, sys.stderr))
204
+
205
+ def _disable_redirect_io(self) -> None:
206
+ """Disable redirecting of stdout / stderr."""
207
+ if self._restore_stdout:
208
+ sys.stdout = cast("TextIO", self._restore_stdout)
209
+ self._restore_stdout = None
210
+ if self._restore_stderr:
211
+ sys.stderr = cast("TextIO", self._restore_stderr)
212
+ self._restore_stderr = None
213
+
214
+ @property
215
+ def renderable(self) -> RenderableType:
216
+ """Get the renderable that is being displayed
217
+
218
+ Returns:
219
+ RenderableType: Displayed renderable.
220
+ """
221
+ live_stack = self.console._live_stack
222
+ renderable: RenderableType
223
+ if live_stack and self is live_stack[0]:
224
+ # The first Live instance will render everything in the Live stack
225
+ renderable = Group(*[live.get_renderable() for live in live_stack])
226
+ else:
227
+ renderable = self.get_renderable()
228
+ return Screen(renderable) if self._alt_screen else renderable
229
+
230
+ def update(self, renderable: RenderableType, *, refresh: bool = False) -> None:
231
+ """Update the renderable that is being displayed
232
+
233
+ Args:
234
+ renderable (RenderableType): New renderable to use.
235
+ refresh (bool, optional): Refresh the display. Defaults to False.
236
+ """
237
+ if isinstance(renderable, str):
238
+ renderable = self.console.render_str(renderable)
239
+ with self._lock:
240
+ self._renderable = renderable
241
+ if refresh:
242
+ self.refresh()
243
+
244
+ def refresh(self) -> None:
245
+ """Update the display of the Live Render."""
246
+ with self._lock:
247
+ self._live_render.set_renderable(self.renderable)
248
+ if self._nested:
249
+ if self.console._live_stack:
250
+ self.console._live_stack[0].refresh()
251
+ return
252
+
253
+ if self.console.is_jupyter: # pragma: no cover
254
+ try:
255
+ from IPython.display import display
256
+ from ipywidgets import Output
257
+ except ImportError:
258
+ import warnings
259
+
260
+ warnings.warn('install "ipywidgets" for Jupyter support')
261
+ else:
262
+ if self.ipy_widget is None:
263
+ self.ipy_widget = Output()
264
+ display(self.ipy_widget)
265
+
266
+ with self.ipy_widget:
267
+ self.ipy_widget.clear_output(wait=True)
268
+ self.console.print(self._live_render.renderable)
269
+ elif self.console.is_terminal and not self.console.is_dumb_terminal:
270
+ with self.console:
271
+ self.console.print(Control())
272
+ elif (
273
+ not self._started and not self.transient
274
+ ): # if it is finished allow files or dumb-terminals to see final result
275
+ with self.console:
276
+ self.console.print(Control())
277
+
278
+ def process_renderables(
279
+ self, renderables: List[ConsoleRenderable]
280
+ ) -> List[ConsoleRenderable]:
281
+ """Process renderables to restore cursor and display progress."""
282
+ self._live_render.vertical_overflow = self.vertical_overflow
283
+ if self.console.is_interactive:
284
+ # lock needs acquiring as user can modify live_render renderable at any time unlike in Progress.
285
+ with self._lock:
286
+ reset = (
287
+ Control.home()
288
+ if self._alt_screen
289
+ else self._live_render.position_cursor()
290
+ )
291
+ renderables = [reset, *renderables, self._live_render]
292
+ elif (
293
+ not self._started and not self.transient
294
+ ): # if it is finished render the final output for files or dumb_terminals
295
+ renderables = [*renderables, self._live_render]
296
+
297
+ return renderables
298
+
299
+
300
+ if __name__ == "__main__": # pragma: no cover
301
+ import random
302
+ import time
303
+ from itertools import cycle
304
+ from typing import Dict, List, Tuple
305
+
306
+ from .align import Align
307
+ from .console import Console
308
+ from .live import Live as Live
309
+ from .panel import Panel
310
+ from .rule import Rule
311
+ from .syntax import Syntax
312
+ from .table import Table
313
+
314
+ console = Console()
315
+
316
+ syntax = Syntax(
317
+ '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
318
+ """Iterate and generate a tuple with a flag for last value."""
319
+ iter_values = iter(values)
320
+ try:
321
+ previous_value = next(iter_values)
322
+ except StopIteration:
323
+ return
324
+ for value in iter_values:
325
+ yield False, previous_value
326
+ previous_value = value
327
+ yield True, previous_value''',
328
+ "python",
329
+ line_numbers=True,
330
+ )
331
+
332
+ table = Table("foo", "bar", "baz")
333
+ table.add_row("1", "2", "3")
334
+
335
+ progress_renderables = [
336
+ "You can make the terminal shorter and taller to see the live table hide"
337
+ "Text may be printed while the progress bars are rendering.",
338
+ Panel("In fact, [i]any[/i] renderable will work"),
339
+ "Such as [magenta]tables[/]...",
340
+ table,
341
+ "Pretty printed structures...",
342
+ {"type": "example", "text": "Pretty printed"},
343
+ "Syntax...",
344
+ syntax,
345
+ Rule("Give it a try!"),
346
+ ]
347
+
348
+ examples = cycle(progress_renderables)
349
+
350
+ exchanges = [
351
+ "SGD",
352
+ "MYR",
353
+ "EUR",
354
+ "USD",
355
+ "AUD",
356
+ "JPY",
357
+ "CNH",
358
+ "HKD",
359
+ "CAD",
360
+ "INR",
361
+ "DKK",
362
+ "GBP",
363
+ "RUB",
364
+ "NZD",
365
+ "MXN",
366
+ "IDR",
367
+ "TWD",
368
+ "THB",
369
+ "VND",
370
+ ]
371
+ with Live(console=console) as live_table:
372
+ exchange_rate_dict: Dict[Tuple[str, str], float] = {}
373
+
374
+ for index in range(100):
375
+ select_exchange = exchanges[index % len(exchanges)]
376
+
377
+ for exchange in exchanges:
378
+ if exchange == select_exchange:
379
+ continue
380
+ time.sleep(0.4)
381
+ if random.randint(0, 10) < 1:
382
+ console.log(next(examples))
383
+ exchange_rate_dict[(select_exchange, exchange)] = 200 / (
384
+ (random.random() * 320) + 1
385
+ )
386
+ if len(exchange_rate_dict) > len(exchanges) - 1:
387
+ exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0])
388
+ table = Table(title="Exchange Rates")
389
+
390
+ table.add_column("Source Currency")
391
+ table.add_column("Destination Currency")
392
+ table.add_column("Exchange Rate")
393
+
394
+ for (source, dest), exchange_rate in exchange_rate_dict.items():
395
+ table.add_row(
396
+ source,
397
+ dest,
398
+ Text(
399
+ f"{exchange_rate:.4f}",
400
+ style="red" if exchange_rate < 1.0 else "green",
401
+ ),
402
+ )
403
+
404
+ live_table.update(Align.center(table))
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/live_render.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal, Optional, Tuple
2
+
3
+ from ._loop import loop_last
4
+ from .console import Console, ConsoleOptions, RenderableType, RenderResult
5
+ from .control import Control
6
+ from .segment import ControlType, Segment
7
+ from .style import StyleType
8
+ from .text import Text
9
+
10
+ VerticalOverflowMethod = Literal["crop", "ellipsis", "visible"]
11
+
12
+
13
+ class LiveRender:
14
+ """Creates a renderable that may be updated.
15
+
16
+ Args:
17
+ renderable (RenderableType): Any renderable object.
18
+ style (StyleType, optional): An optional style to apply to the renderable. Defaults to "".
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ renderable: RenderableType,
24
+ style: StyleType = "",
25
+ vertical_overflow: VerticalOverflowMethod = "ellipsis",
26
+ ) -> None:
27
+ self.renderable = renderable
28
+ self.style = style
29
+ self.vertical_overflow = vertical_overflow
30
+ self._shape: Optional[Tuple[int, int]] = None
31
+
32
+ @property
33
+ def last_render_height(self) -> int:
34
+ """The number of lines in the last render (may be 0 if nothing was rendered).
35
+
36
+ Returns:
37
+ Height in lines
38
+ """
39
+ if self._shape is None:
40
+ return 0
41
+ return self._shape[1]
42
+
43
+ def set_renderable(self, renderable: RenderableType) -> None:
44
+ """Set a new renderable.
45
+
46
+ Args:
47
+ renderable (RenderableType): Any renderable object, including str.
48
+ """
49
+ self.renderable = renderable
50
+
51
+ def position_cursor(self) -> Control:
52
+ """Get control codes to move cursor to beginning of live render.
53
+
54
+ Returns:
55
+ Control: A control instance that may be printed.
56
+ """
57
+ if self._shape is not None:
58
+ _, height = self._shape
59
+ return Control(
60
+ ControlType.CARRIAGE_RETURN,
61
+ (ControlType.ERASE_IN_LINE, 2),
62
+ *(
63
+ (
64
+ (ControlType.CURSOR_UP, 1),
65
+ (ControlType.ERASE_IN_LINE, 2),
66
+ )
67
+ * (height - 1)
68
+ )
69
+ )
70
+ return Control()
71
+
72
+ def restore_cursor(self) -> Control:
73
+ """Get control codes to clear the render and restore the cursor to its previous position.
74
+
75
+ Returns:
76
+ Control: A Control instance that may be printed.
77
+ """
78
+ if self._shape is not None:
79
+ _, height = self._shape
80
+ return Control(
81
+ ControlType.CARRIAGE_RETURN,
82
+ *((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height
83
+ )
84
+ return Control()
85
+
86
+ def __rich_console__(
87
+ self, console: Console, options: ConsoleOptions
88
+ ) -> RenderResult:
89
+ renderable = self.renderable
90
+ style = console.get_style(self.style)
91
+ lines = console.render_lines(renderable, options, style=style, pad=False)
92
+ shape = Segment.get_shape(lines)
93
+
94
+ _, height = shape
95
+ if height > options.size.height:
96
+ if self.vertical_overflow == "crop":
97
+ lines = lines[: options.size.height]
98
+ shape = Segment.get_shape(lines)
99
+ elif self.vertical_overflow == "ellipsis":
100
+ lines = lines[: (options.size.height - 1)]
101
+ overflow_text = Text(
102
+ "...",
103
+ overflow="crop",
104
+ justify="center",
105
+ end="",
106
+ style="live.ellipsis",
107
+ )
108
+ lines.append(list(console.render(overflow_text)))
109
+ shape = Segment.get_shape(lines)
110
+ self._shape = shape
111
+
112
+ new_line = Segment.line()
113
+ for last, line in loop_last(lines):
114
+ yield from line
115
+ if not last:
116
+ yield new_line
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/logging.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ from datetime import datetime
6
+ from logging import Handler, LogRecord
7
+ from types import ModuleType
8
+ from typing import TYPE_CHECKING, ClassVar, Iterable, List, Optional, Type, Union
9
+
10
+ if TYPE_CHECKING:
11
+ from ._log_render import FormatTimeCallable
12
+ from .console import Console, ConsoleRenderable
13
+ from .highlighter import Highlighter
14
+ from .traceback import Traceback
15
+
16
+ from rich._null_file import NullFile
17
+
18
+ from . import get_console
19
+ from ._log_render import LogRender
20
+ from .highlighter import ReprHighlighter
21
+ from .text import Text
22
+
23
+
24
+ class RichHandler(Handler):
25
+ """A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.
26
+ The level is color coded, and the message is syntax highlighted.
27
+
28
+ Note:
29
+ Be careful when enabling console markup in log messages if you have configured logging for libraries not
30
+ under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.
31
+
32
+ Args:
33
+ level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.
34
+ console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.
35
+ Default will use a global console instance writing to stdout.
36
+ show_time (bool, optional): Show a column for the time. Defaults to True.
37
+ omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.
38
+ show_level (bool, optional): Show a column for the level. Defaults to True.
39
+ show_path (bool, optional): Show the path to the original log call. Defaults to True.
40
+ enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.
41
+ highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.
42
+ markup (bool, optional): Enable console markup in log messages. Defaults to False.
43
+ rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False.
44
+ tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None.
45
+ tracebacks_code_width (int, optional): Number of code characters used to render tracebacks, or None for full width. Defaults to 88.
46
+ tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None.
47
+ tracebacks_theme (str, optional): Override pygments theme used in traceback.
48
+ tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True.
49
+ tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False.
50
+ tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
51
+ tracebacks_max_frames (int, optional): Optional maximum number of frames returned by traceback.
52
+ locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
53
+ Defaults to 10.
54
+ locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
55
+ log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ".
56
+ keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``.
57
+ """
58
+
59
+ KEYWORDS: ClassVar[Optional[List[str]]] = [
60
+ "GET",
61
+ "POST",
62
+ "HEAD",
63
+ "PUT",
64
+ "DELETE",
65
+ "OPTIONS",
66
+ "TRACE",
67
+ "PATCH",
68
+ ]
69
+ HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter
70
+
71
+ def __init__(
72
+ self,
73
+ level: Union[int, str] = logging.NOTSET,
74
+ console: Optional[Console] = None,
75
+ *,
76
+ show_time: bool = True,
77
+ omit_repeated_times: bool = True,
78
+ show_level: bool = True,
79
+ show_path: bool = True,
80
+ enable_link_path: bool = True,
81
+ highlighter: Optional[Highlighter] = None,
82
+ markup: bool = False,
83
+ rich_tracebacks: bool = False,
84
+ tracebacks_width: Optional[int] = None,
85
+ tracebacks_code_width: Optional[int] = 88,
86
+ tracebacks_extra_lines: int = 3,
87
+ tracebacks_theme: Optional[str] = None,
88
+ tracebacks_word_wrap: bool = True,
89
+ tracebacks_show_locals: bool = False,
90
+ tracebacks_suppress: Iterable[Union[str, ModuleType]] = (),
91
+ tracebacks_max_frames: int = 100,
92
+ locals_max_length: int = 10,
93
+ locals_max_string: int = 80,
94
+ log_time_format: Union[str, FormatTimeCallable] = "[%x %X]",
95
+ keywords: Optional[List[str]] = None,
96
+ ) -> None:
97
+ super().__init__(level=level)
98
+ self.console = console or get_console()
99
+ self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()
100
+ self._log_render = LogRender(
101
+ show_time=show_time,
102
+ show_level=show_level,
103
+ show_path=show_path,
104
+ time_format=log_time_format,
105
+ omit_repeated_times=omit_repeated_times,
106
+ level_width=None,
107
+ )
108
+ self.enable_link_path = enable_link_path
109
+ self.markup = markup
110
+ self.rich_tracebacks = rich_tracebacks
111
+ self.tracebacks_width = tracebacks_width
112
+ self.tracebacks_extra_lines = tracebacks_extra_lines
113
+ self.tracebacks_theme = tracebacks_theme
114
+ self.tracebacks_word_wrap = tracebacks_word_wrap
115
+ self.tracebacks_show_locals = tracebacks_show_locals
116
+ self.tracebacks_suppress = tracebacks_suppress
117
+ self.tracebacks_max_frames = tracebacks_max_frames
118
+ self.tracebacks_code_width = tracebacks_code_width
119
+ self.locals_max_length = locals_max_length
120
+ self.locals_max_string = locals_max_string
121
+ self.keywords = keywords
122
+
123
+ def get_level_text(self, record: LogRecord) -> Text:
124
+ """Get the level name from the record.
125
+
126
+ Args:
127
+ record (LogRecord): LogRecord instance.
128
+
129
+ Returns:
130
+ Text: A tuple of the style and level name.
131
+ """
132
+ level_name = record.levelname
133
+ level_text = Text.styled(
134
+ level_name.ljust(8), f"logging.level.{level_name.lower()}"
135
+ )
136
+ return level_text
137
+
138
+ def emit(self, record: LogRecord) -> None:
139
+ """Invoked by logging."""
140
+ message = self.format(record)
141
+ traceback = None
142
+ if (
143
+ self.rich_tracebacks
144
+ and record.exc_info
145
+ and record.exc_info != (None, None, None)
146
+ ):
147
+ exc_type, exc_value, exc_traceback = record.exc_info
148
+ assert exc_type is not None
149
+ assert exc_value is not None
150
+ from .traceback import Traceback
151
+
152
+ traceback = Traceback.from_exception(
153
+ exc_type,
154
+ exc_value,
155
+ exc_traceback,
156
+ width=self.tracebacks_width,
157
+ code_width=self.tracebacks_code_width,
158
+ extra_lines=self.tracebacks_extra_lines,
159
+ theme=self.tracebacks_theme,
160
+ word_wrap=self.tracebacks_word_wrap,
161
+ show_locals=self.tracebacks_show_locals,
162
+ locals_max_length=self.locals_max_length,
163
+ locals_max_string=self.locals_max_string,
164
+ suppress=self.tracebacks_suppress,
165
+ max_frames=self.tracebacks_max_frames,
166
+ )
167
+ message = record.getMessage()
168
+ if self.formatter:
169
+ record.message = record.getMessage()
170
+ formatter = self.formatter
171
+ if hasattr(formatter, "usesTime") and formatter.usesTime():
172
+ record.asctime = formatter.formatTime(record, formatter.datefmt)
173
+ message = formatter.formatMessage(record)
174
+
175
+ message_renderable = self.render_message(record, message)
176
+ log_renderable = self.render(
177
+ record=record, traceback=traceback, message_renderable=message_renderable
178
+ )
179
+ if isinstance(self.console.file, NullFile):
180
+ # Handles pythonw, where stdout/stderr are null, and we return NullFile
181
+ # instance from Console.file. In this case, we still want to make a log record
182
+ # even though we won't be writing anything to a file.
183
+ self.handleError(record)
184
+ else:
185
+ try:
186
+ self.console.print(log_renderable)
187
+ except Exception:
188
+ self.handleError(record)
189
+
190
+ def render_message(self, record: LogRecord, message: str) -> ConsoleRenderable:
191
+ """Render message text in to Text.
192
+
193
+ Args:
194
+ record (LogRecord): logging Record.
195
+ message (str): String containing log message.
196
+
197
+ Returns:
198
+ ConsoleRenderable: Renderable to display log message.
199
+ """
200
+ use_markup = getattr(record, "markup", self.markup)
201
+ message_text = Text.from_markup(message) if use_markup else Text(message)
202
+
203
+ highlighter = getattr(record, "highlighter", self.highlighter)
204
+ if highlighter:
205
+ message_text = highlighter(message_text)
206
+
207
+ if self.keywords is None:
208
+ self.keywords = self.KEYWORDS
209
+
210
+ if self.keywords:
211
+ message_text.highlight_words(self.keywords, "logging.keyword")
212
+
213
+ return message_text
214
+
215
+ def render(
216
+ self,
217
+ *,
218
+ record: LogRecord,
219
+ traceback: Optional[Traceback],
220
+ message_renderable: ConsoleRenderable,
221
+ ) -> ConsoleRenderable:
222
+ """Render log for display.
223
+
224
+ Args:
225
+ record (LogRecord): logging Record.
226
+ traceback (Optional[Traceback]): Traceback instance or None for no Traceback.
227
+ message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.
228
+
229
+ Returns:
230
+ ConsoleRenderable: Renderable to display log.
231
+ """
232
+ path = os.path.basename(record.pathname)
233
+ level = self.get_level_text(record)
234
+ time_format = None if self.formatter is None else self.formatter.datefmt
235
+ log_time = datetime.fromtimestamp(record.created)
236
+
237
+ log_renderable = self._log_render(
238
+ self.console,
239
+ [message_renderable] if not traceback else [message_renderable, traceback],
240
+ log_time=log_time,
241
+ time_format=time_format,
242
+ level=level,
243
+ path=path,
244
+ line_no=record.lineno,
245
+ link_path=record.pathname if self.enable_link_path else None,
246
+ )
247
+ return log_renderable
248
+
249
+
250
+ if __name__ == "__main__": # pragma: no cover
251
+ from time import sleep
252
+
253
+ FORMAT = "%(message)s"
254
+ # FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s"
255
+ logging.basicConfig(
256
+ level="NOTSET",
257
+ format=FORMAT,
258
+ datefmt="[%X]",
259
+ handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],
260
+ )
261
+ log = logging.getLogger("rich")
262
+
263
+ log.info("Server starting...")
264
+ log.info("Listening on http://127.0.0.1:8080")
265
+ sleep(1)
266
+
267
+ log.info("GET /index.html 200 1298")
268
+ log.info("GET /imgs/backgrounds/back1.jpg 200 54386")
269
+ log.info("GET /css/styles.css 200 54386")
270
+ log.warning("GET /favicon.ico 404 242")
271
+ sleep(1)
272
+
273
+ log.debug(
274
+ "JSONRPC request\n--> %r\n<-- %r",
275
+ {
276
+ "version": "1.1",
277
+ "method": "confirmFruitPurchase",
278
+ "params": [["apple", "orange", "mangoes", "pomelo"], 1.123],
279
+ "id": "194521489",
280
+ },
281
+ {"version": "1.1", "result": True, "error": None, "id": "194521489"},
282
+ )
283
+ log.debug(
284
+ "Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer"
285
+ )
286
+ log.error("Unable to find 'pomelo' in database!")
287
+ log.info("POST /jsonrpc/ 200 65532")
288
+ log.info("POST /admin/ 401 42234")
289
+ log.warning("password was rejected for admin site.")
290
+
291
+ def divide() -> None:
292
+ number = 1
293
+ divisor = 0
294
+ foos = ["foo"] * 100
295
+ log.debug("in divide")
296
+ try:
297
+ number / divisor
298
+ except:
299
+ log.exception("An error of some kind occurred!")
300
+
301
+ divide()
302
+ sleep(1)
303
+ log.critical("Out of memory!")
304
+ log.info("Server exited with code=-1")
305
+ log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/markdown.py ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from dataclasses import dataclass
5
+ from typing import ClassVar, Iterable, get_args
6
+
7
+ from markdown_it import MarkdownIt
8
+ from markdown_it.token import Token
9
+
10
+ from rich.table import Table
11
+
12
+ from . import box
13
+ from ._loop import loop_first
14
+ from ._stack import Stack
15
+ from .console import Console, ConsoleOptions, JustifyMethod, RenderResult
16
+ from .containers import Renderables
17
+ from .jupyter import JupyterMixin
18
+ from .rule import Rule
19
+ from .segment import Segment
20
+ from .style import Style, StyleStack
21
+ from .syntax import Syntax
22
+ from .text import Text, TextType
23
+
24
+
25
+ class MarkdownElement:
26
+ new_line: ClassVar[bool] = True
27
+
28
+ @classmethod
29
+ def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
30
+ """Factory to create markdown element,
31
+
32
+ Args:
33
+ markdown (Markdown): The parent Markdown object.
34
+ token (Token): A node from markdown-it.
35
+
36
+ Returns:
37
+ MarkdownElement: A new markdown element
38
+ """
39
+ return cls()
40
+
41
+ def on_enter(self, context: MarkdownContext) -> None:
42
+ """Called when the node is entered.
43
+
44
+ Args:
45
+ context (MarkdownContext): The markdown context.
46
+ """
47
+
48
+ def on_text(self, context: MarkdownContext, text: TextType) -> None:
49
+ """Called when text is parsed.
50
+
51
+ Args:
52
+ context (MarkdownContext): The markdown context.
53
+ """
54
+
55
+ def on_leave(self, context: MarkdownContext) -> None:
56
+ """Called when the parser leaves the element.
57
+
58
+ Args:
59
+ context (MarkdownContext): [description]
60
+ """
61
+
62
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
63
+ """Called when a child element is closed.
64
+
65
+ This method allows a parent element to take over rendering of its children.
66
+
67
+ Args:
68
+ context (MarkdownContext): The markdown context.
69
+ child (MarkdownElement): The child markdown element.
70
+
71
+ Returns:
72
+ bool: Return True to render the element, or False to not render the element.
73
+ """
74
+ return True
75
+
76
+ def __rich_console__(
77
+ self, console: Console, options: ConsoleOptions
78
+ ) -> RenderResult:
79
+ return ()
80
+
81
+
82
+ class UnknownElement(MarkdownElement):
83
+ """An unknown element.
84
+
85
+ Hopefully there will be no unknown elements, and we will have a MarkdownElement for
86
+ everything in the document.
87
+
88
+ """
89
+
90
+
91
+ class TextElement(MarkdownElement):
92
+ """Base class for elements that render text."""
93
+
94
+ style_name = "none"
95
+
96
+ def on_enter(self, context: MarkdownContext) -> None:
97
+ self.style = context.enter_style(self.style_name)
98
+ self.text = Text(justify="left")
99
+
100
+ def on_text(self, context: MarkdownContext, text: TextType) -> None:
101
+ self.text.append(text, context.current_style if isinstance(text, str) else None)
102
+
103
+ def on_leave(self, context: MarkdownContext) -> None:
104
+ context.leave_style()
105
+
106
+
107
+ class Paragraph(TextElement):
108
+ """A Paragraph."""
109
+
110
+ style_name = "markdown.paragraph"
111
+ justify: JustifyMethod
112
+
113
+ @classmethod
114
+ def create(cls, markdown: Markdown, token: Token) -> Paragraph:
115
+ return cls(justify=markdown.justify or "left")
116
+
117
+ def __init__(self, justify: JustifyMethod) -> None:
118
+ self.justify = justify
119
+
120
+ def __rich_console__(
121
+ self, console: Console, options: ConsoleOptions
122
+ ) -> RenderResult:
123
+ self.text.justify = self.justify
124
+ yield self.text
125
+
126
+
127
+ @dataclass
128
+ class HeadingFormat:
129
+ justify: JustifyMethod = "left"
130
+ style: str = ""
131
+
132
+
133
+ class Heading(TextElement):
134
+ """A heading."""
135
+
136
+ LEVEL_ALIGN: ClassVar[dict[str, JustifyMethod]] = {
137
+ "h1": "center",
138
+ "h2": "left",
139
+ "h3": "left",
140
+ "h4": "left",
141
+ "h5": "left",
142
+ "h6": "left",
143
+ }
144
+
145
+ @classmethod
146
+ def create(cls, markdown: Markdown, token: Token) -> Heading:
147
+ return cls(token.tag)
148
+
149
+ def on_enter(self, context: MarkdownContext) -> None:
150
+ self.text = Text()
151
+ context.enter_style(self.style_name)
152
+
153
+ def __init__(self, tag: str) -> None:
154
+ self.tag = tag
155
+ self.style_name = f"markdown.{tag}"
156
+ super().__init__()
157
+
158
+ def __rich_console__(
159
+ self, console: Console, options: ConsoleOptions
160
+ ) -> RenderResult:
161
+ text = self.text.copy()
162
+ heading_justify = self.LEVEL_ALIGN.get(self.tag, "left")
163
+ text.justify = heading_justify
164
+ yield text
165
+
166
+
167
+ class CodeBlock(TextElement):
168
+ """A code block with syntax highlighting."""
169
+
170
+ style_name = "markdown.code_block"
171
+
172
+ @classmethod
173
+ def create(cls, markdown: Markdown, token: Token) -> CodeBlock:
174
+ node_info = token.info or ""
175
+ lexer_name = node_info.partition(" ")[0]
176
+ return cls(lexer_name or "text", markdown.code_theme)
177
+
178
+ def __init__(self, lexer_name: str, theme: str) -> None:
179
+ self.lexer_name = lexer_name
180
+ self.theme = theme
181
+
182
+ def __rich_console__(
183
+ self, console: Console, options: ConsoleOptions
184
+ ) -> RenderResult:
185
+ code = str(self.text).rstrip()
186
+ syntax = Syntax(
187
+ code, self.lexer_name, theme=self.theme, word_wrap=True, padding=1
188
+ )
189
+ yield syntax
190
+
191
+
192
+ class BlockQuote(TextElement):
193
+ """A block quote."""
194
+
195
+ style_name = "markdown.block_quote"
196
+
197
+ def __init__(self) -> None:
198
+ self.elements: Renderables = Renderables()
199
+
200
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
201
+ self.elements.append(child)
202
+ return False
203
+
204
+ def __rich_console__(
205
+ self, console: Console, options: ConsoleOptions
206
+ ) -> RenderResult:
207
+ render_options = options.update(width=options.max_width - 4)
208
+ lines = console.render_lines(self.elements, render_options, style=self.style)
209
+ style = self.style
210
+ new_line = Segment("\n")
211
+ padding = Segment("▌ ", style)
212
+ for line in lines:
213
+ yield padding
214
+ yield from line
215
+ yield new_line
216
+
217
+
218
+ class HorizontalRule(MarkdownElement):
219
+ """A horizontal rule to divide sections."""
220
+
221
+ new_line = False
222
+
223
+ def __rich_console__(
224
+ self, console: Console, options: ConsoleOptions
225
+ ) -> RenderResult:
226
+ style = console.get_style("markdown.hr", default="none")
227
+ yield Rule(style=style, characters="-")
228
+ yield Text()
229
+
230
+
231
+ class TableElement(MarkdownElement):
232
+ """MarkdownElement corresponding to `table_open`."""
233
+
234
+ def __init__(self) -> None:
235
+ self.header: TableHeaderElement | None = None
236
+ self.body: TableBodyElement | None = None
237
+
238
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
239
+ if isinstance(child, TableHeaderElement):
240
+ self.header = child
241
+ elif isinstance(child, TableBodyElement):
242
+ self.body = child
243
+ else:
244
+ raise RuntimeError("Couldn't process markdown table.")
245
+ return False
246
+
247
+ def __rich_console__(
248
+ self, console: Console, options: ConsoleOptions
249
+ ) -> RenderResult:
250
+ table = Table(
251
+ box=box.SIMPLE,
252
+ pad_edge=False,
253
+ style="markdown.table.border",
254
+ show_edge=True,
255
+ collapse_padding=True,
256
+ )
257
+
258
+ if self.header is not None and self.header.row is not None:
259
+ for column in self.header.row.cells:
260
+ heading = column.content.copy()
261
+ heading.stylize("markdown.table.header")
262
+ table.add_column(heading)
263
+
264
+ if self.body is not None:
265
+ for row in self.body.rows:
266
+ row_content = [element.content for element in row.cells]
267
+ table.add_row(*row_content)
268
+
269
+ yield table
270
+
271
+
272
+ class TableHeaderElement(MarkdownElement):
273
+ """MarkdownElement corresponding to `thead_open` and `thead_close`."""
274
+
275
+ def __init__(self) -> None:
276
+ self.row: TableRowElement | None = None
277
+
278
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
279
+ assert isinstance(child, TableRowElement)
280
+ self.row = child
281
+ return False
282
+
283
+
284
+ class TableBodyElement(MarkdownElement):
285
+ """MarkdownElement corresponding to `tbody_open` and `tbody_close`."""
286
+
287
+ def __init__(self) -> None:
288
+ self.rows: list[TableRowElement] = []
289
+
290
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
291
+ assert isinstance(child, TableRowElement)
292
+ self.rows.append(child)
293
+ return False
294
+
295
+
296
+ class TableRowElement(MarkdownElement):
297
+ """MarkdownElement corresponding to `tr_open` and `tr_close`."""
298
+
299
+ def __init__(self) -> None:
300
+ self.cells: list[TableDataElement] = []
301
+
302
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
303
+ assert isinstance(child, TableDataElement)
304
+ self.cells.append(child)
305
+ return False
306
+
307
+
308
+ class TableDataElement(MarkdownElement):
309
+ """MarkdownElement corresponding to `td_open` and `td_close`
310
+ and `th_open` and `th_close`."""
311
+
312
+ @classmethod
313
+ def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
314
+ style = str(token.attrs.get("style")) or ""
315
+
316
+ justify: JustifyMethod
317
+ if "text-align:right" in style:
318
+ justify = "right"
319
+ elif "text-align:center" in style:
320
+ justify = "center"
321
+ elif "text-align:left" in style:
322
+ justify = "left"
323
+ else:
324
+ justify = "default"
325
+
326
+ assert justify in get_args(JustifyMethod)
327
+ return cls(justify=justify)
328
+
329
+ def __init__(self, justify: JustifyMethod) -> None:
330
+ self.content: Text = Text("", justify=justify)
331
+ self.justify = justify
332
+
333
+ def on_text(self, context: MarkdownContext, text: TextType) -> None:
334
+ text = Text(text) if isinstance(text, str) else text
335
+ text.stylize(context.current_style)
336
+ self.content.append_text(text)
337
+
338
+
339
+ class ListElement(MarkdownElement):
340
+ """A list element."""
341
+
342
+ @classmethod
343
+ def create(cls, markdown: Markdown, token: Token) -> ListElement:
344
+ return cls(token.type, int(token.attrs.get("start", 1)))
345
+
346
+ def __init__(self, list_type: str, list_start: int | None) -> None:
347
+ self.items: list[ListItem] = []
348
+ self.list_type = list_type
349
+ self.list_start = list_start
350
+
351
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
352
+ assert isinstance(child, ListItem)
353
+ self.items.append(child)
354
+ return False
355
+
356
+ def __rich_console__(
357
+ self, console: Console, options: ConsoleOptions
358
+ ) -> RenderResult:
359
+ if self.list_type == "bullet_list_open":
360
+ for item in self.items:
361
+ yield from item.render_bullet(console, options)
362
+ else:
363
+ number = 1 if self.list_start is None else self.list_start
364
+ last_number = number + len(self.items)
365
+ for index, item in enumerate(self.items):
366
+ yield from item.render_number(
367
+ console, options, number + index, last_number
368
+ )
369
+
370
+
371
+ class ListItem(TextElement):
372
+ """An item in a list."""
373
+
374
+ style_name = "markdown.item"
375
+
376
+ def __init__(self) -> None:
377
+ self.elements: Renderables = Renderables()
378
+
379
+ def on_child_close(self, context: MarkdownContext, child: MarkdownElement) -> bool:
380
+ self.elements.append(child)
381
+ return False
382
+
383
+ def render_bullet(self, console: Console, options: ConsoleOptions) -> RenderResult:
384
+ render_options = options.update(width=options.max_width - 3)
385
+ lines = console.render_lines(self.elements, render_options, style=self.style)
386
+ bullet_style = console.get_style("markdown.item.bullet", default="none")
387
+
388
+ bullet = Segment(" • ", bullet_style)
389
+ padding = Segment(" " * 3, bullet_style)
390
+ new_line = Segment("\n")
391
+ for first, line in loop_first(lines):
392
+ yield bullet if first else padding
393
+ yield from line
394
+ yield new_line
395
+
396
+ def render_number(
397
+ self, console: Console, options: ConsoleOptions, number: int, last_number: int
398
+ ) -> RenderResult:
399
+ number_width = len(str(last_number)) + 2
400
+ render_options = options.update(width=options.max_width - number_width)
401
+ lines = console.render_lines(self.elements, render_options, style=self.style)
402
+ number_style = console.get_style("markdown.item.number", default="none")
403
+
404
+ new_line = Segment("\n")
405
+ padding = Segment(" " * number_width, number_style)
406
+ numeral = Segment(f"{number}".rjust(number_width - 1) + " ", number_style)
407
+ for first, line in loop_first(lines):
408
+ yield numeral if first else padding
409
+ yield from line
410
+ yield new_line
411
+
412
+
413
+ class Link(TextElement):
414
+ @classmethod
415
+ def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
416
+ url = token.attrs.get("href", "#")
417
+ return cls(token.content, str(url))
418
+
419
+ def __init__(self, text: str, href: str):
420
+ self.text = Text(text)
421
+ self.href = href
422
+
423
+
424
+ class ImageItem(TextElement):
425
+ """Renders a placeholder for an image."""
426
+
427
+ new_line = False
428
+
429
+ @classmethod
430
+ def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
431
+ """Factory to create markdown element,
432
+
433
+ Args:
434
+ markdown (Markdown): The parent Markdown object.
435
+ token (Any): A token from markdown-it.
436
+
437
+ Returns:
438
+ MarkdownElement: A new markdown element
439
+ """
440
+ return cls(str(token.attrs.get("src", "")), markdown.hyperlinks)
441
+
442
+ def __init__(self, destination: str, hyperlinks: bool) -> None:
443
+ self.destination = destination
444
+ self.hyperlinks = hyperlinks
445
+ self.link: str | None = None
446
+ super().__init__()
447
+
448
+ def on_enter(self, context: MarkdownContext) -> None:
449
+ self.link = context.current_style.link
450
+ self.text = Text(justify="left")
451
+ super().on_enter(context)
452
+
453
+ def __rich_console__(
454
+ self, console: Console, options: ConsoleOptions
455
+ ) -> RenderResult:
456
+ link_style = Style(link=self.link or self.destination or None)
457
+ title = self.text or Text(self.destination.strip("/").rsplit("/", 1)[-1])
458
+ if self.hyperlinks:
459
+ title.stylize(link_style)
460
+ text = Text.assemble("🌆 ", title, " ", end="")
461
+ yield text
462
+
463
+
464
+ class MarkdownContext:
465
+ """Manages the console render state."""
466
+
467
+ def __init__(
468
+ self,
469
+ console: Console,
470
+ options: ConsoleOptions,
471
+ style: Style,
472
+ inline_code_lexer: str | None = None,
473
+ inline_code_theme: str = "monokai",
474
+ ) -> None:
475
+ self.console = console
476
+ self.options = options
477
+ self.style_stack: StyleStack = StyleStack(style)
478
+ self.stack: Stack[MarkdownElement] = Stack()
479
+
480
+ self._syntax: Syntax | None = None
481
+ if inline_code_lexer is not None:
482
+ self._syntax = Syntax("", inline_code_lexer, theme=inline_code_theme)
483
+
484
+ @property
485
+ def current_style(self) -> Style:
486
+ """Current style which is the product of all styles on the stack."""
487
+ return self.style_stack.current
488
+
489
+ def on_text(self, text: str, node_type: str) -> None:
490
+ """Called when the parser visits text."""
491
+ if node_type in {"fence", "code_inline"} and self._syntax is not None:
492
+ highlight_text = self._syntax.highlight(text)
493
+ highlight_text.rstrip()
494
+ self.stack.top.on_text(
495
+ self, Text.assemble(highlight_text, style=self.style_stack.current)
496
+ )
497
+ else:
498
+ self.stack.top.on_text(self, text)
499
+
500
+ def enter_style(self, style_name: str | Style) -> Style:
501
+ """Enter a style context."""
502
+ style = self.console.get_style(style_name, default="none")
503
+ self.style_stack.push(style)
504
+ return self.current_style
505
+
506
+ def leave_style(self) -> Style:
507
+ """Leave a style context."""
508
+ style = self.style_stack.pop()
509
+ return style
510
+
511
+
512
+ class Markdown(JupyterMixin):
513
+ """A Markdown renderable.
514
+
515
+ Args:
516
+ markup (str): A string containing markdown.
517
+ code_theme (str, optional): Pygments theme for code blocks. Defaults to "monokai". See https://pygments.org/styles/ for code themes.
518
+ justify (JustifyMethod, optional): Justify value for paragraphs. Defaults to None.
519
+ style (Union[str, Style], optional): Optional style to apply to markdown.
520
+ hyperlinks (bool, optional): Enable hyperlinks. Defaults to ``True``.
521
+ inline_code_lexer: (str, optional): Lexer to use if inline code highlighting is
522
+ enabled. Defaults to None.
523
+ inline_code_theme: (Optional[str], optional): Pygments theme for inline code
524
+ highlighting, or None for no highlighting. Defaults to None.
525
+ """
526
+
527
+ elements: ClassVar[dict[str, type[MarkdownElement]]] = {
528
+ "paragraph_open": Paragraph,
529
+ "heading_open": Heading,
530
+ "fence": CodeBlock,
531
+ "code_block": CodeBlock,
532
+ "blockquote_open": BlockQuote,
533
+ "hr": HorizontalRule,
534
+ "bullet_list_open": ListElement,
535
+ "ordered_list_open": ListElement,
536
+ "list_item_open": ListItem,
537
+ "image": ImageItem,
538
+ "table_open": TableElement,
539
+ "tbody_open": TableBodyElement,
540
+ "thead_open": TableHeaderElement,
541
+ "tr_open": TableRowElement,
542
+ "td_open": TableDataElement,
543
+ "th_open": TableDataElement,
544
+ }
545
+
546
+ inlines = {"em", "strong", "code", "s"}
547
+
548
+ def __init__(
549
+ self,
550
+ markup: str,
551
+ code_theme: str = "monokai",
552
+ justify: JustifyMethod | None = None,
553
+ style: str | Style = "none",
554
+ hyperlinks: bool = True,
555
+ inline_code_lexer: str | None = None,
556
+ inline_code_theme: str | None = None,
557
+ ) -> None:
558
+ parser = MarkdownIt().enable("strikethrough").enable("table")
559
+ self.markup = markup
560
+ self.parsed = parser.parse(markup)
561
+ self.code_theme = code_theme
562
+ self.justify: JustifyMethod | None = justify
563
+ self.style = style
564
+ self.hyperlinks = hyperlinks
565
+ self.inline_code_lexer = inline_code_lexer
566
+ self.inline_code_theme = inline_code_theme or code_theme
567
+
568
+ def _flatten_tokens(self, tokens: Iterable[Token]) -> Iterable[Token]:
569
+ """Flattens the token stream."""
570
+ for token in tokens:
571
+ is_fence = token.type == "fence"
572
+ is_image = token.tag == "img"
573
+ if token.children and not (is_image or is_fence):
574
+ yield from self._flatten_tokens(token.children)
575
+ else:
576
+ yield token
577
+
578
+ def __rich_console__(
579
+ self, console: Console, options: ConsoleOptions
580
+ ) -> RenderResult:
581
+ """Render markdown to the console."""
582
+ style = console.get_style(self.style, default="none")
583
+ options = options.update(height=None)
584
+ context = MarkdownContext(
585
+ console,
586
+ options,
587
+ style,
588
+ inline_code_lexer=self.inline_code_lexer,
589
+ inline_code_theme=self.inline_code_theme,
590
+ )
591
+ tokens = self.parsed
592
+ inline_style_tags = self.inlines
593
+ new_line = False
594
+ _new_line_segment = Segment.line()
595
+
596
+ for token in self._flatten_tokens(tokens):
597
+ node_type = token.type
598
+ tag = token.tag
599
+
600
+ entering = token.nesting == 1
601
+ exiting = token.nesting == -1
602
+ self_closing = token.nesting == 0
603
+
604
+ if node_type == "text":
605
+ context.on_text(token.content, node_type)
606
+ elif node_type == "hardbreak":
607
+ context.on_text("\n", node_type)
608
+ elif node_type == "softbreak":
609
+ context.on_text(" ", node_type)
610
+ elif node_type == "link_open":
611
+ href = str(token.attrs.get("href", ""))
612
+ if self.hyperlinks:
613
+ link_style = console.get_style("markdown.link_url", default="none")
614
+ link_style += Style(link=href)
615
+ context.enter_style(link_style)
616
+ else:
617
+ context.stack.push(Link.create(self, token))
618
+ elif node_type == "link_close":
619
+ if self.hyperlinks:
620
+ context.leave_style()
621
+ else:
622
+ element = context.stack.pop()
623
+ assert isinstance(element, Link)
624
+ link_style = console.get_style("markdown.link", default="none")
625
+ context.enter_style(link_style)
626
+ context.on_text(element.text.plain, node_type)
627
+ context.leave_style()
628
+ context.on_text(" (", node_type)
629
+ link_url_style = console.get_style(
630
+ "markdown.link_url", default="none"
631
+ )
632
+ context.enter_style(link_url_style)
633
+ context.on_text(element.href, node_type)
634
+ context.leave_style()
635
+ context.on_text(")", node_type)
636
+ elif (
637
+ tag in inline_style_tags
638
+ and node_type != "fence"
639
+ and node_type != "code_block"
640
+ ):
641
+ if entering:
642
+ # If it's an opening inline token e.g. strong, em, etc.
643
+ # Then we move into a style context i.e. push to stack.
644
+ context.enter_style(f"markdown.{tag}")
645
+ elif exiting:
646
+ # If it's a closing inline style, then we pop the style
647
+ # off of the stack, to move out of the context of it...
648
+ context.leave_style()
649
+ else:
650
+ # If it's a self-closing inline style e.g. `code_inline`
651
+ context.enter_style(f"markdown.{tag}")
652
+ if token.content:
653
+ context.on_text(token.content, node_type)
654
+ context.leave_style()
655
+ else:
656
+ # Map the markdown tag -> MarkdownElement renderable
657
+ element_class = self.elements.get(token.type) or UnknownElement
658
+ element = element_class.create(self, token)
659
+
660
+ if entering or self_closing:
661
+ context.stack.push(element)
662
+ element.on_enter(context)
663
+
664
+ if exiting: # CLOSING tag
665
+ element = context.stack.pop()
666
+
667
+ should_render = not context.stack or (
668
+ context.stack
669
+ and context.stack.top.on_child_close(context, element)
670
+ )
671
+
672
+ if should_render:
673
+ if new_line:
674
+ yield _new_line_segment
675
+
676
+ yield from console.render(element, context.options)
677
+ elif self_closing: # SELF-CLOSING tags (e.g. text, code, image)
678
+ context.stack.pop()
679
+ text = token.content
680
+ if text is not None:
681
+ element.on_text(context, text)
682
+
683
+ should_render = (
684
+ not context.stack
685
+ or context.stack
686
+ and context.stack.top.on_child_close(context, element)
687
+ )
688
+ if should_render:
689
+ if new_line and node_type != "inline":
690
+ yield _new_line_segment
691
+ yield from console.render(element, context.options)
692
+
693
+ if exiting or self_closing:
694
+ element.on_leave(context)
695
+ new_line = element.new_line
696
+
697
+
698
+ if __name__ == "__main__": # pragma: no cover
699
+ import argparse
700
+ import sys
701
+
702
+ parser = argparse.ArgumentParser(
703
+ description="Render Markdown to the console with Rich"
704
+ )
705
+ parser.add_argument(
706
+ "path",
707
+ metavar="PATH",
708
+ help="path to markdown file, or - for stdin",
709
+ )
710
+ parser.add_argument(
711
+ "-c",
712
+ "--force-color",
713
+ dest="force_color",
714
+ action="store_true",
715
+ default=None,
716
+ help="force color for non-terminals",
717
+ )
718
+ parser.add_argument(
719
+ "-t",
720
+ "--code-theme",
721
+ dest="code_theme",
722
+ default="monokai",
723
+ help="pygments code theme",
724
+ )
725
+ parser.add_argument(
726
+ "-i",
727
+ "--inline-code-lexer",
728
+ dest="inline_code_lexer",
729
+ default=None,
730
+ help="inline_code_lexer",
731
+ )
732
+ parser.add_argument(
733
+ "-y",
734
+ "--hyperlinks",
735
+ dest="hyperlinks",
736
+ action="store_true",
737
+ help="enable hyperlinks",
738
+ )
739
+ parser.add_argument(
740
+ "-w",
741
+ "--width",
742
+ type=int,
743
+ dest="width",
744
+ default=None,
745
+ help="width of output (default will auto-detect)",
746
+ )
747
+ parser.add_argument(
748
+ "-j",
749
+ "--justify",
750
+ dest="justify",
751
+ action="store_true",
752
+ help="enable full text justify",
753
+ )
754
+ parser.add_argument(
755
+ "-p",
756
+ "--page",
757
+ dest="page",
758
+ action="store_true",
759
+ help="use pager to scroll output",
760
+ )
761
+ args = parser.parse_args()
762
+
763
+ from rich.console import Console
764
+
765
+ if args.path == "-":
766
+ markdown_body = sys.stdin.read()
767
+ else:
768
+ with open(args.path, encoding="utf-8") as markdown_file:
769
+ markdown_body = markdown_file.read()
770
+
771
+ markdown = Markdown(
772
+ markdown_body,
773
+ justify="full" if args.justify else "left",
774
+ code_theme=args.code_theme,
775
+ hyperlinks=args.hyperlinks,
776
+ inline_code_lexer=args.inline_code_lexer,
777
+ )
778
+ if args.page:
779
+ import io
780
+ import pydoc
781
+
782
+ fileio = io.StringIO()
783
+ console = Console(
784
+ file=fileio, force_terminal=args.force_color, width=args.width
785
+ )
786
+ console.print(markdown)
787
+ pydoc.pager(fileio.getvalue())
788
+
789
+ else:
790
+ console = Console(
791
+ force_terminal=args.force_color, width=args.width, record=True
792
+ )
793
+ console.print(markdown)
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/markup.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from ast import literal_eval
3
+ from operator import attrgetter
4
+ from typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union
5
+
6
+ from ._emoji_replace import _emoji_replace
7
+ from .emoji import EmojiVariant
8
+ from .errors import MarkupError
9
+ from .style import Style
10
+ from .text import Span, Text
11
+
12
+ RE_TAGS = re.compile(
13
+ r"""((\\*)\[([a-z#/@][^[]*?)])""",
14
+ re.VERBOSE,
15
+ )
16
+
17
+ RE_HANDLER = re.compile(r"^([\w.]*?)(\(.*?\))?$")
18
+
19
+
20
+ class Tag(NamedTuple):
21
+ """A tag in console markup."""
22
+
23
+ name: str
24
+ """The tag name. e.g. 'bold'."""
25
+ parameters: Optional[str]
26
+ """Any additional parameters after the name."""
27
+
28
+ def __str__(self) -> str:
29
+ return (
30
+ self.name if self.parameters is None else f"{self.name} {self.parameters}"
31
+ )
32
+
33
+ @property
34
+ def markup(self) -> str:
35
+ """Get the string representation of this tag."""
36
+ return (
37
+ f"[{self.name}]"
38
+ if self.parameters is None
39
+ else f"[{self.name}={self.parameters}]"
40
+ )
41
+
42
+
43
+ _ReStringMatch = Match[str] # regex match object
44
+ _ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub
45
+ _EscapeSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re
46
+
47
+
48
+ def escape(
49
+ markup: str,
50
+ _escape: _EscapeSubMethod = re.compile(r"(\\*)(\[[a-z#/@][^[]*?])").sub,
51
+ ) -> str:
52
+ """Escapes text so that it won't be interpreted as markup.
53
+
54
+ Args:
55
+ markup (str): Content to be inserted in to markup.
56
+
57
+ Returns:
58
+ str: Markup with square brackets escaped.
59
+ """
60
+
61
+ def escape_backslashes(match: Match[str]) -> str:
62
+ """Called by re.sub replace matches."""
63
+ backslashes, text = match.groups()
64
+ return f"{backslashes}{backslashes}\\{text}"
65
+
66
+ markup = _escape(escape_backslashes, markup)
67
+ if markup.endswith("\\") and not markup.endswith("\\\\"):
68
+ return markup + "\\"
69
+
70
+ return markup
71
+
72
+
73
+ def _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]:
74
+ """Parse markup in to an iterable of tuples of (position, text, tag).
75
+
76
+ Args:
77
+ markup (str): A string containing console markup
78
+
79
+ """
80
+ position = 0
81
+ _divmod = divmod
82
+ _Tag = Tag
83
+ for match in RE_TAGS.finditer(markup):
84
+ full_text, escapes, tag_text = match.groups()
85
+ start, end = match.span()
86
+ if start > position:
87
+ yield start, markup[position:start], None
88
+ if escapes:
89
+ backslashes, escaped = _divmod(len(escapes), 2)
90
+ if backslashes:
91
+ # Literal backslashes
92
+ yield start, "\\" * backslashes, None
93
+ start += backslashes * 2
94
+ if escaped:
95
+ # Escape of tag
96
+ yield start, full_text[len(escapes) :], None
97
+ position = end
98
+ continue
99
+ text, equals, parameters = tag_text.partition("=")
100
+ yield start, None, _Tag(text, parameters if equals else None)
101
+ position = end
102
+ if position < len(markup):
103
+ yield position, markup[position:], None
104
+
105
+
106
+ def render(
107
+ markup: str,
108
+ style: Union[str, Style] = "",
109
+ emoji: bool = True,
110
+ emoji_variant: Optional[EmojiVariant] = None,
111
+ ) -> Text:
112
+ """Render console markup in to a Text instance.
113
+
114
+ Args:
115
+ markup (str): A string containing console markup.
116
+ style: (Union[str, Style]): The style to use.
117
+ emoji (bool, optional): Also render emoji code. Defaults to True.
118
+ emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
119
+
120
+
121
+ Raises:
122
+ MarkupError: If there is a syntax error in the markup.
123
+
124
+ Returns:
125
+ Text: A test instance.
126
+ """
127
+ emoji_replace = _emoji_replace
128
+ if "[" not in markup:
129
+ return Text(
130
+ emoji_replace(markup, default_variant=emoji_variant) if emoji else markup,
131
+ style=style,
132
+ )
133
+ text = Text(style=style)
134
+ append = text.append
135
+ normalize = Style.normalize
136
+
137
+ style_stack: List[Tuple[int, Tag]] = []
138
+ pop = style_stack.pop
139
+
140
+ spans: List[Span] = []
141
+ append_span = spans.append
142
+
143
+ _Span = Span
144
+ _Tag = Tag
145
+
146
+ def pop_style(style_name: str) -> Tuple[int, Tag]:
147
+ """Pop tag matching given style name."""
148
+ for index, (_, tag) in enumerate(reversed(style_stack), 1):
149
+ if tag.name == style_name:
150
+ return pop(-index)
151
+ raise KeyError(style_name)
152
+
153
+ for position, plain_text, tag in _parse(markup):
154
+ if plain_text is not None:
155
+ # Handle open brace escapes, where the brace is not part of a tag.
156
+ plain_text = plain_text.replace("\\[", "[")
157
+ append(emoji_replace(plain_text) if emoji else plain_text)
158
+ elif tag is not None:
159
+ if tag.name.startswith("/"): # Closing tag
160
+ style_name = tag.name[1:].strip()
161
+
162
+ if style_name: # explicit close
163
+ style_name = normalize(style_name)
164
+ try:
165
+ start, open_tag = pop_style(style_name)
166
+ except KeyError:
167
+ raise MarkupError(
168
+ f"closing tag '{tag.markup}' at position {position} doesn't match any open tag"
169
+ ) from None
170
+ else: # implicit close
171
+ try:
172
+ start, open_tag = pop()
173
+ except IndexError:
174
+ raise MarkupError(
175
+ f"closing tag '[/]' at position {position} has nothing to close"
176
+ ) from None
177
+
178
+ if open_tag.name.startswith("@"):
179
+ if open_tag.parameters:
180
+ handler_name = ""
181
+ parameters = open_tag.parameters.strip()
182
+ handler_match = RE_HANDLER.match(parameters)
183
+ if handler_match is not None:
184
+ handler_name, match_parameters = handler_match.groups()
185
+ parameters = (
186
+ "()" if match_parameters is None else match_parameters
187
+ )
188
+
189
+ try:
190
+ meta_params = literal_eval(parameters)
191
+ except SyntaxError as error:
192
+ raise MarkupError(
193
+ f"error parsing {parameters!r} in {open_tag.parameters!r}; {error.msg}"
194
+ )
195
+ except Exception as error:
196
+ raise MarkupError(
197
+ f"error parsing {open_tag.parameters!r}; {error}"
198
+ ) from None
199
+
200
+ if handler_name:
201
+ meta_params = (
202
+ handler_name,
203
+ meta_params
204
+ if isinstance(meta_params, tuple)
205
+ else (meta_params,),
206
+ )
207
+
208
+ else:
209
+ meta_params = ()
210
+
211
+ append_span(
212
+ _Span(
213
+ start, len(text), Style(meta={open_tag.name: meta_params})
214
+ )
215
+ )
216
+ else:
217
+ append_span(_Span(start, len(text), str(open_tag)))
218
+
219
+ else: # Opening tag
220
+ normalized_tag = _Tag(normalize(tag.name), tag.parameters)
221
+ style_stack.append((len(text), normalized_tag))
222
+
223
+ text_length = len(text)
224
+ while style_stack:
225
+ start, tag = style_stack.pop()
226
+ style = str(tag)
227
+ if style:
228
+ append_span(_Span(start, text_length, style))
229
+
230
+ text.spans = sorted(spans[::-1], key=attrgetter("start"))
231
+ return text
232
+
233
+
234
+ if __name__ == "__main__": # pragma: no cover
235
+ MARKUP = [
236
+ "[red]Hello World[/red]",
237
+ "[magenta]Hello [b]World[/b]",
238
+ "[bold]Bold[italic] bold and italic [/bold]italic[/italic]",
239
+ "Click [link=https://www.willmcgugan.com]here[/link] to visit my Blog",
240
+ ":warning-emoji: [bold red blink] DANGER![/]",
241
+ ]
242
+
243
+ from rich import print
244
+ from rich.table import Table
245
+
246
+ grid = Table("Markup", "Result", padding=(0, 1))
247
+
248
+ for markup in MARKUP:
249
+ grid.add_row(Text(markup), markup)
250
+
251
+ print(grid)
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/measure.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from operator import itemgetter
2
+ from typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Sequence
3
+
4
+ from . import errors
5
+ from .protocol import is_renderable, rich_cast
6
+
7
+ if TYPE_CHECKING:
8
+ from .console import Console, ConsoleOptions, RenderableType
9
+
10
+
11
+ class Measurement(NamedTuple):
12
+ """Stores the minimum and maximum widths (in characters) required to render an object."""
13
+
14
+ minimum: int
15
+ """Minimum number of cells required to render."""
16
+ maximum: int
17
+ """Maximum number of cells required to render."""
18
+
19
+ @property
20
+ def span(self) -> int:
21
+ """Get difference between maximum and minimum."""
22
+ return self.maximum - self.minimum
23
+
24
+ def normalize(self) -> "Measurement":
25
+ """Get measurement that ensures that minimum <= maximum and minimum >= 0
26
+
27
+ Returns:
28
+ Measurement: A normalized measurement.
29
+ """
30
+ minimum, maximum = self
31
+ minimum = min(max(0, minimum), maximum)
32
+ return Measurement(max(0, minimum), max(0, max(minimum, maximum)))
33
+
34
+ def with_maximum(self, width: int) -> "Measurement":
35
+ """Get a RenderableWith where the widths are <= width.
36
+
37
+ Args:
38
+ width (int): Maximum desired width.
39
+
40
+ Returns:
41
+ Measurement: New Measurement object.
42
+ """
43
+ minimum, maximum = self
44
+ return Measurement(min(minimum, width), min(maximum, width))
45
+
46
+ def with_minimum(self, width: int) -> "Measurement":
47
+ """Get a RenderableWith where the widths are >= width.
48
+
49
+ Args:
50
+ width (int): Minimum desired width.
51
+
52
+ Returns:
53
+ Measurement: New Measurement object.
54
+ """
55
+ minimum, maximum = self
56
+ width = max(0, width)
57
+ return Measurement(max(minimum, width), max(maximum, width))
58
+
59
+ def clamp(
60
+ self, min_width: Optional[int] = None, max_width: Optional[int] = None
61
+ ) -> "Measurement":
62
+ """Clamp a measurement within the specified range.
63
+
64
+ Args:
65
+ min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None.
66
+ max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None.
67
+
68
+ Returns:
69
+ Measurement: New Measurement object.
70
+ """
71
+ measurement = self
72
+ if min_width is not None:
73
+ measurement = measurement.with_minimum(min_width)
74
+ if max_width is not None:
75
+ measurement = measurement.with_maximum(max_width)
76
+ return measurement
77
+
78
+ @classmethod
79
+ def get(
80
+ cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType"
81
+ ) -> "Measurement":
82
+ """Get a measurement for a renderable.
83
+
84
+ Args:
85
+ console (~rich.console.Console): Console instance.
86
+ options (~rich.console.ConsoleOptions): Console options.
87
+ renderable (RenderableType): An object that may be rendered with Rich.
88
+
89
+ Raises:
90
+ errors.NotRenderableError: If the object is not renderable.
91
+
92
+ Returns:
93
+ Measurement: Measurement object containing range of character widths required to render the object.
94
+ """
95
+ _max_width = options.max_width
96
+ if _max_width < 1:
97
+ return Measurement(0, 0)
98
+ if isinstance(renderable, str):
99
+ renderable = console.render_str(
100
+ renderable, markup=options.markup, highlight=False
101
+ )
102
+ renderable = rich_cast(renderable)
103
+ if is_renderable(renderable):
104
+ get_console_width: Optional[
105
+ Callable[["Console", "ConsoleOptions"], "Measurement"]
106
+ ] = getattr(renderable, "__rich_measure__", None)
107
+ if get_console_width is not None:
108
+ render_width = (
109
+ get_console_width(console, options)
110
+ .normalize()
111
+ .with_maximum(_max_width)
112
+ )
113
+ if render_width.maximum < 1:
114
+ return Measurement(0, 0)
115
+ return render_width.normalize()
116
+ else:
117
+ return Measurement(0, _max_width)
118
+ else:
119
+ raise errors.NotRenderableError(
120
+ f"Unable to get render width for {renderable!r}; "
121
+ "a str, Segment, or object with __rich_console__ method is required"
122
+ )
123
+
124
+
125
+ def measure_renderables(
126
+ console: "Console",
127
+ options: "ConsoleOptions",
128
+ renderables: Sequence["RenderableType"],
129
+ ) -> "Measurement":
130
+ """Get a measurement that would fit a number of renderables.
131
+
132
+ Args:
133
+ console (~rich.console.Console): Console instance.
134
+ options (~rich.console.ConsoleOptions): Console options.
135
+ renderables (Iterable[RenderableType]): One or more renderable objects.
136
+
137
+ Returns:
138
+ Measurement: Measurement object containing range of character widths required to
139
+ contain all given renderables.
140
+ """
141
+ if not renderables:
142
+ return Measurement(0, 0)
143
+ get_measurement = Measurement.get
144
+ measurements = [
145
+ get_measurement(console, options, renderable) for renderable in renderables
146
+ ]
147
+ measured_width = Measurement(
148
+ max(measurements, key=itemgetter(0)).minimum,
149
+ max(measurements, key=itemgetter(1)).maximum,
150
+ )
151
+ return measured_width
.cache/uv/archive-v0/1AmN3AaX0LoiIR2OeGzy7/rich/padding.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
2
+
3
+ if TYPE_CHECKING:
4
+ from .console import (
5
+ Console,
6
+ ConsoleOptions,
7
+ RenderableType,
8
+ RenderResult,
9
+ )
10
+
11
+ from .jupyter import JupyterMixin
12
+ from .measure import Measurement
13
+ from .segment import Segment
14
+ from .style import Style
15
+
16
+ PaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]]
17
+
18
+
19
+ class Padding(JupyterMixin):
20
+ """Draw space around content.
21
+
22
+ Example:
23
+ >>> print(Padding("Hello", (2, 4), style="on blue"))
24
+
25
+ Args:
26
+ renderable (RenderableType): String or other renderable.
27
+ pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders.
28
+ May be specified with 1, 2, or 4 integers (CSS style).
29
+ style (Union[str, Style], optional): Style for padding characters. Defaults to "none".
30
+ expand (bool, optional): Expand padding to fit available width. Defaults to True.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ renderable: "RenderableType",
36
+ pad: "PaddingDimensions" = (0, 0, 0, 0),
37
+ *,
38
+ style: Union[str, Style] = "none",
39
+ expand: bool = True,
40
+ ):
41
+ self.renderable = renderable
42
+ self.top, self.right, self.bottom, self.left = self.unpack(pad)
43
+ self.style = style
44
+ self.expand = expand
45
+
46
+ @classmethod
47
+ def indent(cls, renderable: "RenderableType", level: int) -> "Padding":
48
+ """Make padding instance to render an indent.
49
+
50
+ Args:
51
+ renderable (RenderableType): String or other renderable.
52
+ level (int): Number of characters to indent.
53
+
54
+ Returns:
55
+ Padding: A Padding instance.
56
+ """
57
+
58
+ return Padding(renderable, pad=(0, 0, 0, level), expand=False)
59
+
60
+ @staticmethod
61
+ def unpack(pad: "PaddingDimensions") -> Tuple[int, int, int, int]:
62
+ """Unpack padding specified in CSS style."""
63
+ if isinstance(pad, int):
64
+ return (pad, pad, pad, pad)
65
+ if len(pad) == 1:
66
+ _pad = pad[0]
67
+ return (_pad, _pad, _pad, _pad)
68
+ if len(pad) == 2:
69
+ pad_top, pad_right = pad
70
+ return (pad_top, pad_right, pad_top, pad_right)
71
+ if len(pad) == 4:
72
+ top, right, bottom, left = pad
73
+ return (top, right, bottom, left)
74
+ raise ValueError(f"1, 2 or 4 integers required for padding; {len(pad)} given")
75
+
76
+ def __repr__(self) -> str:
77
+ return f"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))"
78
+
79
+ def __rich_console__(
80
+ self, console: "Console", options: "ConsoleOptions"
81
+ ) -> "RenderResult":
82
+ style = console.get_style(self.style)
83
+ if self.expand:
84
+ width = options.max_width
85
+ else:
86
+ width = min(
87
+ Measurement.get(console, options, self.renderable).maximum
88
+ + self.left
89
+ + self.right,
90
+ options.max_width,
91
+ )
92
+ render_options = options.update_width(width - self.left - self.right)
93
+ if render_options.height is not None:
94
+ render_options = render_options.update_height(
95
+ height=render_options.height - self.top - self.bottom
96
+ )
97
+ lines = console.render_lines(
98
+ self.renderable, render_options, style=style, pad=True
99
+ )
100
+ _Segment = Segment
101
+
102
+ left = _Segment(" " * self.left, style) if self.left else None
103
+ right = (
104
+ [_Segment(f'{" " * self.right}', style), _Segment.line()]
105
+ if self.right
106
+ else [_Segment.line()]
107
+ )
108
+ blank_line: Optional[List[Segment]] = None
109
+ if self.top:
110
+ blank_line = [_Segment(f'{" " * width}\n', style)]
111
+ yield from blank_line * self.top
112
+ if left:
113
+ for line in lines:
114
+ yield left
115
+ yield from line
116
+ yield from right
117
+ else:
118
+ for line in lines:
119
+ yield from line
120
+ yield from right
121
+ if self.bottom:
122
+ blank_line = blank_line or [_Segment(f'{" " * width}\n', style)]
123
+ yield from blank_line * self.bottom
124
+
125
+ def __rich_measure__(
126
+ self, console: "Console", options: "ConsoleOptions"
127
+ ) -> "Measurement":
128
+ max_width = options.max_width
129
+ extra_width = self.left + self.right
130
+ if max_width - extra_width < 1:
131
+ return Measurement(max_width, max_width)
132
+ measure_min, measure_max = Measurement.get(console, options, self.renderable)
133
+ measurement = Measurement(measure_min + extra_width, measure_max + extra_width)
134
+ measurement = measurement.with_maximum(max_width)
135
+ return measurement
136
+
137
+
138
+ if __name__ == "__main__": # pragma: no cover
139
+ from rich import print
140
+
141
+ print(Padding("Hello, World", (2, 4), style="on blue"))