Zednation commited on
Commit
9ad9b5f
·
verified ·
1 Parent(s): 8efd65a

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .DS_Store +0 -0
  2. .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_backends/_asyncio.py +0 -0
  3. .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_core/_subprocesses.py +196 -0
  4. .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_resources.py +33 -0
  5. .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_testing.py +65 -0
  6. .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/RECORD +22 -0
  7. .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/licenses/LICENSE.txt +28 -0
  8. .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/_textwrap.py +51 -0
  9. .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/parser.py +532 -0
  10. .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/termui.py +891 -0
  11. .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/testing.py +669 -0
  12. .cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec-2026.4.0.dist-info/METADATA +257 -0
  13. .cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec/callbacks.py +324 -0
  14. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/__init__.py +0 -0
  15. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/html_re.py +39 -0
  16. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/utils.py +313 -0
  17. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/__init__.py +6 -0
  18. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/parse_link_title.py +75 -0
  19. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/parser_core.py +46 -0
  20. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/port.yaml +48 -0
  21. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/default.py +36 -0
  22. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/zero.py +44 -0
  23. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/ruler.py +275 -0
  24. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/__init__.py +27 -0
  25. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/code.py +36 -0
  26. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/fence.py +101 -0
  27. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/hr.py +56 -0
  28. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/lheading.py +86 -0
  29. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/list.py +345 -0
  30. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/paragraph.py +66 -0
  31. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/__init__.py +19 -0
  32. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/linkify.py +149 -0
  33. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/normalize.py +19 -0
  34. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/text_join.py +35 -0
  35. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/backticks.py +72 -0
  36. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/balance_pairs.py +138 -0
  37. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/emphasis.py +102 -0
  38. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/linkify.py +62 -0
  39. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/newline.py +44 -0
  40. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/token.py +178 -0
  41. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/WHEEL +4 -0
  42. .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/entry_points.txt +3 -0
  43. .cache/uv/archive-v0/kP2PUXEYMUC0shkt92DN5/idna-3.13.dist-info/METADATA +204 -0
  44. .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging-26.2.dist-info/RECORD +27 -0
  45. .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/__init__.py +15 -0
  46. .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_parser.py +393 -0
  47. .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_structures.py +33 -0
  48. .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/dependency_groups.py +302 -0
  49. .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/errors.py +94 -0
  50. .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/py.typed +0 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_backends/_asyncio.py ADDED
The diff for this file is too large to render. See raw diff
 
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_core/_subprocesses.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
4
+ from io import BytesIO
5
+ from os import PathLike
6
+ from subprocess import PIPE, CalledProcessError, CompletedProcess
7
+ from typing import IO, Any, TypeAlias, cast
8
+
9
+ from ..abc import Process
10
+ from ._eventloop import get_async_backend
11
+ from ._tasks import create_task_group
12
+
13
+ StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes]
14
+
15
+
16
+ async def run_process(
17
+ command: StrOrBytesPath | Sequence[StrOrBytesPath],
18
+ *,
19
+ input: bytes | None = None,
20
+ stdin: int | IO[Any] | None = None,
21
+ stdout: int | IO[Any] | None = PIPE,
22
+ stderr: int | IO[Any] | None = PIPE,
23
+ check: bool = True,
24
+ cwd: StrOrBytesPath | None = None,
25
+ env: Mapping[str, str] | None = None,
26
+ startupinfo: Any = None,
27
+ creationflags: int = 0,
28
+ start_new_session: bool = False,
29
+ pass_fds: Sequence[int] = (),
30
+ user: str | int | None = None,
31
+ group: str | int | None = None,
32
+ extra_groups: Iterable[str | int] | None = None,
33
+ umask: int = -1,
34
+ ) -> CompletedProcess[bytes]:
35
+ """
36
+ Run an external command in a subprocess and wait until it completes.
37
+
38
+ .. seealso:: :func:`subprocess.run`
39
+
40
+ :param command: either a string to pass to the shell, or an iterable of strings
41
+ containing the executable name or path and its arguments
42
+ :param input: bytes passed to the standard input of the subprocess
43
+ :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
44
+ a file-like object, or `None`; ``input`` overrides this
45
+ :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
46
+ a file-like object, or `None`
47
+ :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
48
+ :data:`subprocess.STDOUT`, a file-like object, or `None`
49
+ :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the
50
+ process terminates with a return code other than 0
51
+ :param cwd: If not ``None``, change the working directory to this before running the
52
+ command
53
+ :param env: if not ``None``, this mapping replaces the inherited environment
54
+ variables from the parent process
55
+ :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used
56
+ to specify process startup parameters (Windows only)
57
+ :param creationflags: flags that can be used to control the creation of the
58
+ subprocess (see :class:`subprocess.Popen` for the specifics)
59
+ :param start_new_session: if ``true`` the setsid() system call will be made in the
60
+ child process prior to the execution of the subprocess. (POSIX only)
61
+ :param pass_fds: sequence of file descriptors to keep open between the parent and
62
+ child processes. (POSIX only)
63
+ :param user: effective user to run the process as (Python >= 3.9, POSIX only)
64
+ :param group: effective group to run the process as (Python >= 3.9, POSIX only)
65
+ :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9,
66
+ POSIX only)
67
+ :param umask: if not negative, this umask is applied in the child process before
68
+ running the given command (Python >= 3.9, POSIX only)
69
+ :return: an object representing the completed process
70
+ :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process
71
+ exits with a nonzero return code
72
+
73
+ """
74
+
75
+ async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None:
76
+ buffer = BytesIO()
77
+ async for chunk in stream:
78
+ buffer.write(chunk)
79
+
80
+ stream_contents[index] = buffer.getvalue()
81
+
82
+ if stdin is not None and input is not None:
83
+ raise ValueError("only one of stdin and input is allowed")
84
+
85
+ async with await open_process(
86
+ command,
87
+ stdin=PIPE if input else stdin,
88
+ stdout=stdout,
89
+ stderr=stderr,
90
+ cwd=cwd,
91
+ env=env,
92
+ startupinfo=startupinfo,
93
+ creationflags=creationflags,
94
+ start_new_session=start_new_session,
95
+ pass_fds=pass_fds,
96
+ user=user,
97
+ group=group,
98
+ extra_groups=extra_groups,
99
+ umask=umask,
100
+ ) as process:
101
+ stream_contents: list[bytes | None] = [None, None]
102
+ async with create_task_group() as tg:
103
+ if process.stdout:
104
+ tg.start_soon(drain_stream, process.stdout, 0)
105
+
106
+ if process.stderr:
107
+ tg.start_soon(drain_stream, process.stderr, 1)
108
+
109
+ if process.stdin and input:
110
+ await process.stdin.send(input)
111
+ await process.stdin.aclose()
112
+
113
+ await process.wait()
114
+
115
+ output, errors = stream_contents
116
+ if check and process.returncode != 0:
117
+ raise CalledProcessError(cast(int, process.returncode), command, output, errors)
118
+
119
+ return CompletedProcess(command, cast(int, process.returncode), output, errors)
120
+
121
+
122
+ async def open_process(
123
+ command: StrOrBytesPath | Sequence[StrOrBytesPath],
124
+ *,
125
+ stdin: int | IO[Any] | None = PIPE,
126
+ stdout: int | IO[Any] | None = PIPE,
127
+ stderr: int | IO[Any] | None = PIPE,
128
+ cwd: StrOrBytesPath | None = None,
129
+ env: Mapping[str, str] | None = None,
130
+ startupinfo: Any = None,
131
+ creationflags: int = 0,
132
+ start_new_session: bool = False,
133
+ pass_fds: Sequence[int] = (),
134
+ user: str | int | None = None,
135
+ group: str | int | None = None,
136
+ extra_groups: Iterable[str | int] | None = None,
137
+ umask: int = -1,
138
+ ) -> Process:
139
+ """
140
+ Start an external command in a subprocess.
141
+
142
+ .. seealso:: :class:`subprocess.Popen`
143
+
144
+ :param command: either a string to pass to the shell, or an iterable of strings
145
+ containing the executable name or path and its arguments
146
+ :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a
147
+ file-like object, or ``None``
148
+ :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
149
+ a file-like object, or ``None``
150
+ :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`,
151
+ :data:`subprocess.STDOUT`, a file-like object, or ``None``
152
+ :param cwd: If not ``None``, the working directory is changed before executing
153
+ :param env: If env is not ``None``, it must be a mapping that defines the
154
+ environment variables for the new process
155
+ :param creationflags: flags that can be used to control the creation of the
156
+ subprocess (see :class:`subprocess.Popen` for the specifics)
157
+ :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used
158
+ to specify process startup parameters (Windows only)
159
+ :param start_new_session: if ``true`` the setsid() system call will be made in the
160
+ child process prior to the execution of the subprocess. (POSIX only)
161
+ :param pass_fds: sequence of file descriptors to keep open between the parent and
162
+ child processes. (POSIX only)
163
+ :param user: effective user to run the process as (POSIX only)
164
+ :param group: effective group to run the process as (POSIX only)
165
+ :param extra_groups: supplementary groups to set in the subprocess (POSIX only)
166
+ :param umask: if not negative, this umask is applied in the child process before
167
+ running the given command (POSIX only)
168
+ :return: an asynchronous process object
169
+
170
+ """
171
+ kwargs: dict[str, Any] = {}
172
+ if user is not None:
173
+ kwargs["user"] = user
174
+
175
+ if group is not None:
176
+ kwargs["group"] = group
177
+
178
+ if extra_groups is not None:
179
+ kwargs["extra_groups"] = group
180
+
181
+ if umask >= 0:
182
+ kwargs["umask"] = umask
183
+
184
+ return await get_async_backend().open_process(
185
+ command,
186
+ stdin=stdin,
187
+ stdout=stdout,
188
+ stderr=stderr,
189
+ cwd=cwd,
190
+ env=env,
191
+ startupinfo=startupinfo,
192
+ creationflags=creationflags,
193
+ start_new_session=start_new_session,
194
+ pass_fds=pass_fds,
195
+ **kwargs,
196
+ )
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_resources.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import ABCMeta, abstractmethod
4
+ from types import TracebackType
5
+ from typing import TypeVar
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ class AsyncResource(metaclass=ABCMeta):
11
+ """
12
+ Abstract base class for all closeable asynchronous resources.
13
+
14
+ Works as an asynchronous context manager which returns the instance itself on enter,
15
+ and calls :meth:`aclose` on exit.
16
+ """
17
+
18
+ __slots__ = ()
19
+
20
+ async def __aenter__(self: T) -> T:
21
+ return self
22
+
23
+ async def __aexit__(
24
+ self,
25
+ exc_type: type[BaseException] | None,
26
+ exc_val: BaseException | None,
27
+ exc_tb: TracebackType | None,
28
+ ) -> None:
29
+ await self.aclose()
30
+
31
+ @abstractmethod
32
+ async def aclose(self) -> None:
33
+ """Close the resource."""
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_testing.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import types
4
+ from abc import ABCMeta, abstractmethod
5
+ from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable
6
+ from typing import Any, TypeVar
7
+
8
+ _T = TypeVar("_T")
9
+
10
+
11
+ class TestRunner(metaclass=ABCMeta):
12
+ """
13
+ Encapsulates a running event loop. Every call made through this object will use the
14
+ same event loop.
15
+ """
16
+
17
+ def __enter__(self) -> TestRunner:
18
+ return self
19
+
20
+ @abstractmethod
21
+ def __exit__(
22
+ self,
23
+ exc_type: type[BaseException] | None,
24
+ exc_val: BaseException | None,
25
+ exc_tb: types.TracebackType | None,
26
+ ) -> bool | None: ...
27
+
28
+ @abstractmethod
29
+ def run_asyncgen_fixture(
30
+ self,
31
+ fixture_func: Callable[..., AsyncGenerator[_T, Any]],
32
+ kwargs: dict[str, Any],
33
+ ) -> Iterable[_T]:
34
+ """
35
+ Run an async generator fixture.
36
+
37
+ :param fixture_func: the fixture function
38
+ :param kwargs: keyword arguments to call the fixture function with
39
+ :return: an iterator yielding the value yielded from the async generator
40
+ """
41
+
42
+ @abstractmethod
43
+ def run_fixture(
44
+ self,
45
+ fixture_func: Callable[..., Coroutine[Any, Any, _T]],
46
+ kwargs: dict[str, Any],
47
+ ) -> _T:
48
+ """
49
+ Run an async fixture.
50
+
51
+ :param fixture_func: the fixture function
52
+ :param kwargs: keyword arguments to call the fixture function with
53
+ :return: the return value of the fixture function
54
+ """
55
+
56
+ @abstractmethod
57
+ def run_test(
58
+ self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any]
59
+ ) -> None:
60
+ """
61
+ Run an async test function.
62
+
63
+ :param test_func: the test function
64
+ :param kwargs: keyword arguments to call the test function with
65
+ """
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/RECORD ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ click/__init__.py,sha256=tq5olp0lVuUNbwOj0p5nMVdqhOyYz4aZzF8S5T0aFMU,4526
2
+ click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693
3
+ click/_termui_impl.py,sha256=R3aYjPD2x1xgNXiXEqHSR-jAVhbXKkLKeqgr-4eDOkA,28066
4
+ click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400
5
+ click/_utils.py,sha256=kZwtTf5gMuCilJJceS2iTCvRvCY-0aN5rJq8gKw7p8g,943
6
+ click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465
7
+ click/core.py,sha256=wzDpH4Wh45hBfsdw3BHqn_095457WRrb92dyaeIGkHk,134478
8
+ click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461
9
+ click/exceptions.py,sha256=8utf8w6V5hJXMnO_ic1FNrtbwuEn1NUu1aDwV8UqnG4,9954
10
+ click/formatting.py,sha256=RVfwwr0rwWNpgGr8NaHodPzkIr7_tUyVh_nDdanLMNc,9730
11
+ click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923
12
+ click/parser.py,sha256=Q31pH0FlQZEq-UXE_ABRzlygEfvxPTuZbWNh4xfXmzw,19010
13
+ click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ click/shell_completion.py,sha256=Cc4GQUFuWpfQBa9sF5qXeeYI7n3tI_1k6ZdSn4BZbT0,20994
15
+ click/termui.py,sha256=0xjUaEZJz1_1y8eqon2kOe2OXrmHzZCJoVohFb43yTs,31434
16
+ click/testing.py,sha256=PYLYW4ZjCAP6HRWtNhFpr3imJxQVEPFq3EW3JL0LTfA,22714
17
+ click/types.py,sha256=ek54BNSFwPKsqtfT7jsqcc4WHui8AIFVMKM4oVZIXhc,39927
18
+ click/utils.py,sha256=vep6qqMkv3WkzA9OCu7f6Ku-3beZHNpo8qJqL-uzUk8,20282
19
+ click-8.3.3.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475
20
+ click-8.3.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
21
+ click-8.3.3.dist-info/METADATA,sha256=_sjhT7_ZKYkyseqbWJtQA8eAcV2CeDJdcNrX_92pSCY,2621
22
+ click-8.3.3.dist-info/RECORD,,
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2014 Pallets
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
21
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
24
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/_textwrap.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import textwrap
5
+ from contextlib import contextmanager
6
+
7
+
8
+ class TextWrapper(textwrap.TextWrapper):
9
+ def _handle_long_word(
10
+ self,
11
+ reversed_chunks: list[str],
12
+ cur_line: list[str],
13
+ cur_len: int,
14
+ width: int,
15
+ ) -> None:
16
+ space_left = max(width - cur_len, 1)
17
+
18
+ if self.break_long_words:
19
+ last = reversed_chunks[-1]
20
+ cut = last[:space_left]
21
+ res = last[space_left:]
22
+ cur_line.append(cut)
23
+ reversed_chunks[-1] = res
24
+ elif not cur_line:
25
+ cur_line.append(reversed_chunks.pop())
26
+
27
+ @contextmanager
28
+ def extra_indent(self, indent: str) -> cabc.Iterator[None]:
29
+ old_initial_indent = self.initial_indent
30
+ old_subsequent_indent = self.subsequent_indent
31
+ self.initial_indent += indent
32
+ self.subsequent_indent += indent
33
+
34
+ try:
35
+ yield
36
+ finally:
37
+ self.initial_indent = old_initial_indent
38
+ self.subsequent_indent = old_subsequent_indent
39
+
40
+ def indent_only(self, text: str) -> str:
41
+ rv = []
42
+
43
+ for idx, line in enumerate(text.splitlines()):
44
+ indent = self.initial_indent
45
+
46
+ if idx > 0:
47
+ indent = self.subsequent_indent
48
+
49
+ rv.append(f"{indent}{line}")
50
+
51
+ return "\n".join(rv)
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/parser.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module started out as largely a copy paste from the stdlib's
3
+ optparse module with the features removed that we do not need from
4
+ optparse because we implement them in Click on a higher level (for
5
+ instance type handling, help formatting and a lot more).
6
+
7
+ The plan is to remove more and more from here over time.
8
+
9
+ The reason this is a different module and not optparse from the stdlib
10
+ is that there are differences in 2.x and 3.x about the error messages
11
+ generated and optparse in the stdlib uses gettext for no good reason
12
+ and might cause us issues.
13
+
14
+ Click uses parts of optparse written by Gregory P. Ward and maintained
15
+ by the Python Software Foundation. This is limited to code in parser.py.
16
+
17
+ Copyright 2001-2006 Gregory P. Ward. All rights reserved.
18
+ Copyright 2002-2006 Python Software Foundation. All rights reserved.
19
+ """
20
+
21
+ # This code uses parts of optparse written by Gregory P. Ward and
22
+ # maintained by the Python Software Foundation.
23
+ # Copyright 2001-2006 Gregory P. Ward
24
+ # Copyright 2002-2006 Python Software Foundation
25
+ from __future__ import annotations
26
+
27
+ import collections.abc as cabc
28
+ import typing as t
29
+ from collections import deque
30
+ from gettext import gettext as _
31
+ from gettext import ngettext
32
+
33
+ from ._utils import FLAG_NEEDS_VALUE
34
+ from ._utils import UNSET
35
+ from .exceptions import BadArgumentUsage
36
+ from .exceptions import BadOptionUsage
37
+ from .exceptions import NoSuchOption
38
+ from .exceptions import UsageError
39
+
40
+ if t.TYPE_CHECKING:
41
+ from ._utils import T_FLAG_NEEDS_VALUE
42
+ from ._utils import T_UNSET
43
+ from .core import Argument as CoreArgument
44
+ from .core import Context
45
+ from .core import Option as CoreOption
46
+ from .core import Parameter as CoreParameter
47
+
48
+ V = t.TypeVar("V")
49
+
50
+
51
+ def _unpack_args(
52
+ args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]
53
+ ) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]:
54
+ """Given an iterable of arguments and an iterable of nargs specifications,
55
+ it returns a tuple with all the unpacked arguments at the first index
56
+ and all remaining arguments as the second.
57
+
58
+ The nargs specification is the number of arguments that should be consumed
59
+ or `-1` to indicate that this position should eat up all the remainders.
60
+
61
+ Missing items are filled with ``UNSET``.
62
+ """
63
+ args = deque(args)
64
+ nargs_spec = deque(nargs_spec)
65
+ rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []
66
+ spos: int | None = None
67
+
68
+ def _fetch(c: deque[V]) -> V | T_UNSET:
69
+ try:
70
+ if spos is None:
71
+ return c.popleft()
72
+ else:
73
+ return c.pop()
74
+ except IndexError:
75
+ return UNSET
76
+
77
+ while nargs_spec:
78
+ nargs = _fetch(nargs_spec)
79
+
80
+ if nargs is None:
81
+ continue
82
+
83
+ if nargs == 1:
84
+ rv.append(_fetch(args)) # type: ignore[arg-type]
85
+ elif nargs > 1:
86
+ x = [_fetch(args) for _ in range(nargs)]
87
+
88
+ # If we're reversed, we're pulling in the arguments in reverse,
89
+ # so we need to turn them around.
90
+ if spos is not None:
91
+ x.reverse()
92
+
93
+ rv.append(tuple(x))
94
+ elif nargs < 0:
95
+ if spos is not None:
96
+ raise TypeError("Cannot have two nargs < 0")
97
+
98
+ spos = len(rv)
99
+ rv.append(UNSET)
100
+
101
+ # spos is the position of the wildcard (star). If it's not `None`,
102
+ # we fill it with the remainder.
103
+ if spos is not None:
104
+ rv[spos] = tuple(args)
105
+ args = []
106
+ rv[spos + 1 :] = reversed(rv[spos + 1 :])
107
+
108
+ return tuple(rv), list(args)
109
+
110
+
111
+ def _split_opt(opt: str) -> tuple[str, str]:
112
+ first = opt[:1]
113
+ if first.isalnum():
114
+ return "", opt
115
+ if opt[1:2] == first:
116
+ return opt[:2], opt[2:]
117
+ return first, opt[1:]
118
+
119
+
120
+ def _normalize_opt(opt: str, ctx: Context | None) -> str:
121
+ if ctx is None or ctx.token_normalize_func is None:
122
+ return opt
123
+ prefix, opt = _split_opt(opt)
124
+ return f"{prefix}{ctx.token_normalize_func(opt)}"
125
+
126
+
127
+ class _Option:
128
+ def __init__(
129
+ self,
130
+ obj: CoreOption,
131
+ opts: cabc.Sequence[str],
132
+ dest: str | None,
133
+ action: str | None = None,
134
+ nargs: int = 1,
135
+ const: t.Any | None = None,
136
+ ):
137
+ self._short_opts = []
138
+ self._long_opts = []
139
+ self.prefixes: set[str] = set()
140
+
141
+ for opt in opts:
142
+ prefix, value = _split_opt(opt)
143
+ if not prefix:
144
+ raise ValueError(f"Invalid start character for option ({opt})")
145
+ self.prefixes.add(prefix[0])
146
+ if len(prefix) == 1 and len(value) == 1:
147
+ self._short_opts.append(opt)
148
+ else:
149
+ self._long_opts.append(opt)
150
+ self.prefixes.add(prefix)
151
+
152
+ if action is None:
153
+ action = "store"
154
+
155
+ self.dest = dest
156
+ self.action = action
157
+ self.nargs = nargs
158
+ self.const = const
159
+ self.obj = obj
160
+
161
+ @property
162
+ def takes_value(self) -> bool:
163
+ return self.action in ("store", "append")
164
+
165
+ def process(self, value: t.Any, state: _ParsingState) -> None:
166
+ if self.action == "store":
167
+ state.opts[self.dest] = value # type: ignore
168
+ elif self.action == "store_const":
169
+ state.opts[self.dest] = self.const # type: ignore
170
+ elif self.action == "append":
171
+ state.opts.setdefault(self.dest, []).append(value) # type: ignore
172
+ elif self.action == "append_const":
173
+ state.opts.setdefault(self.dest, []).append(self.const) # type: ignore
174
+ elif self.action == "count":
175
+ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore
176
+ else:
177
+ raise ValueError(f"unknown action '{self.action}'")
178
+ state.order.append(self.obj)
179
+
180
+
181
+ class _Argument:
182
+ def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1):
183
+ self.dest = dest
184
+ self.nargs = nargs
185
+ self.obj = obj
186
+
187
+ def process(
188
+ self,
189
+ value: str | cabc.Sequence[str | None] | None | T_UNSET,
190
+ state: _ParsingState,
191
+ ) -> None:
192
+ if self.nargs > 1:
193
+ assert isinstance(value, cabc.Sequence)
194
+ holes = sum(1 for x in value if x is UNSET)
195
+ if holes == len(value):
196
+ value = UNSET
197
+ elif holes != 0:
198
+ raise BadArgumentUsage(
199
+ _("Argument {name!r} takes {nargs} values.").format(
200
+ name=self.dest, nargs=self.nargs
201
+ )
202
+ )
203
+
204
+ # We failed to collect any argument value so we consider the argument as unset.
205
+ if value == ():
206
+ value = UNSET
207
+
208
+ state.opts[self.dest] = value # type: ignore
209
+ state.order.append(self.obj)
210
+
211
+
212
+ class _ParsingState:
213
+ def __init__(self, rargs: list[str]) -> None:
214
+ self.opts: dict[str, t.Any] = {}
215
+ self.largs: list[str] = []
216
+ self.rargs = rargs
217
+ self.order: list[CoreParameter] = []
218
+
219
+
220
+ class _OptionParser:
221
+ """The option parser is an internal class that is ultimately used to
222
+ parse options and arguments. It's modelled after optparse and brings
223
+ a similar but vastly simplified API. It should generally not be used
224
+ directly as the high level Click classes wrap it for you.
225
+
226
+ It's not nearly as extensible as optparse or argparse as it does not
227
+ implement features that are implemented on a higher level (such as
228
+ types or defaults).
229
+
230
+ :param ctx: optionally the :class:`~click.Context` where this parser
231
+ should go with.
232
+
233
+ .. deprecated:: 8.2
234
+ Will be removed in Click 9.0.
235
+ """
236
+
237
+ def __init__(self, ctx: Context | None = None) -> None:
238
+ #: The :class:`~click.Context` for this parser. This might be
239
+ #: `None` for some advanced use cases.
240
+ self.ctx = ctx
241
+ #: This controls how the parser deals with interspersed arguments.
242
+ #: If this is set to `False`, the parser will stop on the first
243
+ #: non-option. Click uses this to implement nested subcommands
244
+ #: safely.
245
+ self.allow_interspersed_args: bool = True
246
+ #: This tells the parser how to deal with unknown options. By
247
+ #: default it will error out (which is sensible), but there is a
248
+ #: second mode where it will ignore it and continue processing
249
+ #: after shifting all the unknown options into the resulting args.
250
+ self.ignore_unknown_options: bool = False
251
+
252
+ if ctx is not None:
253
+ self.allow_interspersed_args = ctx.allow_interspersed_args
254
+ self.ignore_unknown_options = ctx.ignore_unknown_options
255
+
256
+ self._short_opt: dict[str, _Option] = {}
257
+ self._long_opt: dict[str, _Option] = {}
258
+ self._opt_prefixes = {"-", "--"}
259
+ self._args: list[_Argument] = []
260
+
261
+ def add_option(
262
+ self,
263
+ obj: CoreOption,
264
+ opts: cabc.Sequence[str],
265
+ dest: str | None,
266
+ action: str | None = None,
267
+ nargs: int = 1,
268
+ const: t.Any | None = None,
269
+ ) -> None:
270
+ """Adds a new option named `dest` to the parser. The destination
271
+ is not inferred (unlike with optparse) and needs to be explicitly
272
+ provided. Action can be any of ``store``, ``store_const``,
273
+ ``append``, ``append_const`` or ``count``.
274
+
275
+ The `obj` can be used to identify the option in the order list
276
+ that is returned from the parser.
277
+ """
278
+ opts = [_normalize_opt(opt, self.ctx) for opt in opts]
279
+ option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const)
280
+ self._opt_prefixes.update(option.prefixes)
281
+ for opt in option._short_opts:
282
+ self._short_opt[opt] = option
283
+ for opt in option._long_opts:
284
+ self._long_opt[opt] = option
285
+
286
+ def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None:
287
+ """Adds a positional argument named `dest` to the parser.
288
+
289
+ The `obj` can be used to identify the option in the order list
290
+ that is returned from the parser.
291
+ """
292
+ self._args.append(_Argument(obj, dest=dest, nargs=nargs))
293
+
294
+ def parse_args(
295
+ self, args: list[str]
296
+ ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]:
297
+ """Parses positional arguments and returns ``(values, args, order)``
298
+ for the parsed options and arguments as well as the leftover
299
+ arguments if there are any. The order is a list of objects as they
300
+ appear on the command line. If arguments appear multiple times they
301
+ will be memorized multiple times as well.
302
+ """
303
+ state = _ParsingState(args)
304
+ try:
305
+ self._process_args_for_options(state)
306
+ self._process_args_for_args(state)
307
+ except UsageError:
308
+ if self.ctx is None or not self.ctx.resilient_parsing:
309
+ raise
310
+ return state.opts, state.largs, state.order
311
+
312
+ def _process_args_for_args(self, state: _ParsingState) -> None:
313
+ pargs, args = _unpack_args(
314
+ state.largs + state.rargs, [x.nargs for x in self._args]
315
+ )
316
+
317
+ for idx, arg in enumerate(self._args):
318
+ arg.process(pargs[idx], state)
319
+
320
+ state.largs = args
321
+ state.rargs = []
322
+
323
+ def _process_args_for_options(self, state: _ParsingState) -> None:
324
+ while state.rargs:
325
+ arg = state.rargs.pop(0)
326
+ arglen = len(arg)
327
+ # Double dashes always handled explicitly regardless of what
328
+ # prefixes are valid.
329
+ if arg == "--":
330
+ return
331
+ elif arg[:1] in self._opt_prefixes and arglen > 1:
332
+ self._process_opts(arg, state)
333
+ elif self.allow_interspersed_args:
334
+ state.largs.append(arg)
335
+ else:
336
+ state.rargs.insert(0, arg)
337
+ return
338
+
339
+ # Say this is the original argument list:
340
+ # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
341
+ # ^
342
+ # (we are about to process arg(i)).
343
+ #
344
+ # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
345
+ # [arg0, ..., arg(i-1)] (any options and their arguments will have
346
+ # been removed from largs).
347
+ #
348
+ # The while loop will usually consume 1 or more arguments per pass.
349
+ # If it consumes 1 (eg. arg is an option that takes no arguments),
350
+ # then after _process_arg() is done the situation is:
351
+ #
352
+ # largs = subset of [arg0, ..., arg(i)]
353
+ # rargs = [arg(i+1), ..., arg(N-1)]
354
+ #
355
+ # If allow_interspersed_args is false, largs will always be
356
+ # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
357
+ # not a very interesting subset!
358
+
359
+ def _match_long_opt(
360
+ self, opt: str, explicit_value: str | None, state: _ParsingState
361
+ ) -> None:
362
+ if opt not in self._long_opt:
363
+ from difflib import get_close_matches
364
+
365
+ possibilities = get_close_matches(opt, self._long_opt)
366
+ raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
367
+
368
+ option = self._long_opt[opt]
369
+ if option.takes_value:
370
+ # At this point it's safe to modify rargs by injecting the
371
+ # explicit value, because no exception is raised in this
372
+ # branch. This means that the inserted value will be fully
373
+ # consumed.
374
+ if explicit_value is not None:
375
+ state.rargs.insert(0, explicit_value)
376
+
377
+ value = self._get_value_from_state(opt, option, state)
378
+
379
+ elif explicit_value is not None:
380
+ raise BadOptionUsage(
381
+ opt, _("Option {name!r} does not take a value.").format(name=opt)
382
+ )
383
+
384
+ else:
385
+ value = UNSET
386
+
387
+ option.process(value, state)
388
+
389
+ def _match_short_opt(self, arg: str, state: _ParsingState) -> None:
390
+ stop = False
391
+ i = 1
392
+ prefix = arg[0]
393
+ unknown_options = []
394
+
395
+ for ch in arg[1:]:
396
+ opt = _normalize_opt(f"{prefix}{ch}", self.ctx)
397
+ option = self._short_opt.get(opt)
398
+ i += 1
399
+
400
+ if not option:
401
+ if self.ignore_unknown_options:
402
+ unknown_options.append(ch)
403
+ continue
404
+ raise NoSuchOption(opt, ctx=self.ctx)
405
+ if option.takes_value:
406
+ # Any characters left in arg? Pretend they're the
407
+ # next arg, and stop consuming characters of arg.
408
+ if i < len(arg):
409
+ state.rargs.insert(0, arg[i:])
410
+ stop = True
411
+
412
+ value = self._get_value_from_state(opt, option, state)
413
+
414
+ else:
415
+ value = UNSET
416
+
417
+ option.process(value, state)
418
+
419
+ if stop:
420
+ break
421
+
422
+ # If we got any unknown options we recombine the string of the
423
+ # remaining options and re-attach the prefix, then report that
424
+ # to the state as new larg. This way there is basic combinatorics
425
+ # that can be achieved while still ignoring unknown arguments.
426
+ if self.ignore_unknown_options and unknown_options:
427
+ state.largs.append(f"{prefix}{''.join(unknown_options)}")
428
+
429
+ def _get_value_from_state(
430
+ self, option_name: str, option: _Option, state: _ParsingState
431
+ ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE:
432
+ nargs = option.nargs
433
+
434
+ value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE
435
+
436
+ if len(state.rargs) < nargs:
437
+ if option.obj._flag_needs_value:
438
+ # Option allows omitting the value.
439
+ value = FLAG_NEEDS_VALUE
440
+ else:
441
+ raise BadOptionUsage(
442
+ option_name,
443
+ ngettext(
444
+ "Option {name!r} requires an argument.",
445
+ "Option {name!r} requires {nargs} arguments.",
446
+ nargs,
447
+ ).format(name=option_name, nargs=nargs),
448
+ )
449
+ elif nargs == 1:
450
+ next_rarg = state.rargs[0]
451
+
452
+ if (
453
+ option.obj._flag_needs_value
454
+ and isinstance(next_rarg, str)
455
+ and next_rarg[:1] in self._opt_prefixes
456
+ and len(next_rarg) > 1
457
+ ):
458
+ # The next arg looks like the start of an option, don't
459
+ # use it as the value if omitting the value is allowed.
460
+ value = FLAG_NEEDS_VALUE
461
+ else:
462
+ value = state.rargs.pop(0)
463
+ else:
464
+ value = tuple(state.rargs[:nargs])
465
+ del state.rargs[:nargs]
466
+
467
+ return value
468
+
469
+ def _process_opts(self, arg: str, state: _ParsingState) -> None:
470
+ explicit_value = None
471
+ # Long option handling happens in two parts. The first part is
472
+ # supporting explicitly attached values. In any case, we will try
473
+ # to long match the option first.
474
+ if "=" in arg:
475
+ long_opt, explicit_value = arg.split("=", 1)
476
+ else:
477
+ long_opt = arg
478
+ norm_long_opt = _normalize_opt(long_opt, self.ctx)
479
+
480
+ # At this point we will match the (assumed) long option through
481
+ # the long option matching code. Note that this allows options
482
+ # like "-foo" to be matched as long options.
483
+ try:
484
+ self._match_long_opt(norm_long_opt, explicit_value, state)
485
+ except NoSuchOption:
486
+ # At this point the long option matching failed, and we need
487
+ # to try with short options. However there is a special rule
488
+ # which says, that if we have a two character options prefix
489
+ # (applies to "--foo" for instance), we do not dispatch to the
490
+ # short option code and will instead raise the no option
491
+ # error.
492
+ if arg[:2] not in self._opt_prefixes:
493
+ self._match_short_opt(arg, state)
494
+ return
495
+
496
+ if not self.ignore_unknown_options:
497
+ raise
498
+
499
+ state.largs.append(arg)
500
+
501
+
502
+ def __getattr__(name: str) -> object:
503
+ import warnings
504
+
505
+ if name in {
506
+ "OptionParser",
507
+ "Argument",
508
+ "Option",
509
+ "split_opt",
510
+ "normalize_opt",
511
+ "ParsingState",
512
+ }:
513
+ warnings.warn(
514
+ f"'parser.{name}' is deprecated and will be removed in Click 9.0."
515
+ " The old parser is available in 'optparse'.",
516
+ DeprecationWarning,
517
+ stacklevel=2,
518
+ )
519
+ return globals()[f"_{name}"]
520
+
521
+ if name == "split_arg_string":
522
+ from .shell_completion import split_arg_string
523
+
524
+ warnings.warn(
525
+ "Importing 'parser.split_arg_string' is deprecated, it will only be"
526
+ " available in 'shell_completion' in Click 9.0.",
527
+ DeprecationWarning,
528
+ stacklevel=2,
529
+ )
530
+ return split_arg_string
531
+
532
+ raise AttributeError(name)
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/termui.py ADDED
@@ -0,0 +1,891 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import inspect
5
+ import io
6
+ import itertools
7
+ import sys
8
+ import typing as t
9
+ from contextlib import AbstractContextManager
10
+ from gettext import gettext as _
11
+
12
+ from ._compat import isatty
13
+ from ._compat import strip_ansi
14
+ from .exceptions import Abort
15
+ from .exceptions import UsageError
16
+ from .globals import resolve_color_default
17
+ from .types import Choice
18
+ from .types import convert_type
19
+ from .types import ParamType
20
+ from .utils import echo
21
+ from .utils import LazyFile
22
+
23
+ if t.TYPE_CHECKING:
24
+ from ._termui_impl import ProgressBar
25
+
26
+ V = t.TypeVar("V")
27
+
28
+ # The prompt functions to use. The doc tools currently override these
29
+ # functions to customize how they work.
30
+ visible_prompt_func: t.Callable[[str], str] = input
31
+
32
+ _ansi_colors = {
33
+ "black": 30,
34
+ "red": 31,
35
+ "green": 32,
36
+ "yellow": 33,
37
+ "blue": 34,
38
+ "magenta": 35,
39
+ "cyan": 36,
40
+ "white": 37,
41
+ "reset": 39,
42
+ "bright_black": 90,
43
+ "bright_red": 91,
44
+ "bright_green": 92,
45
+ "bright_yellow": 93,
46
+ "bright_blue": 94,
47
+ "bright_magenta": 95,
48
+ "bright_cyan": 96,
49
+ "bright_white": 97,
50
+ }
51
+ _ansi_reset_all = "\033[0m"
52
+
53
+
54
+ def hidden_prompt_func(prompt: str) -> str:
55
+ import getpass
56
+
57
+ return getpass.getpass(prompt)
58
+
59
+
60
+ def _build_prompt(
61
+ text: str,
62
+ suffix: str,
63
+ show_default: bool | str = False,
64
+ default: t.Any | None = None,
65
+ show_choices: bool = True,
66
+ type: ParamType | None = None,
67
+ ) -> str:
68
+ prompt = text
69
+ if type is not None and show_choices and isinstance(type, Choice):
70
+ prompt += f" ({', '.join(map(str, type.choices))})"
71
+ if isinstance(show_default, str):
72
+ default = f"({show_default})"
73
+ if default is not None and show_default:
74
+ prompt = f"{prompt} [{_format_default(default)}]"
75
+ return f"{prompt}{suffix}"
76
+
77
+
78
+ def _format_default(default: t.Any) -> t.Any:
79
+ if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
80
+ return default.name
81
+
82
+ return default
83
+
84
+
85
+ def prompt(
86
+ text: str,
87
+ default: t.Any | None = None,
88
+ hide_input: bool = False,
89
+ confirmation_prompt: bool | str = False,
90
+ type: ParamType | t.Any | None = None,
91
+ value_proc: t.Callable[[str], t.Any] | None = None,
92
+ prompt_suffix: str = ": ",
93
+ show_default: bool | str = True,
94
+ err: bool = False,
95
+ show_choices: bool = True,
96
+ ) -> t.Any:
97
+ """Prompts a user for input. This is a convenience function that can
98
+ be used to prompt a user for input later.
99
+
100
+ If the user aborts the input by sending an interrupt signal, this
101
+ function will catch it and raise a :exc:`Abort` exception.
102
+
103
+ :param text: the text to show for the prompt.
104
+ :param default: the default value to use if no input happens. If this
105
+ is not given it will prompt until it's aborted.
106
+ :param hide_input: if this is set to true then the input value will
107
+ be hidden.
108
+ :param confirmation_prompt: Prompt a second time to confirm the
109
+ value. Can be set to a string instead of ``True`` to customize
110
+ the message.
111
+ :param type: the type to use to check the value against.
112
+ :param value_proc: if this parameter is provided it's a function that
113
+ is invoked instead of the type conversion to
114
+ convert a value.
115
+ :param prompt_suffix: a suffix that should be added to the prompt.
116
+ :param show_default: shows or hides the default value in the prompt.
117
+ If this value is a string, it shows that string
118
+ in parentheses instead of the actual value.
119
+ :param err: if set to true the file defaults to ``stderr`` instead of
120
+ ``stdout``, the same as with echo.
121
+ :param show_choices: Show or hide choices if the passed type is a Choice.
122
+ For example if type is a Choice of either day or week,
123
+ show_choices is true and text is "Group by" then the
124
+ prompt will be "Group by (day, week): ".
125
+
126
+ .. versionchanged:: 8.3.3
127
+ ``show_default`` can be a string to show a custom value instead
128
+ of the actual default, matching the help text behavior.
129
+
130
+ .. versionchanged:: 8.3.1
131
+ A space is no longer appended to the prompt.
132
+
133
+ .. versionadded:: 8.0
134
+ ``confirmation_prompt`` can be a custom string.
135
+
136
+ .. versionadded:: 7.0
137
+ Added the ``show_choices`` parameter.
138
+
139
+ .. versionadded:: 6.0
140
+ Added unicode support for cmd.exe on Windows.
141
+
142
+ .. versionadded:: 4.0
143
+ Added the `err` parameter.
144
+
145
+ """
146
+
147
+ def prompt_func(text: str) -> str:
148
+ f = hidden_prompt_func if hide_input else visible_prompt_func
149
+ try:
150
+ # Write the prompt separately so that we get nice
151
+ # coloring through colorama on Windows
152
+ echo(text[:-1], nl=False, err=err)
153
+ # Echo the last character to stdout to work around an issue where
154
+ # readline causes backspace to clear the whole line.
155
+ return f(text[-1:])
156
+ except (KeyboardInterrupt, EOFError):
157
+ # getpass doesn't print a newline if the user aborts input with ^C.
158
+ # Allegedly this behavior is inherited from getpass(3).
159
+ # A doc bug has been filed at https://bugs.python.org/issue24711
160
+ if hide_input:
161
+ echo(None, err=err)
162
+ raise Abort() from None
163
+
164
+ if value_proc is None:
165
+ value_proc = convert_type(type, default)
166
+
167
+ prompt = _build_prompt(
168
+ text, prompt_suffix, show_default, default, show_choices, type
169
+ )
170
+
171
+ if confirmation_prompt:
172
+ if confirmation_prompt is True:
173
+ confirmation_prompt = _("Repeat for confirmation")
174
+
175
+ confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
176
+
177
+ while True:
178
+ while True:
179
+ value = prompt_func(prompt)
180
+ if value:
181
+ break
182
+ elif default is not None:
183
+ value = default
184
+ break
185
+ try:
186
+ result = value_proc(value)
187
+ except UsageError as e:
188
+ if hide_input:
189
+ echo(_("Error: The value you entered was invalid."), err=err)
190
+ else:
191
+ echo(_("Error: {e.message}").format(e=e), err=err)
192
+ continue
193
+ if not confirmation_prompt:
194
+ return result
195
+ while True:
196
+ value2 = prompt_func(confirmation_prompt)
197
+ is_empty = not value and not value2
198
+ if value2 or is_empty:
199
+ break
200
+ if value == value2:
201
+ return result
202
+ echo(_("Error: The two entered values do not match."), err=err)
203
+
204
+
205
+ def confirm(
206
+ text: str,
207
+ default: bool | None = False,
208
+ abort: bool = False,
209
+ prompt_suffix: str = ": ",
210
+ show_default: bool = True,
211
+ err: bool = False,
212
+ ) -> bool:
213
+ """Prompts for confirmation (yes/no question).
214
+
215
+ If the user aborts the input by sending a interrupt signal this
216
+ function will catch it and raise a :exc:`Abort` exception.
217
+
218
+ :param text: the question to ask.
219
+ :param default: The default value to use when no input is given. If
220
+ ``None``, repeat until input is given.
221
+ :param abort: if this is set to `True` a negative answer aborts the
222
+ exception by raising :exc:`Abort`.
223
+ :param prompt_suffix: a suffix that should be added to the prompt.
224
+ :param show_default: shows or hides the default value in the prompt.
225
+ :param err: if set to true the file defaults to ``stderr`` instead of
226
+ ``stdout``, the same as with echo.
227
+
228
+ .. versionchanged:: 8.3.1
229
+ A space is no longer appended to the prompt.
230
+
231
+ .. versionchanged:: 8.0
232
+ Repeat until input is given if ``default`` is ``None``.
233
+
234
+ .. versionadded:: 4.0
235
+ Added the ``err`` parameter.
236
+ """
237
+ prompt = _build_prompt(
238
+ text,
239
+ prompt_suffix,
240
+ show_default,
241
+ "y/n" if default is None else ("Y/n" if default else "y/N"),
242
+ )
243
+
244
+ while True:
245
+ try:
246
+ # Write the prompt separately so that we get nice
247
+ # coloring through colorama on Windows
248
+ echo(prompt[:-1], nl=False, err=err)
249
+ # Echo the last character to stdout to work around an issue where
250
+ # readline causes backspace to clear the whole line.
251
+ value = visible_prompt_func(prompt[-1:]).lower().strip()
252
+ except (KeyboardInterrupt, EOFError):
253
+ raise Abort() from None
254
+ if value in ("y", "yes"):
255
+ rv = True
256
+ elif value in ("n", "no"):
257
+ rv = False
258
+ elif default is not None and value == "":
259
+ rv = default
260
+ else:
261
+ echo(_("Error: invalid input"), err=err)
262
+ continue
263
+ break
264
+ if abort and not rv:
265
+ raise Abort()
266
+ return rv
267
+
268
+
269
+ def echo_via_pager(
270
+ text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,
271
+ color: bool | None = None,
272
+ ) -> None:
273
+ """This function takes a text and shows it via an environment specific
274
+ pager on stdout.
275
+
276
+ .. versionchanged:: 3.0
277
+ Added the `color` flag.
278
+
279
+ :param text_or_generator: the text to page, or alternatively, a
280
+ generator emitting the text to page.
281
+ :param color: controls if the pager supports ANSI colors or not. The
282
+ default is autodetection.
283
+ """
284
+ color = resolve_color_default(color)
285
+
286
+ if inspect.isgeneratorfunction(text_or_generator):
287
+ i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()
288
+ elif isinstance(text_or_generator, str):
289
+ i = [text_or_generator]
290
+ else:
291
+ i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
292
+
293
+ # convert every element of i to a text type if necessary
294
+ text_generator = (el if isinstance(el, str) else str(el) for el in i)
295
+
296
+ from ._termui_impl import pager
297
+
298
+ return pager(itertools.chain(text_generator, "\n"), color)
299
+
300
+
301
+ @t.overload
302
+ def progressbar(
303
+ *,
304
+ length: int,
305
+ label: str | None = None,
306
+ hidden: bool = False,
307
+ show_eta: bool = True,
308
+ show_percent: bool | None = None,
309
+ show_pos: bool = False,
310
+ fill_char: str = "#",
311
+ empty_char: str = "-",
312
+ bar_template: str = "%(label)s [%(bar)s] %(info)s",
313
+ info_sep: str = " ",
314
+ width: int = 36,
315
+ file: t.TextIO | None = None,
316
+ color: bool | None = None,
317
+ update_min_steps: int = 1,
318
+ ) -> ProgressBar[int]: ...
319
+
320
+
321
+ @t.overload
322
+ def progressbar(
323
+ iterable: cabc.Iterable[V] | None = None,
324
+ length: int | None = None,
325
+ label: str | None = None,
326
+ hidden: bool = False,
327
+ show_eta: bool = True,
328
+ show_percent: bool | None = None,
329
+ show_pos: bool = False,
330
+ item_show_func: t.Callable[[V | None], str | None] | None = None,
331
+ fill_char: str = "#",
332
+ empty_char: str = "-",
333
+ bar_template: str = "%(label)s [%(bar)s] %(info)s",
334
+ info_sep: str = " ",
335
+ width: int = 36,
336
+ file: t.TextIO | None = None,
337
+ color: bool | None = None,
338
+ update_min_steps: int = 1,
339
+ ) -> ProgressBar[V]: ...
340
+
341
+
342
+ def progressbar(
343
+ iterable: cabc.Iterable[V] | None = None,
344
+ length: int | None = None,
345
+ label: str | None = None,
346
+ hidden: bool = False,
347
+ show_eta: bool = True,
348
+ show_percent: bool | None = None,
349
+ show_pos: bool = False,
350
+ item_show_func: t.Callable[[V | None], str | None] | None = None,
351
+ fill_char: str = "#",
352
+ empty_char: str = "-",
353
+ bar_template: str = "%(label)s [%(bar)s] %(info)s",
354
+ info_sep: str = " ",
355
+ width: int = 36,
356
+ file: t.TextIO | None = None,
357
+ color: bool | None = None,
358
+ update_min_steps: int = 1,
359
+ ) -> ProgressBar[V]:
360
+ """This function creates an iterable context manager that can be used
361
+ to iterate over something while showing a progress bar. It will
362
+ either iterate over the `iterable` or `length` items (that are counted
363
+ up). While iteration happens, this function will print a rendered
364
+ progress bar to the given `file` (defaults to stdout) and will attempt
365
+ to calculate remaining time and more. By default, this progress bar
366
+ will not be rendered if the file is not a terminal.
367
+
368
+ The context manager creates the progress bar. When the context
369
+ manager is entered the progress bar is already created. With every
370
+ iteration over the progress bar, the iterable passed to the bar is
371
+ advanced and the bar is updated. When the context manager exits,
372
+ a newline is printed and the progress bar is finalized on screen.
373
+
374
+ Note: The progress bar is currently designed for use cases where the
375
+ total progress can be expected to take at least several seconds.
376
+ Because of this, the ProgressBar class object won't display
377
+ progress that is considered too fast, and progress where the time
378
+ between steps is less than a second.
379
+
380
+ No printing must happen or the progress bar will be unintentionally
381
+ destroyed.
382
+
383
+ Example usage::
384
+
385
+ with progressbar(items) as bar:
386
+ for item in bar:
387
+ do_something_with(item)
388
+
389
+ Alternatively, if no iterable is specified, one can manually update the
390
+ progress bar through the `update()` method instead of directly
391
+ iterating over the progress bar. The update method accepts the number
392
+ of steps to increment the bar with::
393
+
394
+ with progressbar(length=chunks.total_bytes) as bar:
395
+ for chunk in chunks:
396
+ process_chunk(chunk)
397
+ bar.update(chunks.bytes)
398
+
399
+ The ``update()`` method also takes an optional value specifying the
400
+ ``current_item`` at the new position. This is useful when used
401
+ together with ``item_show_func`` to customize the output for each
402
+ manual step::
403
+
404
+ with click.progressbar(
405
+ length=total_size,
406
+ label='Unzipping archive',
407
+ item_show_func=lambda a: a.filename
408
+ ) as bar:
409
+ for archive in zip_file:
410
+ archive.extract()
411
+ bar.update(archive.size, archive)
412
+
413
+ :param iterable: an iterable to iterate over. If not provided the length
414
+ is required.
415
+ :param length: the number of items to iterate over. By default the
416
+ progressbar will attempt to ask the iterator about its
417
+ length, which might or might not work. If an iterable is
418
+ also provided this parameter can be used to override the
419
+ length. If an iterable is not provided the progress bar
420
+ will iterate over a range of that length.
421
+ :param label: the label to show next to the progress bar.
422
+ :param hidden: hide the progressbar. Defaults to ``False``. When no tty is
423
+ detected, it will only print the progressbar label. Setting this to
424
+ ``False`` also disables that.
425
+ :param show_eta: enables or disables the estimated time display. This is
426
+ automatically disabled if the length cannot be
427
+ determined.
428
+ :param show_percent: enables or disables the percentage display. The
429
+ default is `True` if the iterable has a length or
430
+ `False` if not.
431
+ :param show_pos: enables or disables the absolute position display. The
432
+ default is `False`.
433
+ :param item_show_func: A function called with the current item which
434
+ can return a string to show next to the progress bar. If the
435
+ function returns ``None`` nothing is shown. The current item can
436
+ be ``None``, such as when entering and exiting the bar.
437
+ :param fill_char: the character to use to show the filled part of the
438
+ progress bar.
439
+ :param empty_char: the character to use to show the non-filled part of
440
+ the progress bar.
441
+ :param bar_template: the format string to use as template for the bar.
442
+ The parameters in it are ``label`` for the label,
443
+ ``bar`` for the progress bar and ``info`` for the
444
+ info section.
445
+ :param info_sep: the separator between multiple info items (eta etc.)
446
+ :param width: the width of the progress bar in characters, 0 means full
447
+ terminal width
448
+ :param file: The file to write to. If this is not a terminal then
449
+ only the label is printed.
450
+ :param color: controls if the terminal supports ANSI colors or not. The
451
+ default is autodetection. This is only needed if ANSI
452
+ codes are included anywhere in the progress bar output
453
+ which is not the case by default.
454
+ :param update_min_steps: Render only when this many updates have
455
+ completed. This allows tuning for very fast iterators.
456
+
457
+ .. versionadded:: 8.2
458
+ The ``hidden`` argument.
459
+
460
+ .. versionchanged:: 8.0
461
+ Output is shown even if execution time is less than 0.5 seconds.
462
+
463
+ .. versionchanged:: 8.0
464
+ ``item_show_func`` shows the current item, not the previous one.
465
+
466
+ .. versionchanged:: 8.0
467
+ Labels are echoed if the output is not a TTY. Reverts a change
468
+ in 7.0 that removed all output.
469
+
470
+ .. versionadded:: 8.0
471
+ The ``update_min_steps`` parameter.
472
+
473
+ .. versionadded:: 4.0
474
+ The ``color`` parameter and ``update`` method.
475
+
476
+ .. versionadded:: 2.0
477
+ """
478
+ from ._termui_impl import ProgressBar
479
+
480
+ color = resolve_color_default(color)
481
+ return ProgressBar(
482
+ iterable=iterable,
483
+ length=length,
484
+ hidden=hidden,
485
+ show_eta=show_eta,
486
+ show_percent=show_percent,
487
+ show_pos=show_pos,
488
+ item_show_func=item_show_func,
489
+ fill_char=fill_char,
490
+ empty_char=empty_char,
491
+ bar_template=bar_template,
492
+ info_sep=info_sep,
493
+ file=file,
494
+ label=label,
495
+ width=width,
496
+ color=color,
497
+ update_min_steps=update_min_steps,
498
+ )
499
+
500
+
501
+ def clear() -> None:
502
+ """Clears the terminal screen. This will have the effect of clearing
503
+ the whole visible space of the terminal and moving the cursor to the
504
+ top left. This does not do anything if not connected to a terminal.
505
+
506
+ .. versionadded:: 2.0
507
+ """
508
+ if not isatty(sys.stdout):
509
+ return
510
+
511
+ # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
512
+ echo("\033[2J\033[1;1H", nl=False)
513
+
514
+
515
+ def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:
516
+ if isinstance(color, int):
517
+ return f"{38 + offset};5;{color:d}"
518
+
519
+ if isinstance(color, (tuple, list)):
520
+ r, g, b = color
521
+ return f"{38 + offset};2;{r:d};{g:d};{b:d}"
522
+
523
+ return str(_ansi_colors[color] + offset)
524
+
525
+
526
+ def style(
527
+ text: t.Any,
528
+ fg: int | tuple[int, int, int] | str | None = None,
529
+ bg: int | tuple[int, int, int] | str | None = None,
530
+ bold: bool | None = None,
531
+ dim: bool | None = None,
532
+ underline: bool | None = None,
533
+ overline: bool | None = None,
534
+ italic: bool | None = None,
535
+ blink: bool | None = None,
536
+ reverse: bool | None = None,
537
+ strikethrough: bool | None = None,
538
+ reset: bool = True,
539
+ ) -> str:
540
+ """Styles a text with ANSI styles and returns the new string. By
541
+ default the styling is self contained which means that at the end
542
+ of the string a reset code is issued. This can be prevented by
543
+ passing ``reset=False``.
544
+
545
+ Examples::
546
+
547
+ click.echo(click.style('Hello World!', fg='green'))
548
+ click.echo(click.style('ATTENTION!', blink=True))
549
+ click.echo(click.style('Some things', reverse=True, fg='cyan'))
550
+ click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
551
+
552
+ Supported color names:
553
+
554
+ * ``black`` (might be a gray)
555
+ * ``red``
556
+ * ``green``
557
+ * ``yellow`` (might be an orange)
558
+ * ``blue``
559
+ * ``magenta``
560
+ * ``cyan``
561
+ * ``white`` (might be light gray)
562
+ * ``bright_black``
563
+ * ``bright_red``
564
+ * ``bright_green``
565
+ * ``bright_yellow``
566
+ * ``bright_blue``
567
+ * ``bright_magenta``
568
+ * ``bright_cyan``
569
+ * ``bright_white``
570
+ * ``reset`` (reset the color code only)
571
+
572
+ If the terminal supports it, color may also be specified as:
573
+
574
+ - An integer in the interval [0, 255]. The terminal must support
575
+ 8-bit/256-color mode.
576
+ - An RGB tuple of three integers in [0, 255]. The terminal must
577
+ support 24-bit/true-color mode.
578
+
579
+ See https://en.wikipedia.org/wiki/ANSI_color and
580
+ https://gist.github.com/XVilka/8346728 for more information.
581
+
582
+ :param text: the string to style with ansi codes.
583
+ :param fg: if provided this will become the foreground color.
584
+ :param bg: if provided this will become the background color.
585
+ :param bold: if provided this will enable or disable bold mode.
586
+ :param dim: if provided this will enable or disable dim mode. This is
587
+ badly supported.
588
+ :param underline: if provided this will enable or disable underline.
589
+ :param overline: if provided this will enable or disable overline.
590
+ :param italic: if provided this will enable or disable italic.
591
+ :param blink: if provided this will enable or disable blinking.
592
+ :param reverse: if provided this will enable or disable inverse
593
+ rendering (foreground becomes background and the
594
+ other way round).
595
+ :param strikethrough: if provided this will enable or disable
596
+ striking through text.
597
+ :param reset: by default a reset-all code is added at the end of the
598
+ string which means that styles do not carry over. This
599
+ can be disabled to compose styles.
600
+
601
+ .. versionchanged:: 8.0
602
+ A non-string ``message`` is converted to a string.
603
+
604
+ .. versionchanged:: 8.0
605
+ Added support for 256 and RGB color codes.
606
+
607
+ .. versionchanged:: 8.0
608
+ Added the ``strikethrough``, ``italic``, and ``overline``
609
+ parameters.
610
+
611
+ .. versionchanged:: 7.0
612
+ Added support for bright colors.
613
+
614
+ .. versionadded:: 2.0
615
+ """
616
+ if not isinstance(text, str):
617
+ text = str(text)
618
+
619
+ bits = []
620
+
621
+ if fg:
622
+ try:
623
+ bits.append(f"\033[{_interpret_color(fg)}m")
624
+ except KeyError:
625
+ raise TypeError(f"Unknown color {fg!r}") from None
626
+
627
+ if bg:
628
+ try:
629
+ bits.append(f"\033[{_interpret_color(bg, 10)}m")
630
+ except KeyError:
631
+ raise TypeError(f"Unknown color {bg!r}") from None
632
+
633
+ if bold is not None:
634
+ bits.append(f"\033[{1 if bold else 22}m")
635
+ if dim is not None:
636
+ bits.append(f"\033[{2 if dim else 22}m")
637
+ if underline is not None:
638
+ bits.append(f"\033[{4 if underline else 24}m")
639
+ if overline is not None:
640
+ bits.append(f"\033[{53 if overline else 55}m")
641
+ if italic is not None:
642
+ bits.append(f"\033[{3 if italic else 23}m")
643
+ if blink is not None:
644
+ bits.append(f"\033[{5 if blink else 25}m")
645
+ if reverse is not None:
646
+ bits.append(f"\033[{7 if reverse else 27}m")
647
+ if strikethrough is not None:
648
+ bits.append(f"\033[{9 if strikethrough else 29}m")
649
+ bits.append(text)
650
+ if reset:
651
+ bits.append(_ansi_reset_all)
652
+ return "".join(bits)
653
+
654
+
655
+ def unstyle(text: str) -> str:
656
+ """Removes ANSI styling information from a string. Usually it's not
657
+ necessary to use this function as Click's echo function will
658
+ automatically remove styling if necessary.
659
+
660
+ .. versionadded:: 2.0
661
+
662
+ :param text: the text to remove style information from.
663
+ """
664
+ return strip_ansi(text)
665
+
666
+
667
+ def secho(
668
+ message: t.Any | None = None,
669
+ file: t.IO[t.AnyStr] | None = None,
670
+ nl: bool = True,
671
+ err: bool = False,
672
+ color: bool | None = None,
673
+ **styles: t.Any,
674
+ ) -> None:
675
+ """This function combines :func:`echo` and :func:`style` into one
676
+ call. As such the following two calls are the same::
677
+
678
+ click.secho('Hello World!', fg='green')
679
+ click.echo(click.style('Hello World!', fg='green'))
680
+
681
+ All keyword arguments are forwarded to the underlying functions
682
+ depending on which one they go with.
683
+
684
+ Non-string types will be converted to :class:`str`. However,
685
+ :class:`bytes` are passed directly to :meth:`echo` without applying
686
+ style. If you want to style bytes that represent text, call
687
+ :meth:`bytes.decode` first.
688
+
689
+ .. versionchanged:: 8.0
690
+ A non-string ``message`` is converted to a string. Bytes are
691
+ passed through without style applied.
692
+
693
+ .. versionadded:: 2.0
694
+ """
695
+ if message is not None and not isinstance(message, (bytes, bytearray)):
696
+ message = style(message, **styles)
697
+
698
+ return echo(message, file=file, nl=nl, err=err, color=color)
699
+
700
+
701
+ @t.overload
702
+ def edit(
703
+ text: bytes | bytearray,
704
+ editor: str | None = None,
705
+ env: cabc.Mapping[str, str] | None = None,
706
+ require_save: bool = False,
707
+ extension: str = ".txt",
708
+ ) -> bytes | None: ...
709
+
710
+
711
+ @t.overload
712
+ def edit(
713
+ text: str,
714
+ editor: str | None = None,
715
+ env: cabc.Mapping[str, str] | None = None,
716
+ require_save: bool = True,
717
+ extension: str = ".txt",
718
+ ) -> str | None: ...
719
+
720
+
721
+ @t.overload
722
+ def edit(
723
+ text: None = None,
724
+ editor: str | None = None,
725
+ env: cabc.Mapping[str, str] | None = None,
726
+ require_save: bool = True,
727
+ extension: str = ".txt",
728
+ filename: str | cabc.Iterable[str] | None = None,
729
+ ) -> None: ...
730
+
731
+
732
+ def edit(
733
+ text: str | bytes | bytearray | None = None,
734
+ editor: str | None = None,
735
+ env: cabc.Mapping[str, str] | None = None,
736
+ require_save: bool = True,
737
+ extension: str = ".txt",
738
+ filename: str | cabc.Iterable[str] | None = None,
739
+ ) -> str | bytes | bytearray | None:
740
+ r"""Edits the given text in the defined editor. If an editor is given
741
+ (should be the full path to the executable but the regular operating
742
+ system search path is used for finding the executable) it overrides
743
+ the detected editor. Optionally, some environment variables can be
744
+ used. If the editor is closed without changes, `None` is returned. In
745
+ case a file is edited directly the return value is always `None` and
746
+ `require_save` and `extension` are ignored.
747
+
748
+ If the editor cannot be opened a :exc:`UsageError` is raised.
749
+
750
+ Note for Windows: to simplify cross-platform usage, the newlines are
751
+ automatically converted from POSIX to Windows and vice versa. As such,
752
+ the message here will have ``\n`` as newline markers.
753
+
754
+ :param text: the text to edit.
755
+ :param editor: optionally the editor to use. Defaults to automatic
756
+ detection.
757
+ :param env: environment variables to forward to the editor.
758
+ :param require_save: if this is true, then not saving in the editor
759
+ will make the return value become `None`.
760
+ :param extension: the extension to tell the editor about. This defaults
761
+ to `.txt` but changing this might change syntax
762
+ highlighting.
763
+ :param filename: if provided it will edit this file instead of the
764
+ provided text contents. It will not use a temporary
765
+ file as an indirection in that case. If the editor supports
766
+ editing multiple files at once, a sequence of files may be
767
+ passed as well. Invoke `click.file` once per file instead
768
+ if multiple files cannot be managed at once or editing the
769
+ files serially is desired.
770
+
771
+ .. versionchanged:: 8.2.0
772
+ ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``
773
+ if the ``editor`` supports editing multiple files at once.
774
+
775
+ """
776
+ from ._termui_impl import Editor
777
+
778
+ ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
779
+
780
+ if filename is None:
781
+ return ed.edit(text)
782
+
783
+ if isinstance(filename, str):
784
+ filename = (filename,)
785
+
786
+ ed.edit_files(filenames=filename)
787
+ return None
788
+
789
+
790
+ def launch(url: str, wait: bool = False, locate: bool = False) -> int:
791
+ """This function launches the given URL (or filename) in the default
792
+ viewer application for this file type. If this is an executable, it
793
+ might launch the executable in a new session. The return value is
794
+ the exit code of the launched application. Usually, ``0`` indicates
795
+ success.
796
+
797
+ Examples::
798
+
799
+ click.launch('https://click.palletsprojects.com/')
800
+ click.launch('/my/downloaded/file', locate=True)
801
+
802
+ .. versionadded:: 2.0
803
+
804
+ :param url: URL or filename of the thing to launch.
805
+ :param wait: Wait for the program to exit before returning. This
806
+ only works if the launched program blocks. In particular,
807
+ ``xdg-open`` on Linux does not block.
808
+ :param locate: if this is set to `True` then instead of launching the
809
+ application associated with the URL it will attempt to
810
+ launch a file manager with the file located. This
811
+ might have weird effects if the URL does not point to
812
+ the filesystem.
813
+ """
814
+ from ._termui_impl import open_url
815
+
816
+ return open_url(url, wait=wait, locate=locate)
817
+
818
+
819
+ # If this is provided, getchar() calls into this instead. This is used
820
+ # for unittesting purposes.
821
+ _getchar: t.Callable[[bool], str] | None = None
822
+
823
+
824
+ def getchar(echo: bool = False) -> str:
825
+ """Fetches a single character from the terminal and returns it. This
826
+ will always return a unicode character and under certain rare
827
+ circumstances this might return more than one character. The
828
+ situations which more than one character is returned is when for
829
+ whatever reason multiple characters end up in the terminal buffer or
830
+ standard input was not actually a terminal.
831
+
832
+ Note that this will always read from the terminal, even if something
833
+ is piped into the standard input.
834
+
835
+ Note for Windows: in rare cases when typing non-ASCII characters, this
836
+ function might wait for a second character and then return both at once.
837
+ This is because certain Unicode characters look like special-key markers.
838
+
839
+ .. versionadded:: 2.0
840
+
841
+ :param echo: if set to `True`, the character read will also show up on
842
+ the terminal. The default is to not show it.
843
+ """
844
+ global _getchar
845
+
846
+ if _getchar is None:
847
+ from ._termui_impl import getchar as f
848
+
849
+ _getchar = f
850
+
851
+ return _getchar(echo)
852
+
853
+
854
+ def raw_terminal() -> AbstractContextManager[int]:
855
+ from ._termui_impl import raw_terminal as f
856
+
857
+ return f()
858
+
859
+
860
+ def pause(info: str | None = None, err: bool = False) -> None:
861
+ """This command stops execution and waits for the user to press any
862
+ key to continue. This is similar to the Windows batch "pause"
863
+ command. If the program is not run through a terminal, this command
864
+ will instead do nothing.
865
+
866
+ .. versionadded:: 2.0
867
+
868
+ .. versionadded:: 4.0
869
+ Added the `err` parameter.
870
+
871
+ :param info: The message to print before pausing. Defaults to
872
+ ``"Press any key to continue..."``.
873
+ :param err: if set to message goes to ``stderr`` instead of
874
+ ``stdout``, the same as with echo.
875
+ """
876
+ if not isatty(sys.stdin) or not isatty(sys.stdout):
877
+ return
878
+
879
+ if info is None:
880
+ info = _("Press any key to continue...")
881
+
882
+ try:
883
+ if info:
884
+ echo(info, nl=False, err=err)
885
+ try:
886
+ getchar()
887
+ except (KeyboardInterrupt, EOFError):
888
+ pass
889
+ finally:
890
+ if info:
891
+ echo(err=err)
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/testing.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import contextlib
5
+ import io
6
+ import os
7
+ import pdb
8
+ import shlex
9
+ import sys
10
+ import tempfile
11
+ import typing as t
12
+ from types import TracebackType
13
+
14
+ from . import _compat
15
+ from . import formatting
16
+ from . import termui
17
+ from . import utils
18
+ from ._compat import _find_binary_reader
19
+
20
+ if t.TYPE_CHECKING:
21
+ from _typeshed import ReadableBuffer
22
+
23
+ from .core import Command
24
+
25
+
26
+ class EchoingStdin:
27
+ def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:
28
+ self._input = input
29
+ self._output = output
30
+ self._paused = False
31
+
32
+ def __getattr__(self, x: str) -> t.Any:
33
+ return getattr(self._input, x)
34
+
35
+ def _echo(self, rv: bytes) -> bytes:
36
+ if not self._paused:
37
+ self._output.write(rv)
38
+
39
+ return rv
40
+
41
+ def read(self, n: int = -1) -> bytes:
42
+ return self._echo(self._input.read(n))
43
+
44
+ def read1(self, n: int = -1) -> bytes:
45
+ return self._echo(self._input.read1(n)) # type: ignore
46
+
47
+ def readline(self, n: int = -1) -> bytes:
48
+ return self._echo(self._input.readline(n))
49
+
50
+ def readlines(self) -> list[bytes]:
51
+ return [self._echo(x) for x in self._input.readlines()]
52
+
53
+ def __iter__(self) -> cabc.Iterator[bytes]:
54
+ return iter(self._echo(x) for x in self._input)
55
+
56
+ def __repr__(self) -> str:
57
+ return repr(self._input)
58
+
59
+
60
+ @contextlib.contextmanager
61
+ def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]:
62
+ if stream is None:
63
+ yield
64
+ else:
65
+ stream._paused = True
66
+ yield
67
+ stream._paused = False
68
+
69
+
70
+ class BytesIOCopy(io.BytesIO):
71
+ """Patch ``io.BytesIO`` to let the written stream be copied to another.
72
+
73
+ .. versionadded:: 8.2
74
+ """
75
+
76
+ def __init__(self, copy_to: io.BytesIO) -> None:
77
+ super().__init__()
78
+ self.copy_to = copy_to
79
+
80
+ def flush(self) -> None:
81
+ super().flush()
82
+ self.copy_to.flush()
83
+
84
+ def write(self, b: ReadableBuffer) -> int:
85
+ self.copy_to.write(b)
86
+ return super().write(b)
87
+
88
+
89
+ class StreamMixer:
90
+ """Mixes `<stdout>` and `<stderr>` streams.
91
+
92
+ The result is available in the ``output`` attribute.
93
+
94
+ .. versionadded:: 8.2
95
+ """
96
+
97
+ def __init__(self) -> None:
98
+ self.output: io.BytesIO = io.BytesIO()
99
+ self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)
100
+ self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)
101
+
102
+
103
+ class _NamedTextIOWrapper(io.TextIOWrapper):
104
+ """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``
105
+ that does not close its underlying buffer.
106
+
107
+ An optional ``original_fd`` preserves the file descriptor of the
108
+ stream being replaced, so that C-level consumers that call
109
+ :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work.
110
+ Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing`
111
+ for details.
112
+
113
+ .. versionchanged:: 8.3.3
114
+ Added ``original_fd`` parameter and :meth:`fileno` override.
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ buffer: t.BinaryIO,
120
+ name: str,
121
+ mode: str,
122
+ *,
123
+ original_fd: int = -1,
124
+ **kwargs: t.Any,
125
+ ) -> None:
126
+ super().__init__(buffer, **kwargs)
127
+ self._name = name
128
+ self._mode = mode
129
+ self._original_fd = original_fd
130
+
131
+ def close(self) -> None:
132
+ """The buffer this object contains belongs to some other object,
133
+ so prevent the default ``__del__`` implementation from closing
134
+ that buffer.
135
+
136
+ .. versionadded:: 8.3.2
137
+ """
138
+
139
+ def fileno(self) -> int:
140
+ """Return the file descriptor of the original stream, if one was
141
+ provided at construction time.
142
+
143
+ This allows C-level consumers (``faulthandler``, ``subprocess``,
144
+ signal handlers, ...) to obtain a valid fd without crashing, even
145
+ though the Python-level writes are redirected to an in-memory
146
+ buffer.
147
+
148
+ .. versionadded:: 8.3.3
149
+ """
150
+ if self._original_fd >= 0:
151
+ return self._original_fd
152
+ return super().fileno()
153
+
154
+ @property
155
+ def name(self) -> str:
156
+ return self._name
157
+
158
+ @property
159
+ def mode(self) -> str:
160
+ return self._mode
161
+
162
+
163
+ def make_input_stream(
164
+ input: str | bytes | t.IO[t.Any] | None, charset: str
165
+ ) -> t.BinaryIO:
166
+ # Is already an input stream.
167
+ if hasattr(input, "read"):
168
+ rv = _find_binary_reader(t.cast("t.IO[t.Any]", input))
169
+
170
+ if rv is not None:
171
+ return rv
172
+
173
+ raise TypeError("Could not find binary reader for input stream.")
174
+
175
+ if input is None:
176
+ input = b""
177
+ elif isinstance(input, str):
178
+ input = input.encode(charset)
179
+
180
+ return io.BytesIO(input)
181
+
182
+
183
+ class Result:
184
+ """Holds the captured result of an invoked CLI script.
185
+
186
+ :param runner: The runner that created the result
187
+ :param stdout_bytes: The standard output as bytes.
188
+ :param stderr_bytes: The standard error as bytes.
189
+ :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the
190
+ user would see it in its terminal.
191
+ :param return_value: The value returned from the invoked command.
192
+ :param exit_code: The exit code as integer.
193
+ :param exception: The exception that happened if one did.
194
+ :param exc_info: Exception information (exception type, exception instance,
195
+ traceback type).
196
+
197
+ .. versionchanged:: 8.2
198
+ ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and
199
+ ``mix_stderr`` has been removed.
200
+
201
+ .. versionadded:: 8.0
202
+ Added ``return_value``.
203
+ """
204
+
205
+ def __init__(
206
+ self,
207
+ runner: CliRunner,
208
+ stdout_bytes: bytes,
209
+ stderr_bytes: bytes,
210
+ output_bytes: bytes,
211
+ return_value: t.Any,
212
+ exit_code: int,
213
+ exception: BaseException | None,
214
+ exc_info: tuple[type[BaseException], BaseException, TracebackType]
215
+ | None = None,
216
+ ):
217
+ self.runner = runner
218
+ self.stdout_bytes = stdout_bytes
219
+ self.stderr_bytes = stderr_bytes
220
+ self.output_bytes = output_bytes
221
+ self.return_value = return_value
222
+ self.exit_code = exit_code
223
+ self.exception = exception
224
+ self.exc_info = exc_info
225
+
226
+ @property
227
+ def output(self) -> str:
228
+ """The terminal output as unicode string, as the user would see it.
229
+
230
+ .. versionchanged:: 8.2
231
+ No longer a proxy for ``self.stdout``. Now has its own independent stream
232
+ that is mixing `<stdout>` and `<stderr>`, in the order they were written.
233
+ """
234
+ return self.output_bytes.decode(self.runner.charset, "replace").replace(
235
+ "\r\n", "\n"
236
+ )
237
+
238
+ @property
239
+ def stdout(self) -> str:
240
+ """The standard output as unicode string."""
241
+ return self.stdout_bytes.decode(self.runner.charset, "replace").replace(
242
+ "\r\n", "\n"
243
+ )
244
+
245
+ @property
246
+ def stderr(self) -> str:
247
+ """The standard error as unicode string.
248
+
249
+ .. versionchanged:: 8.2
250
+ No longer raise an exception, always returns the `<stderr>` string.
251
+ """
252
+ return self.stderr_bytes.decode(self.runner.charset, "replace").replace(
253
+ "\r\n", "\n"
254
+ )
255
+
256
+ def __repr__(self) -> str:
257
+ exc_str = repr(self.exception) if self.exception else "okay"
258
+ return f"<{type(self).__name__} {exc_str}>"
259
+
260
+
261
+ class CliRunner:
262
+ """The CLI runner provides functionality to invoke a Click command line
263
+ script for unittesting purposes in a isolated environment. This only
264
+ works in single-threaded systems without any concurrency as it changes the
265
+ global interpreter state.
266
+
267
+ :param charset: the character set for the input and output data.
268
+ :param env: a dictionary with environment variables for overriding.
269
+ :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes
270
+ to `<stdout>`. This is useful for showing examples in
271
+ some circumstances. Note that regular prompts
272
+ will automatically echo the input.
273
+ :param catch_exceptions: Whether to catch any exceptions other than
274
+ ``SystemExit`` when running :meth:`~CliRunner.invoke`.
275
+
276
+ .. versionchanged:: 8.2
277
+ Added the ``catch_exceptions`` parameter.
278
+
279
+ .. versionchanged:: 8.2
280
+ ``mix_stderr`` parameter has been removed.
281
+ """
282
+
283
+ def __init__(
284
+ self,
285
+ charset: str = "utf-8",
286
+ env: cabc.Mapping[str, str | None] | None = None,
287
+ echo_stdin: bool = False,
288
+ catch_exceptions: bool = True,
289
+ ) -> None:
290
+ self.charset = charset
291
+ self.env: cabc.Mapping[str, str | None] = env or {}
292
+ self.echo_stdin = echo_stdin
293
+ self.catch_exceptions = catch_exceptions
294
+
295
+ def get_default_prog_name(self, cli: Command) -> str:
296
+ """Given a command object it will return the default program name
297
+ for it. The default is the `name` attribute or ``"root"`` if not
298
+ set.
299
+ """
300
+ return cli.name or "root"
301
+
302
+ def make_env(
303
+ self, overrides: cabc.Mapping[str, str | None] | None = None
304
+ ) -> cabc.Mapping[str, str | None]:
305
+ """Returns the environment overrides for invoking a script."""
306
+ rv = dict(self.env)
307
+ if overrides:
308
+ rv.update(overrides)
309
+ return rv
310
+
311
+ @contextlib.contextmanager
312
+ def isolation(
313
+ self,
314
+ input: str | bytes | t.IO[t.Any] | None = None,
315
+ env: cabc.Mapping[str, str | None] | None = None,
316
+ color: bool = False,
317
+ ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:
318
+ """A context manager that sets up the isolation for invoking of a
319
+ command line tool. This sets up `<stdin>` with the given input data
320
+ and `os.environ` with the overrides from the given dictionary.
321
+ This also rebinds some internals in Click to be mocked (like the
322
+ prompt functionality).
323
+
324
+ This is automatically done in the :meth:`invoke` method.
325
+
326
+ :param input: the input stream to put into `sys.stdin`.
327
+ :param env: the environment overrides as dictionary.
328
+ :param color: whether the output should contain color codes. The
329
+ application can still override this explicitly.
330
+
331
+ .. versionadded:: 8.2
332
+ An additional output stream is returned, which is a mix of
333
+ `<stdout>` and `<stderr>` streams.
334
+
335
+ .. versionchanged:: 8.2
336
+ Always returns the `<stderr>` stream.
337
+
338
+ .. versionchanged:: 8.0
339
+ `<stderr>` is opened with ``errors="backslashreplace"``
340
+ instead of the default ``"strict"``.
341
+
342
+ .. versionchanged:: 4.0
343
+ Added the ``color`` parameter.
344
+ """
345
+ bytes_input = make_input_stream(input, self.charset)
346
+ echo_input = None
347
+
348
+ old_stdin = sys.stdin
349
+ old_stdout = sys.stdout
350
+ old_stderr = sys.stderr
351
+ old_forced_width = formatting.FORCED_WIDTH
352
+ formatting.FORCED_WIDTH = 80
353
+
354
+ env = self.make_env(env)
355
+
356
+ stream_mixer = StreamMixer()
357
+
358
+ # Preserve the original file descriptors so that C-level
359
+ # consumers (faulthandler, subprocess, etc.) can still obtain a
360
+ # valid fd from the redirected streams. The original streams
361
+ # may themselves lack a fileno() (e.g. when CliRunner is used
362
+ # inside pytest's capsys), so we fall back to -1.
363
+ def _safe_fileno(stream: t.IO[t.Any]) -> int:
364
+ try:
365
+ return stream.fileno()
366
+ except (AttributeError, io.UnsupportedOperation):
367
+ return -1
368
+
369
+ old_stdout_fd = _safe_fileno(old_stdout)
370
+ old_stderr_fd = _safe_fileno(old_stderr)
371
+
372
+ if self.echo_stdin:
373
+ bytes_input = echo_input = t.cast(
374
+ t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)
375
+ )
376
+
377
+ sys.stdin = text_input = _NamedTextIOWrapper(
378
+ bytes_input, encoding=self.charset, name="<stdin>", mode="r"
379
+ )
380
+
381
+ if self.echo_stdin:
382
+ # Force unbuffered reads, otherwise TextIOWrapper reads a
383
+ # large chunk which is echoed early.
384
+ text_input._CHUNK_SIZE = 1 # type: ignore
385
+
386
+ sys.stdout = _NamedTextIOWrapper(
387
+ stream_mixer.stdout,
388
+ encoding=self.charset,
389
+ name="<stdout>",
390
+ mode="w",
391
+ original_fd=old_stdout_fd,
392
+ )
393
+
394
+ sys.stderr = _NamedTextIOWrapper(
395
+ stream_mixer.stderr,
396
+ encoding=self.charset,
397
+ name="<stderr>",
398
+ mode="w",
399
+ errors="backslashreplace",
400
+ original_fd=old_stderr_fd,
401
+ )
402
+
403
+ @_pause_echo(echo_input) # type: ignore
404
+ def visible_input(prompt: str | None = None) -> str:
405
+ sys.stdout.write(prompt or "")
406
+ try:
407
+ val = next(text_input).rstrip("\r\n")
408
+ except StopIteration as e:
409
+ raise EOFError() from e
410
+ sys.stdout.write(f"{val}\n")
411
+ sys.stdout.flush()
412
+ return val
413
+
414
+ @_pause_echo(echo_input) # type: ignore
415
+ def hidden_input(prompt: str | None = None) -> str:
416
+ sys.stdout.write(f"{prompt or ''}\n")
417
+ sys.stdout.flush()
418
+ try:
419
+ return next(text_input).rstrip("\r\n")
420
+ except StopIteration as e:
421
+ raise EOFError() from e
422
+
423
+ @_pause_echo(echo_input) # type: ignore
424
+ def _getchar(echo: bool) -> str:
425
+ char = sys.stdin.read(1)
426
+
427
+ if echo:
428
+ sys.stdout.write(char)
429
+
430
+ sys.stdout.flush()
431
+ return char
432
+
433
+ default_color = color
434
+
435
+ def should_strip_ansi(
436
+ stream: t.IO[t.Any] | None = None, color: bool | None = None
437
+ ) -> bool:
438
+ if color is None:
439
+ return not default_color
440
+ return not color
441
+
442
+ old_visible_prompt_func = termui.visible_prompt_func
443
+ old_hidden_prompt_func = termui.hidden_prompt_func
444
+ old__getchar_func = termui._getchar
445
+ old_should_strip_ansi = utils.should_strip_ansi # type: ignore
446
+ old__compat_should_strip_ansi = _compat.should_strip_ansi
447
+ old_pdb_init = pdb.Pdb.__init__
448
+ termui.visible_prompt_func = visible_input
449
+ termui.hidden_prompt_func = hidden_input
450
+ termui._getchar = _getchar
451
+ utils.should_strip_ansi = should_strip_ansi # type: ignore
452
+ _compat.should_strip_ansi = should_strip_ansi
453
+
454
+ def _patched_pdb_init(
455
+ self: pdb.Pdb,
456
+ completekey: str = "tab",
457
+ stdin: t.IO[str] | None = None,
458
+ stdout: t.IO[str] | None = None,
459
+ **kwargs: t.Any,
460
+ ) -> None:
461
+ """Default ``pdb.Pdb`` to real terminal streams during
462
+ ``CliRunner`` isolation.
463
+
464
+ Without this patch, ``pdb.Pdb.__init__`` inherits from
465
+ ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout``
466
+ when no explicit streams are provided. During isolation
467
+ those are ``BytesIO``-backed wrappers, so the debugger
468
+ reads from an empty buffer and writes to captured output,
469
+ making interactive debugging impossible.
470
+
471
+ By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the
472
+ original terminal streams Python preserves regardless of
473
+ redirection), debuggers can interact with the user while
474
+ ``click.echo`` output is still captured normally.
475
+
476
+ This covers ``pdb.set_trace()``, ``breakpoint()``,
477
+ ``pdb.post_mortem()``, and debuggers that subclass
478
+ ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout``
479
+ arguments are honored and not overridden. Debuggers that
480
+ do not subclass ``pdb.Pdb`` (pudb, debugpy) are not
481
+ covered.
482
+ """
483
+ if stdin is None:
484
+ stdin = sys.__stdin__
485
+ if stdout is None:
486
+ stdout = sys.__stdout__
487
+ old_pdb_init(
488
+ self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs
489
+ )
490
+
491
+ pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment]
492
+
493
+ old_env = {}
494
+ try:
495
+ for key, value in env.items():
496
+ old_env[key] = os.environ.get(key)
497
+ if value is None:
498
+ try:
499
+ del os.environ[key]
500
+ except Exception:
501
+ pass
502
+ else:
503
+ os.environ[key] = value
504
+ yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)
505
+ finally:
506
+ for key, value in old_env.items():
507
+ if value is None:
508
+ try:
509
+ del os.environ[key]
510
+ except Exception:
511
+ pass
512
+ else:
513
+ os.environ[key] = value
514
+ sys.stdout = old_stdout
515
+ sys.stderr = old_stderr
516
+ sys.stdin = old_stdin
517
+ termui.visible_prompt_func = old_visible_prompt_func
518
+ termui.hidden_prompt_func = old_hidden_prompt_func
519
+ termui._getchar = old__getchar_func
520
+ utils.should_strip_ansi = old_should_strip_ansi # type: ignore
521
+ _compat.should_strip_ansi = old__compat_should_strip_ansi
522
+ formatting.FORCED_WIDTH = old_forced_width
523
+ pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign]
524
+
525
+ def invoke(
526
+ self,
527
+ cli: Command,
528
+ args: str | cabc.Sequence[str] | None = None,
529
+ input: str | bytes | t.IO[t.Any] | None = None,
530
+ env: cabc.Mapping[str, str | None] | None = None,
531
+ catch_exceptions: bool | None = None,
532
+ color: bool = False,
533
+ **extra: t.Any,
534
+ ) -> Result:
535
+ """Invokes a command in an isolated environment. The arguments are
536
+ forwarded directly to the command line script, the `extra` keyword
537
+ arguments are passed to the :meth:`~clickpkg.Command.main` function of
538
+ the command.
539
+
540
+ This returns a :class:`Result` object.
541
+
542
+ :param cli: the command to invoke
543
+ :param args: the arguments to invoke. It may be given as an iterable
544
+ or a string. When given as string it will be interpreted
545
+ as a Unix shell command. More details at
546
+ :func:`shlex.split`.
547
+ :param input: the input data for `sys.stdin`.
548
+ :param env: the environment overrides.
549
+ :param catch_exceptions: Whether to catch any other exceptions than
550
+ ``SystemExit``. If :data:`None`, the value
551
+ from :class:`CliRunner` is used.
552
+ :param extra: the keyword arguments to pass to :meth:`main`.
553
+ :param color: whether the output should contain color codes. The
554
+ application can still override this explicitly.
555
+
556
+ .. versionadded:: 8.2
557
+ The result object has the ``output_bytes`` attribute with
558
+ the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would
559
+ see it in its terminal.
560
+
561
+ .. versionchanged:: 8.2
562
+ The result object always returns the ``stderr_bytes`` stream.
563
+
564
+ .. versionchanged:: 8.0
565
+ The result object has the ``return_value`` attribute with
566
+ the value returned from the invoked command.
567
+
568
+ .. versionchanged:: 4.0
569
+ Added the ``color`` parameter.
570
+
571
+ .. versionchanged:: 3.0
572
+ Added the ``catch_exceptions`` parameter.
573
+
574
+ .. versionchanged:: 3.0
575
+ The result object has the ``exc_info`` attribute with the
576
+ traceback if available.
577
+ """
578
+ exc_info = None
579
+ if catch_exceptions is None:
580
+ catch_exceptions = self.catch_exceptions
581
+
582
+ with self.isolation(input=input, env=env, color=color) as outstreams:
583
+ return_value = None
584
+ exception: BaseException | None = None
585
+ exit_code = 0
586
+
587
+ if isinstance(args, str):
588
+ args = shlex.split(args)
589
+
590
+ try:
591
+ prog_name = extra.pop("prog_name")
592
+ except KeyError:
593
+ prog_name = self.get_default_prog_name(cli)
594
+
595
+ try:
596
+ return_value = cli.main(args=args or (), prog_name=prog_name, **extra)
597
+ except SystemExit as e:
598
+ exc_info = sys.exc_info()
599
+ e_code = t.cast("int | t.Any | None", e.code)
600
+
601
+ if e_code is None:
602
+ e_code = 0
603
+
604
+ if e_code != 0:
605
+ exception = e
606
+
607
+ if not isinstance(e_code, int):
608
+ sys.stdout.write(str(e_code))
609
+ sys.stdout.write("\n")
610
+ e_code = 1
611
+
612
+ exit_code = e_code
613
+
614
+ except Exception as e:
615
+ if not catch_exceptions:
616
+ raise
617
+ exception = e
618
+ exit_code = 1
619
+ exc_info = sys.exc_info()
620
+ finally:
621
+ sys.stdout.flush()
622
+ sys.stderr.flush()
623
+ stdout = outstreams[0].getvalue()
624
+ stderr = outstreams[1].getvalue()
625
+ output = outstreams[2].getvalue()
626
+
627
+ return Result(
628
+ runner=self,
629
+ stdout_bytes=stdout,
630
+ stderr_bytes=stderr,
631
+ output_bytes=output,
632
+ return_value=return_value,
633
+ exit_code=exit_code,
634
+ exception=exception,
635
+ exc_info=exc_info, # type: ignore
636
+ )
637
+
638
+ @contextlib.contextmanager
639
+ def isolated_filesystem(
640
+ self, temp_dir: str | os.PathLike[str] | None = None
641
+ ) -> cabc.Iterator[str]:
642
+ """A context manager that creates a temporary directory and
643
+ changes the current working directory to it. This isolates tests
644
+ that affect the contents of the CWD to prevent them from
645
+ interfering with each other.
646
+
647
+ :param temp_dir: Create the temporary directory under this
648
+ directory. If given, the created directory is not removed
649
+ when exiting.
650
+
651
+ .. versionchanged:: 8.0
652
+ Added the ``temp_dir`` parameter.
653
+ """
654
+ cwd = os.getcwd()
655
+ dt = tempfile.mkdtemp(dir=temp_dir)
656
+ os.chdir(dt)
657
+
658
+ try:
659
+ yield dt
660
+ finally:
661
+ os.chdir(cwd)
662
+
663
+ if temp_dir is None:
664
+ import shutil
665
+
666
+ try:
667
+ shutil.rmtree(dt)
668
+ except OSError:
669
+ pass
.cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec-2026.4.0.dist-info/METADATA ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: fsspec
3
+ Version: 2026.4.0
4
+ Summary: File-system specification
5
+ Project-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.html
6
+ Project-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/
7
+ Project-URL: Homepage, https://github.com/fsspec/filesystem_spec
8
+ Maintainer-email: Martin Durant <mdurant@anaconda.com>
9
+ License-Expression: BSD-3-Clause
10
+ License-File: LICENSE
11
+ Keywords: file
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Python: >=3.10
21
+ Provides-Extra: abfs
22
+ Requires-Dist: adlfs; extra == 'abfs'
23
+ Provides-Extra: adl
24
+ Requires-Dist: adlfs; extra == 'adl'
25
+ Provides-Extra: arrow
26
+ Requires-Dist: pyarrow>=1; extra == 'arrow'
27
+ Provides-Extra: dask
28
+ Requires-Dist: dask; extra == 'dask'
29
+ Requires-Dist: distributed; extra == 'dask'
30
+ Provides-Extra: dev
31
+ Requires-Dist: pre-commit; extra == 'dev'
32
+ Requires-Dist: ruff>=0.5; extra == 'dev'
33
+ Provides-Extra: doc
34
+ Requires-Dist: numpydoc; extra == 'doc'
35
+ Requires-Dist: sphinx; extra == 'doc'
36
+ Requires-Dist: sphinx-design; extra == 'doc'
37
+ Requires-Dist: sphinx-rtd-theme; extra == 'doc'
38
+ Requires-Dist: yarl; extra == 'doc'
39
+ Provides-Extra: dropbox
40
+ Requires-Dist: dropbox; extra == 'dropbox'
41
+ Requires-Dist: dropboxdrivefs; extra == 'dropbox'
42
+ Requires-Dist: requests; extra == 'dropbox'
43
+ Provides-Extra: entrypoints
44
+ Provides-Extra: full
45
+ Requires-Dist: adlfs; extra == 'full'
46
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full'
47
+ Requires-Dist: dask; extra == 'full'
48
+ Requires-Dist: distributed; extra == 'full'
49
+ Requires-Dist: dropbox; extra == 'full'
50
+ Requires-Dist: dropboxdrivefs; extra == 'full'
51
+ Requires-Dist: fusepy; extra == 'full'
52
+ Requires-Dist: gcsfs>2024.2.0; extra == 'full'
53
+ Requires-Dist: libarchive-c; extra == 'full'
54
+ Requires-Dist: ocifs; extra == 'full'
55
+ Requires-Dist: panel; extra == 'full'
56
+ Requires-Dist: paramiko; extra == 'full'
57
+ Requires-Dist: pyarrow>=1; extra == 'full'
58
+ Requires-Dist: pygit2; extra == 'full'
59
+ Requires-Dist: requests; extra == 'full'
60
+ Requires-Dist: s3fs>2024.2.0; extra == 'full'
61
+ Requires-Dist: smbprotocol; extra == 'full'
62
+ Requires-Dist: tqdm; extra == 'full'
63
+ Provides-Extra: fuse
64
+ Requires-Dist: fusepy; extra == 'fuse'
65
+ Provides-Extra: gcs
66
+ Requires-Dist: gcsfs>2024.2.0; extra == 'gcs'
67
+ Provides-Extra: git
68
+ Requires-Dist: pygit2; extra == 'git'
69
+ Provides-Extra: github
70
+ Requires-Dist: requests; extra == 'github'
71
+ Provides-Extra: gs
72
+ Requires-Dist: gcsfs; extra == 'gs'
73
+ Provides-Extra: gui
74
+ Requires-Dist: panel; extra == 'gui'
75
+ Provides-Extra: hdfs
76
+ Requires-Dist: pyarrow>=1; extra == 'hdfs'
77
+ Provides-Extra: http
78
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http'
79
+ Provides-Extra: libarchive
80
+ Requires-Dist: libarchive-c; extra == 'libarchive'
81
+ Provides-Extra: oci
82
+ Requires-Dist: ocifs; extra == 'oci'
83
+ Provides-Extra: s3
84
+ Requires-Dist: s3fs>2024.2.0; extra == 's3'
85
+ Provides-Extra: sftp
86
+ Requires-Dist: paramiko; extra == 'sftp'
87
+ Provides-Extra: smb
88
+ Requires-Dist: smbprotocol; extra == 'smb'
89
+ Provides-Extra: ssh
90
+ Requires-Dist: paramiko; extra == 'ssh'
91
+ Provides-Extra: test
92
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'
93
+ Requires-Dist: numpy; extra == 'test'
94
+ Requires-Dist: pytest; extra == 'test'
95
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'
96
+ Requires-Dist: pytest-benchmark; extra == 'test'
97
+ Requires-Dist: pytest-cov; extra == 'test'
98
+ Requires-Dist: pytest-mock; extra == 'test'
99
+ Requires-Dist: pytest-recording; extra == 'test'
100
+ Requires-Dist: pytest-rerunfailures; extra == 'test'
101
+ Requires-Dist: requests; extra == 'test'
102
+ Provides-Extra: test-downstream
103
+ Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'
104
+ Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'
105
+ Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'
106
+ Requires-Dist: pytest-timeout; extra == 'test-downstream'
107
+ Requires-Dist: xarray; extra == 'test-downstream'
108
+ Provides-Extra: test-full
109
+ Requires-Dist: adlfs; extra == 'test-full'
110
+ Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'
111
+ Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'
112
+ Requires-Dist: cloudpickle; extra == 'test-full'
113
+ Requires-Dist: dask; extra == 'test-full'
114
+ Requires-Dist: distributed; extra == 'test-full'
115
+ Requires-Dist: dropbox; extra == 'test-full'
116
+ Requires-Dist: dropboxdrivefs; extra == 'test-full'
117
+ Requires-Dist: fastparquet; extra == 'test-full'
118
+ Requires-Dist: fusepy; extra == 'test-full'
119
+ Requires-Dist: gcsfs; extra == 'test-full'
120
+ Requires-Dist: jinja2; extra == 'test-full'
121
+ Requires-Dist: kerchunk; extra == 'test-full'
122
+ Requires-Dist: libarchive-c; extra == 'test-full'
123
+ Requires-Dist: lz4; extra == 'test-full'
124
+ Requires-Dist: notebook; extra == 'test-full'
125
+ Requires-Dist: numpy; extra == 'test-full'
126
+ Requires-Dist: ocifs; extra == 'test-full'
127
+ Requires-Dist: pandas<3.0.0; extra == 'test-full'
128
+ Requires-Dist: panel; extra == 'test-full'
129
+ Requires-Dist: paramiko; extra == 'test-full'
130
+ Requires-Dist: pyarrow; extra == 'test-full'
131
+ Requires-Dist: pyarrow>=1; extra == 'test-full'
132
+ Requires-Dist: pyftpdlib; extra == 'test-full'
133
+ Requires-Dist: pygit2; extra == 'test-full'
134
+ Requires-Dist: pytest; extra == 'test-full'
135
+ Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'
136
+ Requires-Dist: pytest-benchmark; extra == 'test-full'
137
+ Requires-Dist: pytest-cov; extra == 'test-full'
138
+ Requires-Dist: pytest-mock; extra == 'test-full'
139
+ Requires-Dist: pytest-recording; extra == 'test-full'
140
+ Requires-Dist: pytest-rerunfailures; extra == 'test-full'
141
+ Requires-Dist: python-snappy; extra == 'test-full'
142
+ Requires-Dist: requests; extra == 'test-full'
143
+ Requires-Dist: smbprotocol; extra == 'test-full'
144
+ Requires-Dist: tqdm; extra == 'test-full'
145
+ Requires-Dist: urllib3; extra == 'test-full'
146
+ Requires-Dist: zarr; extra == 'test-full'
147
+ Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'
148
+ Provides-Extra: tqdm
149
+ Requires-Dist: tqdm; extra == 'tqdm'
150
+ Description-Content-Type: text/markdown
151
+
152
+ # filesystem_spec
153
+
154
+ [![PyPI version](https://badge.fury.io/py/fsspec.svg)](https://pypi.python.org/pypi/fsspec/)
155
+ [![Anaconda-Server Badge](https://anaconda.org/conda-forge/fsspec/badges/version.svg)](https://anaconda.org/conda-forge/fsspec)
156
+ ![Build](https://github.com/fsspec/filesystem_spec/workflows/CI/badge.svg)
157
+ [![Docs](https://readthedocs.org/projects/filesystem-spec/badge/?version=latest)](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
158
+
159
+ A specification for pythonic filesystems.
160
+
161
+ ## Install
162
+
163
+ ```bash
164
+ pip install fsspec
165
+ ```
166
+
167
+ would install the base fsspec. Various optionally supported features might require specification of custom
168
+ extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.
169
+ Use `pip install fsspec[full]` for installation of all known extra dependencies.
170
+
171
+ Up-to-date package also provided through conda-forge distribution:
172
+
173
+ ```bash
174
+ conda install -c conda-forge fsspec
175
+ ```
176
+
177
+
178
+ ## Purpose
179
+
180
+ To produce a template or specification for a file-system interface, that specific implementations should follow,
181
+ so that applications making use of them can rely on a common behaviour and not have to worry about the specific
182
+ internal implementation decisions with any given backend. Many such implementations are included in this package,
183
+ or in sister projects such as `s3fs` and `gcsfs`.
184
+
185
+ In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE
186
+ mounting of the file-system implementation may be available for all implementations "for free".
187
+
188
+ ## Documentation
189
+
190
+ Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
191
+
192
+ ## Develop
193
+
194
+ fsspec uses GitHub Actions for CI. Environment files can be found
195
+ in the "ci/" directory. Note that the main environment is called "py38",
196
+ but it is expected that the version of python installed be adjustable at
197
+ CI runtime. For local use, pick a version suitable for you.
198
+
199
+ ```bash
200
+ # For a new environment (mamba / conda).
201
+ mamba create -n fsspec -c conda-forge python=3.10 -y
202
+ conda activate fsspec
203
+
204
+ # Standard dev install with docs and tests.
205
+ pip install -e ".[dev,doc,test]"
206
+
207
+ # Full tests except for downstream
208
+ pip install s3fs
209
+ pip uninstall s3fs
210
+ pip install -e .[dev,doc,test_full]
211
+ pip install s3fs --no-deps
212
+ pytest -v
213
+
214
+ # Downstream tests.
215
+ sh install_s3fs.sh
216
+ # Windows powershell.
217
+ install_s3fs.sh
218
+ ```
219
+
220
+ ### Testing
221
+
222
+ Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
223
+
224
+ The full fsspec suite requires a system-level docker, docker-compose, and fuse
225
+ installation. If only making changes to one backend implementation, it is
226
+ not generally necessary to run all tests locally.
227
+
228
+ It is expected that contributors ensure that any change to fsspec does not
229
+ cause issues or regressions for either other fsspec-related packages such
230
+ as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI
231
+ run and corresponding environment file run a set of tests from the dask
232
+ test suite, and very minimal tests against pandas and zarr from the
233
+ test_downstream.py module in this repo.
234
+
235
+ ### Code Formatting
236
+
237
+ fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure
238
+ a consistent code format throughout the project.
239
+ Run ``black fsspec`` from the root of the filesystem_spec repository to
240
+ auto-format your code. Additionally, many editors have plugins that will apply
241
+ ``black`` as you edit files. ``black`` is included in the ``tox`` environments.
242
+
243
+ Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to
244
+ automatically run ``black`` when you make a git commit.
245
+ Run ``pre-commit install --install-hooks`` from the root of the
246
+ filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run
247
+ before you commit, reformatting any changed files. You can format without
248
+ committing via ``pre-commit run`` or skip these checks with ``git commit
249
+ --no-verify``.
250
+
251
+ ## Support
252
+
253
+ Work on this repository is supported in part by:
254
+
255
+ "Anaconda, Inc. - Advancing AI through open source."
256
+
257
+ <a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>
.cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec/callbacks.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import wraps
2
+
3
+
4
+ class Callback:
5
+ """
6
+ Base class and interface for callback mechanism
7
+
8
+ This class can be used directly for monitoring file transfers by
9
+ providing ``callback=Callback(hooks=...)`` (see the ``hooks`` argument,
10
+ below), or subclassed for more specialised behaviour.
11
+
12
+ Parameters
13
+ ----------
14
+ size: int (optional)
15
+ Nominal quantity for the value that corresponds to a complete
16
+ transfer, e.g., total number of tiles or total number of
17
+ bytes
18
+ value: int (0)
19
+ Starting internal counter value
20
+ hooks: dict or None
21
+ A dict of named functions to be called on each update. The signature
22
+ of these must be ``f(size, value, **kwargs)``
23
+ """
24
+
25
+ def __init__(self, size=None, value=0, hooks=None, **kwargs):
26
+ self.size = size
27
+ self.value = value
28
+ self.hooks = hooks or {}
29
+ self.kw = kwargs
30
+
31
+ def __enter__(self):
32
+ return self
33
+
34
+ def __exit__(self, *exc_args):
35
+ self.close()
36
+
37
+ def close(self):
38
+ """Close callback."""
39
+
40
+ def branched(self, path_1, path_2, **kwargs):
41
+ """
42
+ Return callback for child transfers
43
+
44
+ If this callback is operating at a higher level, e.g., put, which may
45
+ trigger transfers that can also be monitored. The function returns a callback
46
+ that has to be passed to the child method, e.g., put_file,
47
+ as `callback=` argument.
48
+
49
+ The implementation uses `callback.branch` for compatibility.
50
+ When implementing callbacks, it is recommended to override this function instead
51
+ of `branch` and avoid calling `super().branched(...)`.
52
+
53
+ Prefer using this function over `branch`.
54
+
55
+ Parameters
56
+ ----------
57
+ path_1: str
58
+ Child's source path
59
+ path_2: str
60
+ Child's destination path
61
+ **kwargs:
62
+ Arbitrary keyword arguments
63
+
64
+ Returns
65
+ -------
66
+ callback: Callback
67
+ A callback instance to be passed to the child method
68
+ """
69
+ self.branch(path_1, path_2, kwargs)
70
+ # mutate kwargs so that we can force the caller to pass "callback=" explicitly
71
+ return kwargs.pop("callback", DEFAULT_CALLBACK)
72
+
73
+ def branch_coro(self, fn):
74
+ """
75
+ Wraps a coroutine, and pass a new child callback to it.
76
+ """
77
+
78
+ @wraps(fn)
79
+ async def func(path1, path2: str, **kwargs):
80
+ with self.branched(path1, path2, **kwargs) as child:
81
+ return await fn(path1, path2, callback=child, **kwargs)
82
+
83
+ return func
84
+
85
+ def set_size(self, size):
86
+ """
87
+ Set the internal maximum size attribute
88
+
89
+ Usually called if not initially set at instantiation. Note that this
90
+ triggers a ``call()``.
91
+
92
+ Parameters
93
+ ----------
94
+ size: int
95
+ """
96
+ self.size = size
97
+ self.call()
98
+
99
+ def absolute_update(self, value):
100
+ """
101
+ Set the internal value state
102
+
103
+ Triggers ``call()``
104
+
105
+ Parameters
106
+ ----------
107
+ value: int
108
+ """
109
+ self.value = value
110
+ self.call()
111
+
112
+ def relative_update(self, inc=1):
113
+ """
114
+ Delta increment the internal counter
115
+
116
+ Triggers ``call()``
117
+
118
+ Parameters
119
+ ----------
120
+ inc: int
121
+ """
122
+ self.value += inc
123
+ self.call()
124
+
125
+ def call(self, hook_name=None, **kwargs):
126
+ """
127
+ Execute hook(s) with current state
128
+
129
+ Each function is passed the internal size and current value
130
+
131
+ Parameters
132
+ ----------
133
+ hook_name: str or None
134
+ If given, execute on this hook
135
+ kwargs: passed on to (all) hook(s)
136
+ """
137
+ if not self.hooks:
138
+ return
139
+ kw = self.kw.copy()
140
+ kw.update(kwargs)
141
+ if hook_name:
142
+ if hook_name not in self.hooks:
143
+ return
144
+ return self.hooks[hook_name](self.size, self.value, **kw)
145
+ for hook in self.hooks.values() or []:
146
+ hook(self.size, self.value, **kw)
147
+
148
+ def wrap(self, iterable):
149
+ """
150
+ Wrap an iterable to call ``relative_update`` on each iterations
151
+
152
+ Parameters
153
+ ----------
154
+ iterable: Iterable
155
+ The iterable that is being wrapped
156
+ """
157
+ for item in iterable:
158
+ self.relative_update()
159
+ yield item
160
+
161
+ def branch(self, path_1, path_2, kwargs):
162
+ """
163
+ Set callbacks for child transfers
164
+
165
+ If this callback is operating at a higher level, e.g., put, which may
166
+ trigger transfers that can also be monitored. The passed kwargs are
167
+ to be *mutated* to add ``callback=``, if this class supports branching
168
+ to children.
169
+
170
+ Parameters
171
+ ----------
172
+ path_1: str
173
+ Child's source path
174
+ path_2: str
175
+ Child's destination path
176
+ kwargs: dict
177
+ arguments passed to child method, e.g., put_file.
178
+
179
+ Returns
180
+ -------
181
+
182
+ """
183
+ return None
184
+
185
+ def no_op(self, *_, **__):
186
+ pass
187
+
188
+ def __getattr__(self, item):
189
+ """
190
+ If undefined methods are called on this class, nothing happens
191
+ """
192
+ return self.no_op
193
+
194
+ @classmethod
195
+ def as_callback(cls, maybe_callback=None):
196
+ """Transform callback=... into Callback instance
197
+
198
+ For the special value of ``None``, return the global instance of
199
+ ``NoOpCallback``. This is an alternative to including
200
+ ``callback=DEFAULT_CALLBACK`` directly in a method signature.
201
+ """
202
+ if maybe_callback is None:
203
+ return DEFAULT_CALLBACK
204
+ return maybe_callback
205
+
206
+
207
+ class NoOpCallback(Callback):
208
+ """
209
+ This implementation of Callback does exactly nothing
210
+ """
211
+
212
+ def call(self, *args, **kwargs):
213
+ return None
214
+
215
+
216
+ class DotPrinterCallback(Callback):
217
+ """
218
+ Simple example Callback implementation
219
+
220
+ Almost identical to Callback with a hook that prints a char; here we
221
+ demonstrate how the outer layer may print "#" and the inner layer "."
222
+ """
223
+
224
+ def __init__(self, chr_to_print="#", **kwargs):
225
+ self.chr = chr_to_print
226
+ super().__init__(**kwargs)
227
+
228
+ def branch(self, path_1, path_2, kwargs):
229
+ """Mutate kwargs to add new instance with different print char"""
230
+ kwargs["callback"] = DotPrinterCallback(".")
231
+
232
+ def call(self, **kwargs):
233
+ """Just outputs a character"""
234
+ print(self.chr, end="")
235
+
236
+
237
+ class TqdmCallback(Callback):
238
+ """
239
+ A callback to display a progress bar using tqdm
240
+
241
+ Parameters
242
+ ----------
243
+ tqdm_kwargs : dict, (optional)
244
+ Any argument accepted by the tqdm constructor.
245
+ See the `tqdm doc <https://tqdm.github.io/docs/tqdm/#__init__>`_.
246
+ Will be forwarded to `tqdm_cls`.
247
+ tqdm_cls: (optional)
248
+ subclass of `tqdm.tqdm`. If not passed, it will default to `tqdm.tqdm`.
249
+
250
+ Examples
251
+ --------
252
+ >>> import fsspec
253
+ >>> from fsspec.callbacks import TqdmCallback
254
+ >>> fs = fsspec.filesystem("memory")
255
+ >>> path2distant_data = "/your-path"
256
+ >>> fs.upload(
257
+ ".",
258
+ path2distant_data,
259
+ recursive=True,
260
+ callback=TqdmCallback(),
261
+ )
262
+
263
+ You can forward args to tqdm using the ``tqdm_kwargs`` parameter.
264
+
265
+ >>> fs.upload(
266
+ ".",
267
+ path2distant_data,
268
+ recursive=True,
269
+ callback=TqdmCallback(tqdm_kwargs={"desc": "Your tqdm description"}),
270
+ )
271
+
272
+ You can also customize the progress bar by passing a subclass of `tqdm`.
273
+
274
+ .. code-block:: python
275
+
276
+ class TqdmFormat(tqdm):
277
+ '''Provides a `total_time` format parameter'''
278
+ @property
279
+ def format_dict(self):
280
+ d = super().format_dict
281
+ total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1)
282
+ d.update(total_time=self.format_interval(total_time) + " in total")
283
+ return d
284
+
285
+ >>> with TqdmCallback(
286
+ tqdm_kwargs={
287
+ "desc": "desc",
288
+ "bar_format": "{total_time}: {percentage:.0f}%|{bar}{r_bar}",
289
+ },
290
+ tqdm_cls=TqdmFormat,
291
+ ) as callback:
292
+ fs.upload(".", path2distant_data, recursive=True, callback=callback)
293
+ """
294
+
295
+ def __init__(self, tqdm_kwargs=None, *args, **kwargs):
296
+ try:
297
+ from tqdm import tqdm
298
+
299
+ except ImportError as exce:
300
+ raise ImportError(
301
+ "Using TqdmCallback requires tqdm to be installed"
302
+ ) from exce
303
+
304
+ self._tqdm_cls = kwargs.pop("tqdm_cls", tqdm)
305
+ self._tqdm_kwargs = tqdm_kwargs or {}
306
+ self.tqdm = None
307
+ super().__init__(*args, **kwargs)
308
+
309
+ def call(self, *args, **kwargs):
310
+ if self.tqdm is None:
311
+ self.tqdm = self._tqdm_cls(total=self.size, **self._tqdm_kwargs)
312
+ self.tqdm.total = self.size
313
+ self.tqdm.update(self.value - self.tqdm.n)
314
+
315
+ def close(self):
316
+ if self.tqdm is not None:
317
+ self.tqdm.close()
318
+ self.tqdm = None
319
+
320
+ def __del__(self):
321
+ return self.close()
322
+
323
+
324
+ DEFAULT_CALLBACK = _DEFAULT_CALLBACK = NoOpCallback()
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/__init__.py ADDED
File without changes
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/html_re.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regexps to match html elements"""
2
+
3
+ import re
4
+
5
+ attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*"
6
+
7
+ unquoted = "[^\"'=<>`\\x00-\\x20]+"
8
+ single_quoted = "'[^']*'"
9
+ double_quoted = '"[^"]*"'
10
+
11
+ attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")"
12
+
13
+ attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)"
14
+
15
+ open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>"
16
+
17
+ close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>"
18
+ comment = "<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->"
19
+ processing = "<[?][\\s\\S]*?[?]>"
20
+ declaration = "<![A-Za-z][^>]*>"
21
+ cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>"
22
+
23
+ HTML_TAG_RE = re.compile(
24
+ "^(?:"
25
+ + open_tag
26
+ + "|"
27
+ + close_tag
28
+ + "|"
29
+ + comment
30
+ + "|"
31
+ + processing
32
+ + "|"
33
+ + declaration
34
+ + "|"
35
+ + cdata
36
+ + ")"
37
+ )
38
+ HTML_OPEN_CLOSE_TAG_STR = "^(?:" + open_tag + "|" + close_tag + ")"
39
+ HTML_OPEN_CLOSE_TAG_RE = re.compile(HTML_OPEN_CLOSE_TAG_STR)
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/utils.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for parsing source text"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from re import Match
7
+ from typing import TypeVar
8
+ import unicodedata
9
+
10
+ from .entities import entities
11
+
12
+
13
+ def charCodeAt(src: str, pos: int) -> int | None:
14
+ """
15
+ Returns the Unicode value of the character at the specified location.
16
+
17
+ @param - index The zero-based index of the desired character.
18
+ If there is no character at the specified index, NaN is returned.
19
+
20
+ This was added for compatibility with python
21
+ """
22
+ try:
23
+ return ord(src[pos])
24
+ except IndexError:
25
+ return None
26
+
27
+
28
+ def charStrAt(src: str, pos: int) -> str | None:
29
+ """
30
+ Returns the Unicode value of the character at the specified location.
31
+
32
+ @param - index The zero-based index of the desired character.
33
+ If there is no character at the specified index, NaN is returned.
34
+
35
+ This was added for compatibility with python
36
+ """
37
+ try:
38
+ return src[pos]
39
+ except IndexError:
40
+ return None
41
+
42
+
43
+ _ItemTV = TypeVar("_ItemTV")
44
+
45
+
46
+ def arrayReplaceAt(
47
+ src: list[_ItemTV], pos: int, newElements: list[_ItemTV]
48
+ ) -> list[_ItemTV]:
49
+ """
50
+ Remove element from array and put another array at those position.
51
+ Useful for some operations with tokens
52
+ """
53
+ return src[:pos] + newElements + src[pos + 1 :]
54
+
55
+
56
+ def isValidEntityCode(c: int) -> bool:
57
+ # broken sequence
58
+ if c >= 0xD800 and c <= 0xDFFF:
59
+ return False
60
+ # never used
61
+ if c >= 0xFDD0 and c <= 0xFDEF:
62
+ return False
63
+ if ((c & 0xFFFF) == 0xFFFF) or ((c & 0xFFFF) == 0xFFFE):
64
+ return False
65
+ # control codes
66
+ if c >= 0x00 and c <= 0x08:
67
+ return False
68
+ if c == 0x0B:
69
+ return False
70
+ if c >= 0x0E and c <= 0x1F:
71
+ return False
72
+ if c >= 0x7F and c <= 0x9F:
73
+ return False
74
+ # out of range
75
+ return not (c > 0x10FFFF)
76
+
77
+
78
+ def fromCodePoint(c: int) -> str:
79
+ """Convert ordinal to unicode.
80
+
81
+ Note, in the original Javascript two string characters were required,
82
+ for codepoints larger than `0xFFFF`.
83
+ But Python 3 can represent any unicode codepoint in one character.
84
+ """
85
+ return chr(c)
86
+
87
+
88
+ # UNESCAPE_MD_RE = re.compile(r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])')
89
+ # ENTITY_RE_g = re.compile(r'&([a-z#][a-z0-9]{1,31})', re.IGNORECASE)
90
+ UNESCAPE_ALL_RE = re.compile(
91
+ r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])' + "|" + r"&([a-z#][a-z0-9]{1,31});",
92
+ re.IGNORECASE,
93
+ )
94
+ DIGITAL_ENTITY_BASE10_RE = re.compile(r"#([0-9]{1,8})")
95
+ DIGITAL_ENTITY_BASE16_RE = re.compile(r"#x([a-f0-9]{1,8})", re.IGNORECASE)
96
+
97
+
98
+ def replaceEntityPattern(match: str, name: str) -> str:
99
+ """Convert HTML entity patterns,
100
+ see https://spec.commonmark.org/0.30/#entity-references
101
+ """
102
+ if name in entities:
103
+ return entities[name]
104
+
105
+ code: None | int = None
106
+ if pat := DIGITAL_ENTITY_BASE10_RE.fullmatch(name):
107
+ code = int(pat.group(1), 10)
108
+ elif pat := DIGITAL_ENTITY_BASE16_RE.fullmatch(name):
109
+ code = int(pat.group(1), 16)
110
+
111
+ if code is not None and isValidEntityCode(code):
112
+ return fromCodePoint(code)
113
+
114
+ return match
115
+
116
+
117
+ def unescapeAll(string: str) -> str:
118
+ def replacer_func(match: Match[str]) -> str:
119
+ escaped = match.group(1)
120
+ if escaped:
121
+ return escaped
122
+ entity = match.group(2)
123
+ return replaceEntityPattern(match.group(), entity)
124
+
125
+ if "\\" not in string and "&" not in string:
126
+ return string
127
+ return UNESCAPE_ALL_RE.sub(replacer_func, string)
128
+
129
+
130
+ ESCAPABLE = r"""\\!"#$%&'()*+,./:;<=>?@\[\]^`{}|_~-"""
131
+ ESCAPE_CHAR = re.compile(r"\\([" + ESCAPABLE + r"])")
132
+
133
+
134
+ def stripEscape(string: str) -> str:
135
+ """Strip escape \\ characters"""
136
+ return ESCAPE_CHAR.sub(r"\1", string)
137
+
138
+
139
+ def escapeHtml(raw: str) -> str:
140
+ """Replace special characters "&", "<", ">" and '"' to HTML-safe sequences."""
141
+ # like html.escape, but without escaping single quotes
142
+ raw = raw.replace("&", "&amp;") # Must be done first!
143
+ raw = raw.replace("<", "&lt;")
144
+ raw = raw.replace(">", "&gt;")
145
+ raw = raw.replace('"', "&quot;")
146
+ return raw
147
+
148
+
149
+ # //////////////////////////////////////////////////////////////////////////////
150
+
151
+ REGEXP_ESCAPE_RE = re.compile(r"[.?*+^$[\]\\(){}|-]")
152
+
153
+
154
+ def escapeRE(string: str) -> str:
155
+ string = REGEXP_ESCAPE_RE.sub("\\$&", string)
156
+ return string
157
+
158
+
159
+ # //////////////////////////////////////////////////////////////////////////////
160
+
161
+
162
+ def isSpace(code: int | None) -> bool:
163
+ """Check if character code is a whitespace."""
164
+ return code in (0x09, 0x20)
165
+
166
+
167
+ def isStrSpace(ch: str | None) -> bool:
168
+ """Check if character is a whitespace."""
169
+ return ch in ("\t", " ")
170
+
171
+
172
+ MD_WHITESPACE = {
173
+ 0x09, # \t
174
+ 0x0A, # \n
175
+ 0x0B, # \v
176
+ 0x0C, # \f
177
+ 0x0D, # \r
178
+ 0x20, # space
179
+ 0xA0,
180
+ 0x1680,
181
+ 0x202F,
182
+ 0x205F,
183
+ 0x3000,
184
+ }
185
+
186
+
187
+ def isWhiteSpace(code: int) -> bool:
188
+ r"""Zs (unicode class) || [\t\f\v\r\n]"""
189
+ if code >= 0x2000 and code <= 0x200A:
190
+ return True
191
+ return code in MD_WHITESPACE
192
+
193
+
194
+ # //////////////////////////////////////////////////////////////////////////////
195
+
196
+
197
+ def isPunctChar(ch: str) -> bool:
198
+ """Check if character is a punctuation character."""
199
+ return unicodedata.category(ch).startswith(("P", "S"))
200
+
201
+
202
+ MD_ASCII_PUNCT = {
203
+ 0x21, # /* ! */
204
+ 0x22, # /* " */
205
+ 0x23, # /* # */
206
+ 0x24, # /* $ */
207
+ 0x25, # /* % */
208
+ 0x26, # /* & */
209
+ 0x27, # /* ' */
210
+ 0x28, # /* ( */
211
+ 0x29, # /* ) */
212
+ 0x2A, # /* * */
213
+ 0x2B, # /* + */
214
+ 0x2C, # /* , */
215
+ 0x2D, # /* - */
216
+ 0x2E, # /* . */
217
+ 0x2F, # /* / */
218
+ 0x3A, # /* : */
219
+ 0x3B, # /* ; */
220
+ 0x3C, # /* < */
221
+ 0x3D, # /* = */
222
+ 0x3E, # /* > */
223
+ 0x3F, # /* ? */
224
+ 0x40, # /* @ */
225
+ 0x5B, # /* [ */
226
+ 0x5C, # /* \ */
227
+ 0x5D, # /* ] */
228
+ 0x5E, # /* ^ */
229
+ 0x5F, # /* _ */
230
+ 0x60, # /* ` */
231
+ 0x7B, # /* { */
232
+ 0x7C, # /* | */
233
+ 0x7D, # /* } */
234
+ 0x7E, # /* ~ */
235
+ }
236
+
237
+
238
+ def isMdAsciiPunct(ch: int) -> bool:
239
+ """Markdown ASCII punctuation characters.
240
+
241
+ ::
242
+
243
+ !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \\, ], ^, _, `, {, |, }, or ~
244
+
245
+ See http://spec.commonmark.org/0.15/#ascii-punctuation-character
246
+
247
+ Don't confuse with unicode punctuation !!! It lacks some chars in ascii range.
248
+
249
+ """
250
+ return ch in MD_ASCII_PUNCT
251
+
252
+
253
+ def normalizeReference(string: str) -> str:
254
+ """Helper to unify [reference labels]."""
255
+ # Trim and collapse whitespace
256
+ #
257
+ string = re.sub(r"\s+", " ", string.strip())
258
+
259
+ # In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug
260
+ # fixed in v12 (couldn't find any details).
261
+ #
262
+ # So treat this one as a special case
263
+ # (remove this when node v10 is no longer supported).
264
+ #
265
+ # if ('ẞ'.toLowerCase() === 'Ṿ') {
266
+ # str = str.replace(/ẞ/g, 'ß')
267
+ # }
268
+
269
+ # .toLowerCase().toUpperCase() should get rid of all differences
270
+ # between letter variants.
271
+ #
272
+ # Simple .toLowerCase() doesn't normalize 125 code points correctly,
273
+ # and .toUpperCase doesn't normalize 6 of them (list of exceptions:
274
+ # İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently
275
+ # uppercased versions).
276
+ #
277
+ # Here's an example showing how it happens. Lets take greek letter omega:
278
+ # uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ)
279
+ #
280
+ # Unicode entries:
281
+ # 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8
282
+ # 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398
283
+ # 03D1;GREEK THETA SYMBOL;Ll;0;L;<compat> 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398
284
+ # 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L;<compat> 0398;;;;N;;;;03B8
285
+ #
286
+ # Case-insensitive comparison should treat all of them as equivalent.
287
+ #
288
+ # But .toLowerCase() doesn't change ϑ (it's already lowercase),
289
+ # and .toUpperCase() doesn't change ϴ (already uppercase).
290
+ #
291
+ # Applying first lower then upper case normalizes any character:
292
+ # '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398'
293
+ #
294
+ # Note: this is equivalent to unicode case folding; unicode normalization
295
+ # is a different step that is not required here.
296
+ #
297
+ # Final result should be uppercased, because it's later stored in an object
298
+ # (this avoid a conflict with Object.prototype members,
299
+ # most notably, `__proto__`)
300
+ #
301
+ return string.lower().upper()
302
+
303
+
304
+ LINK_OPEN_RE = re.compile(r"^<a[>\s]", flags=re.IGNORECASE)
305
+ LINK_CLOSE_RE = re.compile(r"^</a\s*>", flags=re.IGNORECASE)
306
+
307
+
308
+ def isLinkOpen(string: str) -> bool:
309
+ return bool(LINK_OPEN_RE.search(string))
310
+
311
+
312
+ def isLinkClose(string: str) -> bool:
313
+ return bool(LINK_CLOSE_RE.search(string))
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Functions for parsing Links"""
2
+
3
+ __all__ = ("parseLinkDestination", "parseLinkLabel", "parseLinkTitle")
4
+ from .parse_link_destination import parseLinkDestination
5
+ from .parse_link_label import parseLinkLabel
6
+ from .parse_link_title import parseLinkTitle
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/parse_link_title.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse link title"""
2
+
3
+ from ..common.utils import charCodeAt, unescapeAll
4
+
5
+
6
+ class _State:
7
+ __slots__ = ("can_continue", "marker", "ok", "pos", "str")
8
+
9
+ def __init__(self) -> None:
10
+ self.ok = False
11
+ """if `true`, this is a valid link title"""
12
+ self.can_continue = False
13
+ """if `true`, this link can be continued on the next line"""
14
+ self.pos = 0
15
+ """if `ok`, it's the position of the first character after the closing marker"""
16
+ self.str = ""
17
+ """if `ok`, it's the unescaped title"""
18
+ self.marker = 0
19
+ """expected closing marker character code"""
20
+
21
+ def __str__(self) -> str:
22
+ return self.str
23
+
24
+
25
+ def parseLinkTitle(
26
+ string: str, start: int, maximum: int, prev_state: _State | None = None
27
+ ) -> _State:
28
+ """Parse link title within `str` in [start, max] range,
29
+ or continue previous parsing if `prev_state` is defined (equal to result of last execution).
30
+ """
31
+ pos = start
32
+ state = _State()
33
+
34
+ if prev_state is not None:
35
+ # this is a continuation of a previous parseLinkTitle call on the next line,
36
+ # used in reference links only
37
+ state.str = prev_state.str
38
+ state.marker = prev_state.marker
39
+ else:
40
+ if pos >= maximum:
41
+ return state
42
+
43
+ marker = charCodeAt(string, pos)
44
+
45
+ # /* " */ /* ' */ /* ( */
46
+ if marker != 0x22 and marker != 0x27 and marker != 0x28:
47
+ return state
48
+
49
+ start += 1
50
+ pos += 1
51
+
52
+ # if opening marker is "(", switch it to closing marker ")"
53
+ if marker == 0x28:
54
+ marker = 0x29
55
+
56
+ state.marker = marker
57
+
58
+ while pos < maximum:
59
+ code = charCodeAt(string, pos)
60
+ if code == state.marker:
61
+ state.pos = pos + 1
62
+ state.str += unescapeAll(string[start:pos])
63
+ state.ok = True
64
+ return state
65
+ elif code == 0x28 and state.marker == 0x29: # /* ( */ /* ) */
66
+ return state
67
+ elif code == 0x5C and pos + 1 < maximum: # /* \ */
68
+ pos += 1
69
+
70
+ pos += 1
71
+
72
+ # no closing marker found, but this link title may continue on the next line (for references)
73
+ state.can_continue = True
74
+ state.str += unescapeAll(string[start:pos])
75
+ return state
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/parser_core.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ * class Core
3
+ *
4
+ * Top-level rules executor. Glues block/inline parsers and does intermediate
5
+ * transformations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+
12
+ from .ruler import Ruler
13
+ from .rules_core import (
14
+ block,
15
+ inline,
16
+ linkify,
17
+ normalize,
18
+ replace,
19
+ smartquotes,
20
+ text_join,
21
+ )
22
+ from .rules_core.state_core import StateCore
23
+
24
+ RuleFuncCoreType = Callable[[StateCore], None]
25
+
26
+ _rules: list[tuple[str, RuleFuncCoreType]] = [
27
+ ("normalize", normalize),
28
+ ("block", block),
29
+ ("inline", inline),
30
+ ("linkify", linkify),
31
+ ("replacements", replace),
32
+ ("smartquotes", smartquotes),
33
+ ("text_join", text_join),
34
+ ]
35
+
36
+
37
+ class ParserCore:
38
+ def __init__(self) -> None:
39
+ self.ruler = Ruler[RuleFuncCoreType]()
40
+ for name, rule in _rules:
41
+ self.ruler.push(name, rule)
42
+
43
+ def process(self, state: StateCore) -> None:
44
+ """Executes core chain rules."""
45
+ for rule in self.ruler.getRules(""):
46
+ rule(state)
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/port.yaml ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - package: markdown-it/markdown-it
2
+ version: 14.1.0
3
+ commit: 0fe7ccb4b7f30236fb05f623be6924961d296d3d
4
+ date: Mar 19, 2024
5
+ notes:
6
+ - Rename variables that use python built-in names, e.g.
7
+ - `max` -> `maximum`
8
+ - `len` -> `length`
9
+ - `str` -> `string`
10
+ - |
11
+ Convert JS `for` loops to `while` loops
12
+ this is generally the main difference between the codes,
13
+ because in python you can't do e.g. `for {i=1;i<x;i++} {}`
14
+ - |
15
+ `env` is a common Python dictionary, and so does not have attribute access to keys,
16
+ as with JavaScript dictionaries.
17
+ `options` have attribute access only to core markdownit configuration options
18
+ - |
19
+ `Token.attrs` is a dictionary, instead of a list of lists.
20
+ Upstream the list format is only used to guarantee order: https://github.com/markdown-it/markdown-it/issues/142,
21
+ but in Python 3.7+ order of dictionaries is guaranteed.
22
+ One should anyhow use the `attrGet`, `attrSet`, `attrPush` and `attrJoin` methods
23
+ to manipulate `Token.attrs`, which have an identical signature to those upstream.
24
+ - Use python version of `charCodeAt`
25
+ - |
26
+ Use `str` units instead of `int`s to represent Unicode codepoints.
27
+ This provides a significant performance boost
28
+ - |
29
+ In markdown_it/rules_block/reference.py,
30
+ record line range in state.env["references"] and add state.env["duplicate_refs"]
31
+ This is to allow renderers to report on issues regarding references
32
+ - |
33
+ The `MarkdownIt.__init__` signature is slightly different for updating options,
34
+ since you must always specify the config first, e.g.
35
+ use `MarkdownIt("commonmark", {"html": False})` instead of `MarkdownIt({"html": False})`
36
+ - The default configuration preset for `MarkdownIt` is "commonmark" not "default"
37
+ - Allow custom renderer to be passed to `MarkdownIt`
38
+ - |
39
+ change render method signatures
40
+ `func(tokens, idx, options, env, slf)` to
41
+ `func(self, tokens, idx, options, env)`
42
+ - |
43
+ Extensions add render methods by format
44
+ `MarkdownIt.add_render_rule(name, function, fmt="html")`,
45
+ rather than `MarkdownIt.renderer.rules[name] = function`
46
+ and renderers should declare a class property `__output__ = "html"`.
47
+ This allows for extensibility to more than just HTML renderers
48
+ - inline tokens in tables are assigned a map (this is helpful for propagation to children)
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/default.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """markdown-it default options."""
2
+
3
+ from ..utils import PresetType
4
+
5
+
6
+ def make() -> PresetType:
7
+ return {
8
+ "options": {
9
+ "maxNesting": 100, # Internal protection, recursion limit
10
+ "html": False, # Enable HTML tags in source
11
+ # this is just a shorthand for .disable(["html_inline", "html_block"])
12
+ # used by the linkify rule:
13
+ "linkify": False, # autoconvert URL-like texts to links
14
+ # used by the replacements and smartquotes rules:
15
+ # Enable some language-neutral replacements + quotes beautification
16
+ "typographer": False,
17
+ # used by the smartquotes rule:
18
+ # Double + single quotes replacement pairs, when typographer enabled,
19
+ # and smartquotes on. Could be either a String or an Array.
20
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
21
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
22
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
23
+ # Renderer specific; these options are used directly in the HTML renderer
24
+ "xhtmlOut": False, # Use '/' to close single tags (<br />)
25
+ "breaks": False, # Convert '\n' in paragraphs into <br>
26
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
27
+ # Highlighter function. Should return escaped HTML,
28
+ # or '' if the source string is not changed and should be escaped externally.
29
+ # If result starts with <pre... internal wrapper is skipped.
30
+ #
31
+ # function (/*str, lang, attrs*/) { return ''; }
32
+ #
33
+ "highlight": None,
34
+ },
35
+ "components": {"core": {}, "block": {}, "inline": {}},
36
+ }
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/zero.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ "Zero" preset, with nothing enabled. Useful for manual configuring of simple
3
+ modes. For example, to parse bold/italic only.
4
+ """
5
+
6
+ from ..utils import PresetType
7
+
8
+
9
+ def make() -> PresetType:
10
+ return {
11
+ "options": {
12
+ "maxNesting": 20, # Internal protection, recursion limit
13
+ "html": False, # Enable HTML tags in source
14
+ # this is just a shorthand for .disable(["html_inline", "html_block"])
15
+ # used by the linkify rule:
16
+ "linkify": False, # autoconvert URL-like texts to links
17
+ # used by the replacements and smartquotes rules:
18
+ # Enable some language-neutral replacements + quotes beautification
19
+ "typographer": False,
20
+ # used by the smartquotes rule:
21
+ # Double + single quotes replacement pairs, when typographer enabled,
22
+ # and smartquotes on. Could be either a String or an Array.
23
+ # For example, you can use '«»„“' for Russian, '„“‚‘' for German,
24
+ # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
25
+ "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
26
+ # Renderer specific; these options are used directly in the HTML renderer
27
+ "xhtmlOut": False, # Use '/' to close single tags (<br />)
28
+ "breaks": False, # Convert '\n' in paragraphs into <br>
29
+ "langPrefix": "language-", # CSS language prefix for fenced blocks
30
+ # Highlighter function. Should return escaped HTML,
31
+ # or '' if the source string is not changed and should be escaped externally.
32
+ # If result starts with <pre... internal wrapper is skipped.
33
+ # function (/*str, lang, attrs*/) { return ''; }
34
+ "highlight": None,
35
+ },
36
+ "components": {
37
+ "core": {"rules": ["normalize", "block", "inline", "text_join"]},
38
+ "block": {"rules": ["paragraph"]},
39
+ "inline": {
40
+ "rules": ["text"],
41
+ "rules2": ["balance_pairs", "fragments_join"],
42
+ },
43
+ },
44
+ }
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/ruler.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ class Ruler
3
+
4
+ Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and
5
+ [[MarkdownIt#inline]] to manage sequences of functions (rules):
6
+
7
+ - keep rules in defined order
8
+ - assign the name to each rule
9
+ - enable/disable rules
10
+ - add/replace rules
11
+ - allow assign rules to additional named chains (in the same)
12
+ - caching lists of active rules
13
+
14
+ You will not need use this class directly until write plugins. For simple
15
+ rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and
16
+ [[MarkdownIt.use]].
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Iterable
22
+ from dataclasses import dataclass, field
23
+ from typing import TYPE_CHECKING, Generic, TypedDict, TypeVar
24
+ import warnings
25
+
26
+ from .utils import EnvType
27
+
28
+ if TYPE_CHECKING:
29
+ from markdown_it import MarkdownIt
30
+
31
+
32
+ class StateBase:
33
+ def __init__(self, src: str, md: MarkdownIt, env: EnvType):
34
+ self.src = src
35
+ self.env = env
36
+ self.md = md
37
+
38
+ @property
39
+ def src(self) -> str:
40
+ return self._src
41
+
42
+ @src.setter
43
+ def src(self, value: str) -> None:
44
+ self._src = value
45
+ self._srcCharCode: tuple[int, ...] | None = None
46
+
47
+ @property
48
+ def srcCharCode(self) -> tuple[int, ...]:
49
+ warnings.warn(
50
+ "StateBase.srcCharCode is deprecated. Use StateBase.src instead.",
51
+ DeprecationWarning,
52
+ stacklevel=2,
53
+ )
54
+ if self._srcCharCode is None:
55
+ self._srcCharCode = tuple(ord(c) for c in self._src)
56
+ return self._srcCharCode
57
+
58
+
59
+ class RuleOptionsType(TypedDict, total=False):
60
+ alt: list[str]
61
+
62
+
63
+ RuleFuncTv = TypeVar("RuleFuncTv")
64
+ """A rule function, whose signature is dependent on the state type."""
65
+
66
+
67
+ @dataclass(slots=True)
68
+ class Rule(Generic[RuleFuncTv]):
69
+ name: str
70
+ enabled: bool
71
+ fn: RuleFuncTv = field(repr=False)
72
+ alt: list[str]
73
+
74
+
75
+ class Ruler(Generic[RuleFuncTv]):
76
+ def __init__(self) -> None:
77
+ # List of added rules.
78
+ self.__rules__: list[Rule[RuleFuncTv]] = []
79
+ # Cached rule chains.
80
+ # First level - chain name, '' for default.
81
+ # Second level - diginal anchor for fast filtering by charcodes.
82
+ self.__cache__: dict[str, list[RuleFuncTv]] | None = None
83
+
84
+ def __find__(self, name: str) -> int:
85
+ """Find rule index by name"""
86
+ for i, rule in enumerate(self.__rules__):
87
+ if rule.name == name:
88
+ return i
89
+ return -1
90
+
91
+ def __compile__(self) -> None:
92
+ """Build rules lookup cache"""
93
+ chains = {""}
94
+ # collect unique names
95
+ for rule in self.__rules__:
96
+ if not rule.enabled:
97
+ continue
98
+ for name in rule.alt:
99
+ chains.add(name)
100
+ self.__cache__ = {}
101
+ for chain in chains:
102
+ self.__cache__[chain] = []
103
+ for rule in self.__rules__:
104
+ if not rule.enabled:
105
+ continue
106
+ if chain and (chain not in rule.alt):
107
+ continue
108
+ self.__cache__[chain].append(rule.fn)
109
+
110
+ def at(
111
+ self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
112
+ ) -> None:
113
+ """Replace rule by name with new function & options.
114
+
115
+ :param ruleName: rule name to replace.
116
+ :param fn: new rule function.
117
+ :param options: new rule options (not mandatory).
118
+ :raises: KeyError if name not found
119
+ """
120
+ index = self.__find__(ruleName)
121
+ options = options or {}
122
+ if index == -1:
123
+ raise KeyError(f"Parser rule not found: {ruleName}")
124
+ self.__rules__[index].fn = fn
125
+ self.__rules__[index].alt = options.get("alt", [])
126
+ self.__cache__ = None
127
+
128
+ def before(
129
+ self,
130
+ beforeName: str,
131
+ ruleName: str,
132
+ fn: RuleFuncTv,
133
+ options: RuleOptionsType | None = None,
134
+ ) -> None:
135
+ """Add new rule to chain before one with given name.
136
+
137
+ :param beforeName: new rule will be added before this one.
138
+ :param ruleName: new rule will be added before this one.
139
+ :param fn: new rule function.
140
+ :param options: new rule options (not mandatory).
141
+ :raises: KeyError if name not found
142
+ """
143
+ index = self.__find__(beforeName)
144
+ options = options or {}
145
+ if index == -1:
146
+ raise KeyError(f"Parser rule not found: {beforeName}")
147
+ self.__rules__.insert(
148
+ index, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
149
+ )
150
+ self.__cache__ = None
151
+
152
+ def after(
153
+ self,
154
+ afterName: str,
155
+ ruleName: str,
156
+ fn: RuleFuncTv,
157
+ options: RuleOptionsType | None = None,
158
+ ) -> None:
159
+ """Add new rule to chain after one with given name.
160
+
161
+ :param afterName: new rule will be added after this one.
162
+ :param ruleName: new rule will be added after this one.
163
+ :param fn: new rule function.
164
+ :param options: new rule options (not mandatory).
165
+ :raises: KeyError if name not found
166
+ """
167
+ index = self.__find__(afterName)
168
+ options = options or {}
169
+ if index == -1:
170
+ raise KeyError(f"Parser rule not found: {afterName}")
171
+ self.__rules__.insert(
172
+ index + 1, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
173
+ )
174
+ self.__cache__ = None
175
+
176
+ def push(
177
+ self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
178
+ ) -> None:
179
+ """Push new rule to the end of chain.
180
+
181
+ :param ruleName: new rule will be added to the end of chain.
182
+ :param fn: new rule function.
183
+ :param options: new rule options (not mandatory).
184
+
185
+ """
186
+ self.__rules__.append(
187
+ Rule[RuleFuncTv](ruleName, True, fn, (options or {}).get("alt", []))
188
+ )
189
+ self.__cache__ = None
190
+
191
+ def enable(
192
+ self, names: str | Iterable[str], ignoreInvalid: bool = False
193
+ ) -> list[str]:
194
+ """Enable rules with given names.
195
+
196
+ :param names: name or list of rule names to enable.
197
+ :param ignoreInvalid: ignore errors when rule not found
198
+ :raises: KeyError if name not found and not ignoreInvalid
199
+ :return: list of found rule names
200
+ """
201
+ if isinstance(names, str):
202
+ names = [names]
203
+ result: list[str] = []
204
+ for name in names:
205
+ idx = self.__find__(name)
206
+ if (idx < 0) and ignoreInvalid:
207
+ continue
208
+ if (idx < 0) and not ignoreInvalid:
209
+ raise KeyError(f"Rules manager: invalid rule name {name}")
210
+ self.__rules__[idx].enabled = True
211
+ result.append(name)
212
+ self.__cache__ = None
213
+ return result
214
+
215
+ def enableOnly(
216
+ self, names: str | Iterable[str], ignoreInvalid: bool = False
217
+ ) -> list[str]:
218
+ """Enable rules with given names, and disable everything else.
219
+
220
+ :param names: name or list of rule names to enable.
221
+ :param ignoreInvalid: ignore errors when rule not found
222
+ :raises: KeyError if name not found and not ignoreInvalid
223
+ :return: list of found rule names
224
+ """
225
+ if isinstance(names, str):
226
+ names = [names]
227
+ for rule in self.__rules__:
228
+ rule.enabled = False
229
+ return self.enable(names, ignoreInvalid)
230
+
231
+ def disable(
232
+ self, names: str | Iterable[str], ignoreInvalid: bool = False
233
+ ) -> list[str]:
234
+ """Disable rules with given names.
235
+
236
+ :param names: name or list of rule names to enable.
237
+ :param ignoreInvalid: ignore errors when rule not found
238
+ :raises: KeyError if name not found and not ignoreInvalid
239
+ :return: list of found rule names
240
+ """
241
+ if isinstance(names, str):
242
+ names = [names]
243
+ result = []
244
+ for name in names:
245
+ idx = self.__find__(name)
246
+ if (idx < 0) and ignoreInvalid:
247
+ continue
248
+ if (idx < 0) and not ignoreInvalid:
249
+ raise KeyError(f"Rules manager: invalid rule name {name}")
250
+ self.__rules__[idx].enabled = False
251
+ result.append(name)
252
+ self.__cache__ = None
253
+ return result
254
+
255
+ def getRules(self, chainName: str = "") -> list[RuleFuncTv]:
256
+ """Return array of active functions (rules) for given chain name.
257
+ It analyzes rules configuration, compiles caches if not exists and returns result.
258
+
259
+ Default chain name is `''` (empty string). It can't be skipped.
260
+ That's done intentionally, to keep signature monomorphic for high speed.
261
+
262
+ """
263
+ if self.__cache__ is None:
264
+ self.__compile__()
265
+ assert self.__cache__ is not None
266
+ # Chain can be empty, if rules disabled. But we still have to return Array.
267
+ return self.__cache__.get(chainName, []) or []
268
+
269
+ def get_all_rules(self) -> list[str]:
270
+ """Return all available rule names."""
271
+ return [r.name for r in self.__rules__]
272
+
273
+ def get_active_rules(self) -> list[str]:
274
+ """Return the active rule names."""
275
+ return [r.name for r in self.__rules__ if r.enabled]
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = (
2
+ "StateBlock",
3
+ "blockquote",
4
+ "code",
5
+ "fence",
6
+ "heading",
7
+ "hr",
8
+ "html_block",
9
+ "lheading",
10
+ "list_block",
11
+ "paragraph",
12
+ "reference",
13
+ "table",
14
+ )
15
+
16
+ from .blockquote import blockquote
17
+ from .code import code
18
+ from .fence import fence
19
+ from .heading import heading
20
+ from .hr import hr
21
+ from .html_block import html_block
22
+ from .lheading import lheading
23
+ from .list import list_block
24
+ from .paragraph import paragraph
25
+ from .reference import reference
26
+ from .state_block import StateBlock
27
+ from .table import table
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/code.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Code block (4 spaces padded)."""
2
+
3
+ import logging
4
+
5
+ from .state_block import StateBlock
6
+
7
+ LOGGER = logging.getLogger(__name__)
8
+
9
+
10
+ def code(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
11
+ LOGGER.debug("entering code: %s, %s, %s, %s", state, startLine, endLine, silent)
12
+
13
+ if not state.is_code_block(startLine):
14
+ return False
15
+
16
+ last = nextLine = startLine + 1
17
+
18
+ while nextLine < endLine:
19
+ if state.isEmpty(nextLine):
20
+ nextLine += 1
21
+ continue
22
+
23
+ if state.is_code_block(nextLine):
24
+ nextLine += 1
25
+ last = nextLine
26
+ continue
27
+
28
+ break
29
+
30
+ state.line = last
31
+
32
+ token = state.push("code_block", "code", 0)
33
+ token.content = state.getLines(startLine, last, 4 + state.blkIndent, False) + "\n"
34
+ token.map = [startLine, state.line]
35
+
36
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/fence.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fences (``` lang, ~~~ lang)
2
+ import logging
3
+
4
+ from .state_block import StateBlock
5
+
6
+ LOGGER = logging.getLogger(__name__)
7
+
8
+
9
+ def fence(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
10
+ LOGGER.debug("entering fence: %s, %s, %s, %s", state, startLine, endLine, silent)
11
+
12
+ haveEndMarker = False
13
+ pos = state.bMarks[startLine] + state.tShift[startLine]
14
+ maximum = state.eMarks[startLine]
15
+
16
+ if state.is_code_block(startLine):
17
+ return False
18
+
19
+ if pos + 3 > maximum:
20
+ return False
21
+
22
+ marker = state.src[pos]
23
+
24
+ if marker not in ("~", "`"):
25
+ return False
26
+
27
+ # scan marker length
28
+ mem = pos
29
+ pos = state.skipCharsStr(pos, marker)
30
+
31
+ length = pos - mem
32
+
33
+ if length < 3:
34
+ return False
35
+
36
+ markup = state.src[mem:pos]
37
+ params = state.src[pos:maximum]
38
+
39
+ if marker == "`" and marker in params:
40
+ return False
41
+
42
+ # Since start is found, we can report success here in validation mode
43
+ if silent:
44
+ return True
45
+
46
+ # search end of block
47
+ nextLine = startLine
48
+
49
+ while True:
50
+ nextLine += 1
51
+ if nextLine >= endLine:
52
+ # unclosed block should be autoclosed by end of document.
53
+ # also block seems to be autoclosed by end of parent
54
+ break
55
+
56
+ pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]
57
+ maximum = state.eMarks[nextLine]
58
+
59
+ if pos < maximum and state.sCount[nextLine] < state.blkIndent:
60
+ # non-empty line with negative indent should stop the list:
61
+ # - ```
62
+ # test
63
+ break
64
+
65
+ try:
66
+ if state.src[pos] != marker:
67
+ continue
68
+ except IndexError:
69
+ break
70
+
71
+ if state.is_code_block(nextLine):
72
+ continue
73
+
74
+ pos = state.skipCharsStr(pos, marker)
75
+
76
+ # closing code fence must be at least as long as the opening one
77
+ if pos - mem < length:
78
+ continue
79
+
80
+ # make sure tail has spaces only
81
+ pos = state.skipSpaces(pos)
82
+
83
+ if pos < maximum:
84
+ continue
85
+
86
+ haveEndMarker = True
87
+ # found!
88
+ break
89
+
90
+ # If a fence has heading spaces, they should be removed from its inner block
91
+ length = state.sCount[startLine]
92
+
93
+ state.line = nextLine + (1 if haveEndMarker else 0)
94
+
95
+ token = state.push("fence", "code", 0)
96
+ token.info = params
97
+ token.content = state.getLines(startLine + 1, nextLine, length, True)
98
+ token.markup = markup
99
+ token.map = [startLine, state.line]
100
+
101
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/hr.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Horizontal rule
2
+
3
+ At least 3 of these characters on a line * - _
4
+ """
5
+
6
+ import logging
7
+
8
+ from ..common.utils import isStrSpace
9
+ from .state_block import StateBlock
10
+
11
+ LOGGER = logging.getLogger(__name__)
12
+
13
+
14
+ def hr(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
15
+ LOGGER.debug("entering hr: %s, %s, %s, %s", state, startLine, endLine, silent)
16
+
17
+ pos = state.bMarks[startLine] + state.tShift[startLine]
18
+ maximum = state.eMarks[startLine]
19
+
20
+ if state.is_code_block(startLine):
21
+ return False
22
+
23
+ try:
24
+ marker = state.src[pos]
25
+ except IndexError:
26
+ return False
27
+ pos += 1
28
+
29
+ # Check hr marker
30
+ if marker not in ("*", "-", "_"):
31
+ return False
32
+
33
+ # markers can be mixed with spaces, but there should be at least 3 of them
34
+
35
+ cnt = 1
36
+ while pos < maximum:
37
+ ch = state.src[pos]
38
+ pos += 1
39
+ if ch != marker and not isStrSpace(ch):
40
+ return False
41
+ if ch == marker:
42
+ cnt += 1
43
+
44
+ if cnt < 3:
45
+ return False
46
+
47
+ if silent:
48
+ return True
49
+
50
+ state.line = startLine + 1
51
+
52
+ token = state.push("hr", "hr", 0)
53
+ token.map = [startLine, state.line]
54
+ token.markup = marker * (cnt + 1)
55
+
56
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/lheading.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # lheading (---, ==)
2
+ import logging
3
+
4
+ from .state_block import StateBlock
5
+
6
+ LOGGER = logging.getLogger(__name__)
7
+
8
+
9
+ def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
10
+ LOGGER.debug("entering lheading: %s, %s, %s, %s", state, startLine, endLine, silent)
11
+
12
+ level = None
13
+ nextLine = startLine + 1
14
+ ruler = state.md.block.ruler
15
+ terminatorRules = ruler.getRules("paragraph")
16
+
17
+ if state.is_code_block(startLine):
18
+ return False
19
+
20
+ oldParentType = state.parentType
21
+ state.parentType = "paragraph" # use paragraph to match terminatorRules
22
+
23
+ # jump line-by-line until empty one or EOF
24
+ while nextLine < endLine and not state.isEmpty(nextLine):
25
+ # this would be a code block normally, but after paragraph
26
+ # it's considered a lazy continuation regardless of what's there
27
+ if state.sCount[nextLine] - state.blkIndent > 3:
28
+ nextLine += 1
29
+ continue
30
+
31
+ # Check for underline in setext header
32
+ if state.sCount[nextLine] >= state.blkIndent:
33
+ pos = state.bMarks[nextLine] + state.tShift[nextLine]
34
+ maximum = state.eMarks[nextLine]
35
+
36
+ if pos < maximum:
37
+ marker = state.src[pos]
38
+
39
+ if marker in ("-", "="):
40
+ pos = state.skipCharsStr(pos, marker)
41
+ pos = state.skipSpaces(pos)
42
+
43
+ # /* = */
44
+ if pos >= maximum:
45
+ level = 1 if marker == "=" else 2
46
+ break
47
+
48
+ # quirk for blockquotes, this line should already be checked by that rule
49
+ if state.sCount[nextLine] < 0:
50
+ nextLine += 1
51
+ continue
52
+
53
+ # Some tags can terminate paragraph without empty line.
54
+ terminate = False
55
+ for terminatorRule in terminatorRules:
56
+ if terminatorRule(state, nextLine, endLine, True):
57
+ terminate = True
58
+ break
59
+ if terminate:
60
+ break
61
+
62
+ nextLine += 1
63
+
64
+ if not level:
65
+ # Didn't find valid underline
66
+ return False
67
+
68
+ content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
69
+
70
+ state.line = nextLine + 1
71
+
72
+ token = state.push("heading_open", "h" + str(level), 1)
73
+ token.markup = marker
74
+ token.map = [startLine, state.line]
75
+
76
+ token = state.push("inline", "", 0)
77
+ token.content = content
78
+ token.map = [startLine, state.line - 1]
79
+ token.children = []
80
+
81
+ token = state.push("heading_close", "h" + str(level), -1)
82
+ token.markup = marker
83
+
84
+ state.parentType = oldParentType
85
+
86
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/list.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lists
2
+ import logging
3
+
4
+ from ..common.utils import isStrSpace
5
+ from .state_block import StateBlock
6
+
7
+ LOGGER = logging.getLogger(__name__)
8
+
9
+
10
+ # Search `[-+*][\n ]`, returns next pos after marker on success
11
+ # or -1 on fail.
12
+ def skipBulletListMarker(state: StateBlock, startLine: int) -> int:
13
+ pos = state.bMarks[startLine] + state.tShift[startLine]
14
+ maximum = state.eMarks[startLine]
15
+
16
+ try:
17
+ marker = state.src[pos]
18
+ except IndexError:
19
+ return -1
20
+ pos += 1
21
+
22
+ if marker not in ("*", "-", "+"):
23
+ return -1
24
+
25
+ if pos < maximum:
26
+ ch = state.src[pos]
27
+
28
+ if not isStrSpace(ch):
29
+ # " -test " - is not a list item
30
+ return -1
31
+
32
+ return pos
33
+
34
+
35
+ # Search `\d+[.)][\n ]`, returns next pos after marker on success
36
+ # or -1 on fail.
37
+ def skipOrderedListMarker(state: StateBlock, startLine: int) -> int:
38
+ start = state.bMarks[startLine] + state.tShift[startLine]
39
+ pos = start
40
+ maximum = state.eMarks[startLine]
41
+
42
+ # List marker should have at least 2 chars (digit + dot)
43
+ if pos + 1 >= maximum:
44
+ return -1
45
+
46
+ ch = state.src[pos]
47
+ pos += 1
48
+
49
+ ch_ord = ord(ch)
50
+ # /* 0 */ /* 9 */
51
+ if ch_ord < 0x30 or ch_ord > 0x39:
52
+ return -1
53
+
54
+ while True:
55
+ # EOL -> fail
56
+ if pos >= maximum:
57
+ return -1
58
+
59
+ ch = state.src[pos]
60
+ pos += 1
61
+
62
+ # /* 0 */ /* 9 */
63
+ ch_ord = ord(ch)
64
+ if ch_ord >= 0x30 and ch_ord <= 0x39:
65
+ # List marker should have no more than 9 digits
66
+ # (prevents integer overflow in browsers)
67
+ if pos - start >= 10:
68
+ return -1
69
+
70
+ continue
71
+
72
+ # found valid marker
73
+ if ch in (")", "."):
74
+ break
75
+
76
+ return -1
77
+
78
+ if pos < maximum:
79
+ ch = state.src[pos]
80
+
81
+ if not isStrSpace(ch):
82
+ # " 1.test " - is not a list item
83
+ return -1
84
+
85
+ return pos
86
+
87
+
88
+ def markTightParagraphs(state: StateBlock, idx: int) -> None:
89
+ level = state.level + 2
90
+
91
+ i = idx + 2
92
+ length = len(state.tokens) - 2
93
+ while i < length:
94
+ if state.tokens[i].level == level and state.tokens[i].type == "paragraph_open":
95
+ state.tokens[i + 2].hidden = True
96
+ state.tokens[i].hidden = True
97
+ i += 2
98
+ i += 1
99
+
100
+
101
+ def list_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
102
+ LOGGER.debug("entering list: %s, %s, %s, %s", state, startLine, endLine, silent)
103
+
104
+ isTerminatingParagraph = False
105
+ tight = True
106
+
107
+ if state.is_code_block(startLine):
108
+ return False
109
+
110
+ # Special case:
111
+ # - item 1
112
+ # - item 2
113
+ # - item 3
114
+ # - item 4
115
+ # - this one is a paragraph continuation
116
+ if (
117
+ state.listIndent >= 0
118
+ and state.sCount[startLine] - state.listIndent >= 4
119
+ and state.sCount[startLine] < state.blkIndent
120
+ ):
121
+ return False
122
+
123
+ # limit conditions when list can interrupt
124
+ # a paragraph (validation mode only)
125
+ # Next list item should still terminate previous list item
126
+ #
127
+ # This code can fail if plugins use blkIndent as well as lists,
128
+ # but I hope the spec gets fixed long before that happens.
129
+ #
130
+ if (
131
+ silent
132
+ and state.parentType == "paragraph"
133
+ and state.sCount[startLine] >= state.blkIndent
134
+ ):
135
+ isTerminatingParagraph = True
136
+
137
+ # Detect list type and position after marker
138
+ posAfterMarker = skipOrderedListMarker(state, startLine)
139
+ if posAfterMarker >= 0:
140
+ isOrdered = True
141
+ start = state.bMarks[startLine] + state.tShift[startLine]
142
+ markerValue = int(state.src[start : posAfterMarker - 1])
143
+
144
+ # If we're starting a new ordered list right after
145
+ # a paragraph, it should start with 1.
146
+ if isTerminatingParagraph and markerValue != 1:
147
+ return False
148
+ else:
149
+ posAfterMarker = skipBulletListMarker(state, startLine)
150
+ if posAfterMarker >= 0:
151
+ isOrdered = False
152
+ else:
153
+ return False
154
+
155
+ # If we're starting a new unordered list right after
156
+ # a paragraph, first line should not be empty.
157
+ if (
158
+ isTerminatingParagraph
159
+ and state.skipSpaces(posAfterMarker) >= state.eMarks[startLine]
160
+ ):
161
+ return False
162
+
163
+ # We should terminate list on style change. Remember first one to compare.
164
+ markerChar = state.src[posAfterMarker - 1]
165
+
166
+ # For validation mode we can terminate immediately
167
+ if silent:
168
+ return True
169
+
170
+ # Start list
171
+ listTokIdx = len(state.tokens)
172
+
173
+ if isOrdered:
174
+ token = state.push("ordered_list_open", "ol", 1)
175
+ if markerValue != 1:
176
+ token.attrs = {"start": markerValue}
177
+
178
+ else:
179
+ token = state.push("bullet_list_open", "ul", 1)
180
+
181
+ token.map = listLines = [startLine, 0]
182
+ token.markup = markerChar
183
+
184
+ #
185
+ # Iterate list items
186
+ #
187
+
188
+ nextLine = startLine
189
+ prevEmptyEnd = False
190
+ terminatorRules = state.md.block.ruler.getRules("list")
191
+
192
+ oldParentType = state.parentType
193
+ state.parentType = "list"
194
+
195
+ while nextLine < endLine:
196
+ pos = posAfterMarker
197
+ maximum = state.eMarks[nextLine]
198
+
199
+ initial = offset = (
200
+ state.sCount[nextLine]
201
+ + posAfterMarker
202
+ - (state.bMarks[startLine] + state.tShift[startLine])
203
+ )
204
+
205
+ while pos < maximum:
206
+ ch = state.src[pos]
207
+
208
+ if ch == "\t":
209
+ offset += 4 - (offset + state.bsCount[nextLine]) % 4
210
+ elif ch == " ":
211
+ offset += 1
212
+ else:
213
+ break
214
+
215
+ pos += 1
216
+
217
+ contentStart = pos
218
+
219
+ # trimming space in "- \n 3" case, indent is 1 here
220
+ indentAfterMarker = 1 if contentStart >= maximum else offset - initial
221
+
222
+ # If we have more than 4 spaces, the indent is 1
223
+ # (the rest is just indented code block)
224
+ if indentAfterMarker > 4:
225
+ indentAfterMarker = 1
226
+
227
+ # " - test"
228
+ # ^^^^^ - calculating total length of this thing
229
+ indent = initial + indentAfterMarker
230
+
231
+ # Run subparser & write tokens
232
+ token = state.push("list_item_open", "li", 1)
233
+ token.markup = markerChar
234
+ token.map = itemLines = [startLine, 0]
235
+ if isOrdered:
236
+ token.info = state.src[start : posAfterMarker - 1]
237
+
238
+ # change current state, then restore it after parser subcall
239
+ oldTight = state.tight
240
+ oldTShift = state.tShift[startLine]
241
+ oldSCount = state.sCount[startLine]
242
+
243
+ # - example list
244
+ # ^ listIndent position will be here
245
+ # ^ blkIndent position will be here
246
+ #
247
+ oldListIndent = state.listIndent
248
+ state.listIndent = state.blkIndent
249
+ state.blkIndent = indent
250
+
251
+ state.tight = True
252
+ state.tShift[startLine] = contentStart - state.bMarks[startLine]
253
+ state.sCount[startLine] = offset
254
+
255
+ if contentStart >= maximum and state.isEmpty(startLine + 1):
256
+ # workaround for this case
257
+ # (list item is empty, list terminates before "foo"):
258
+ # ~~~~~~~~
259
+ # -
260
+ #
261
+ # foo
262
+ # ~~~~~~~~
263
+ state.line = min(state.line + 2, endLine)
264
+ else:
265
+ # NOTE in list.js this was:
266
+ # state.md.block.tokenize(state, startLine, endLine, True)
267
+ # but tokeniz does not take the final parameter
268
+ state.md.block.tokenize(state, startLine, endLine)
269
+
270
+ # If any of list item is tight, mark list as tight
271
+ if (not state.tight) or prevEmptyEnd:
272
+ tight = False
273
+
274
+ # Item become loose if finish with empty line,
275
+ # but we should filter last element, because it means list finish
276
+ prevEmptyEnd = (state.line - startLine) > 1 and state.isEmpty(state.line - 1)
277
+
278
+ state.blkIndent = state.listIndent
279
+ state.listIndent = oldListIndent
280
+ state.tShift[startLine] = oldTShift
281
+ state.sCount[startLine] = oldSCount
282
+ state.tight = oldTight
283
+
284
+ token = state.push("list_item_close", "li", -1)
285
+ token.markup = markerChar
286
+
287
+ nextLine = startLine = state.line
288
+ itemLines[1] = nextLine
289
+
290
+ if nextLine >= endLine:
291
+ break
292
+
293
+ contentStart = state.bMarks[startLine]
294
+
295
+ #
296
+ # Try to check if list is terminated or continued.
297
+ #
298
+ if state.sCount[nextLine] < state.blkIndent:
299
+ break
300
+
301
+ if state.is_code_block(startLine):
302
+ break
303
+
304
+ # fail if terminating block found
305
+ terminate = False
306
+ for terminatorRule in terminatorRules:
307
+ if terminatorRule(state, nextLine, endLine, True):
308
+ terminate = True
309
+ break
310
+
311
+ if terminate:
312
+ break
313
+
314
+ # fail if list has another type
315
+ if isOrdered:
316
+ posAfterMarker = skipOrderedListMarker(state, nextLine)
317
+ if posAfterMarker < 0:
318
+ break
319
+ start = state.bMarks[nextLine] + state.tShift[nextLine]
320
+ else:
321
+ posAfterMarker = skipBulletListMarker(state, nextLine)
322
+ if posAfterMarker < 0:
323
+ break
324
+
325
+ if markerChar != state.src[posAfterMarker - 1]:
326
+ break
327
+
328
+ # Finalize list
329
+ if isOrdered:
330
+ token = state.push("ordered_list_close", "ol", -1)
331
+ else:
332
+ token = state.push("bullet_list_close", "ul", -1)
333
+
334
+ token.markup = markerChar
335
+
336
+ listLines[1] = nextLine
337
+ state.line = nextLine
338
+
339
+ state.parentType = oldParentType
340
+
341
+ # mark paragraphs tight if needed
342
+ if tight:
343
+ markTightParagraphs(state, listTokIdx)
344
+
345
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/paragraph.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paragraph."""
2
+
3
+ import logging
4
+
5
+ from .state_block import StateBlock
6
+
7
+ LOGGER = logging.getLogger(__name__)
8
+
9
+
10
+ def paragraph(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
11
+ LOGGER.debug(
12
+ "entering paragraph: %s, %s, %s, %s", state, startLine, endLine, silent
13
+ )
14
+
15
+ nextLine = startLine + 1
16
+ ruler = state.md.block.ruler
17
+ terminatorRules = ruler.getRules("paragraph")
18
+ endLine = state.lineMax
19
+
20
+ oldParentType = state.parentType
21
+ state.parentType = "paragraph"
22
+
23
+ # jump line-by-line until empty one or EOF
24
+ while nextLine < endLine:
25
+ if state.isEmpty(nextLine):
26
+ break
27
+ # this would be a code block normally, but after paragraph
28
+ # it's considered a lazy continuation regardless of what's there
29
+ if state.sCount[nextLine] - state.blkIndent > 3:
30
+ nextLine += 1
31
+ continue
32
+
33
+ # quirk for blockquotes, this line should already be checked by that rule
34
+ if state.sCount[nextLine] < 0:
35
+ nextLine += 1
36
+ continue
37
+
38
+ # Some tags can terminate paragraph without empty line.
39
+ terminate = False
40
+ for terminatorRule in terminatorRules:
41
+ if terminatorRule(state, nextLine, endLine, True):
42
+ terminate = True
43
+ break
44
+
45
+ if terminate:
46
+ break
47
+
48
+ nextLine += 1
49
+
50
+ content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
51
+
52
+ state.line = nextLine
53
+
54
+ token = state.push("paragraph_open", "p", 1)
55
+ token.map = [startLine, state.line]
56
+
57
+ token = state.push("inline", "", 0)
58
+ token.content = content
59
+ token.map = [startLine, state.line]
60
+ token.children = []
61
+
62
+ token = state.push("paragraph_close", "p", -1)
63
+
64
+ state.parentType = oldParentType
65
+
66
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = (
2
+ "StateCore",
3
+ "block",
4
+ "inline",
5
+ "linkify",
6
+ "normalize",
7
+ "replace",
8
+ "smartquotes",
9
+ "text_join",
10
+ )
11
+
12
+ from .block import block
13
+ from .inline import inline
14
+ from .linkify import linkify
15
+ from .normalize import normalize
16
+ from .replacements import replace
17
+ from .smartquotes import smartquotes
18
+ from .state_core import StateCore
19
+ from .text_join import text_join
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/linkify.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import Protocol
5
+
6
+ from ..common.utils import arrayReplaceAt, isLinkClose, isLinkOpen
7
+ from ..token import Token
8
+ from .state_core import StateCore
9
+
10
+ HTTP_RE = re.compile(r"^http://")
11
+ MAILTO_RE = re.compile(r"^mailto:")
12
+ TEST_MAILTO_RE = re.compile(r"^mailto:", flags=re.IGNORECASE)
13
+
14
+
15
+ def linkify(state: StateCore) -> None:
16
+ """Rule for identifying plain-text links."""
17
+ if not state.md.options.linkify:
18
+ return
19
+
20
+ if not state.md.linkify:
21
+ raise ModuleNotFoundError("Linkify enabled but not installed.")
22
+
23
+ for inline_token in state.tokens:
24
+ if inline_token.type != "inline" or not state.md.linkify.pretest(
25
+ inline_token.content
26
+ ):
27
+ continue
28
+
29
+ tokens = inline_token.children
30
+
31
+ htmlLinkLevel = 0
32
+
33
+ # We scan from the end, to keep position when new tags added.
34
+ # Use reversed logic in links start/end match
35
+ assert tokens is not None
36
+ i = len(tokens)
37
+ while i >= 1:
38
+ i -= 1
39
+ assert isinstance(tokens, list)
40
+ currentToken = tokens[i]
41
+
42
+ # Skip content of markdown links
43
+ if currentToken.type == "link_close":
44
+ i -= 1
45
+ while (
46
+ tokens[i].level != currentToken.level
47
+ and tokens[i].type != "link_open"
48
+ ):
49
+ i -= 1
50
+ continue
51
+
52
+ # Skip content of html tag links
53
+ if currentToken.type == "html_inline":
54
+ if isLinkOpen(currentToken.content) and htmlLinkLevel > 0:
55
+ htmlLinkLevel -= 1
56
+ if isLinkClose(currentToken.content):
57
+ htmlLinkLevel += 1
58
+ if htmlLinkLevel > 0:
59
+ continue
60
+
61
+ if currentToken.type == "text" and state.md.linkify.test(
62
+ currentToken.content
63
+ ):
64
+ text = currentToken.content
65
+ links: list[_LinkType] = state.md.linkify.match(text) or []
66
+
67
+ # Now split string to nodes
68
+ nodes = []
69
+ level = currentToken.level
70
+ lastPos = 0
71
+
72
+ # forbid escape sequence at the start of the string,
73
+ # this avoids http\://example.com/ from being linkified as
74
+ # http:<a href="//example.com/">//example.com/</a>
75
+ if (
76
+ links
77
+ and links[0].index == 0
78
+ and i > 0
79
+ and tokens[i - 1].type == "text_special"
80
+ ):
81
+ links = links[1:]
82
+
83
+ for link in links:
84
+ url = link.url
85
+ fullUrl = state.md.normalizeLink(url)
86
+ if not state.md.validateLink(fullUrl):
87
+ continue
88
+
89
+ urlText = link.text
90
+
91
+ # Linkifier might send raw hostnames like "example.com", where url
92
+ # starts with domain name. So we prepend http:// in those cases,
93
+ # and remove it afterwards.
94
+ if not link.schema:
95
+ urlText = HTTP_RE.sub(
96
+ "", state.md.normalizeLinkText("http://" + urlText)
97
+ )
98
+ elif link.schema == "mailto:" and TEST_MAILTO_RE.search(urlText):
99
+ urlText = MAILTO_RE.sub(
100
+ "", state.md.normalizeLinkText("mailto:" + urlText)
101
+ )
102
+ else:
103
+ urlText = state.md.normalizeLinkText(urlText)
104
+
105
+ pos = link.index
106
+
107
+ if pos > lastPos:
108
+ token = Token("text", "", 0)
109
+ token.content = text[lastPos:pos]
110
+ token.level = level
111
+ nodes.append(token)
112
+
113
+ token = Token("link_open", "a", 1)
114
+ token.attrs = {"href": fullUrl}
115
+ token.level = level
116
+ level += 1
117
+ token.markup = "linkify"
118
+ token.info = "auto"
119
+ nodes.append(token)
120
+
121
+ token = Token("text", "", 0)
122
+ token.content = urlText
123
+ token.level = level
124
+ nodes.append(token)
125
+
126
+ token = Token("link_close", "a", -1)
127
+ level -= 1
128
+ token.level = level
129
+ token.markup = "linkify"
130
+ token.info = "auto"
131
+ nodes.append(token)
132
+
133
+ lastPos = link.last_index
134
+
135
+ if lastPos < len(text):
136
+ token = Token("text", "", 0)
137
+ token.content = text[lastPos:]
138
+ token.level = level
139
+ nodes.append(token)
140
+
141
+ inline_token.children = tokens = arrayReplaceAt(tokens, i, nodes)
142
+
143
+
144
+ class _LinkType(Protocol):
145
+ url: str
146
+ text: str
147
+ index: int
148
+ last_index: int
149
+ schema: str | None
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/normalize.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Normalize input string."""
2
+
3
+ import re
4
+
5
+ from .state_core import StateCore
6
+
7
+ # https://spec.commonmark.org/0.29/#line-ending
8
+ NEWLINES_RE = re.compile(r"\r\n?|\n")
9
+ NULL_RE = re.compile(r"\0")
10
+
11
+
12
+ def normalize(state: StateCore) -> None:
13
+ # Normalize newlines
14
+ string = NEWLINES_RE.sub("\n", state.src)
15
+
16
+ # Replace NULL characters
17
+ string = NULL_RE.sub("\ufffd", string)
18
+
19
+ state.src = string
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/text_join.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Join raw text tokens with the rest of the text
2
+
3
+ This is set as a separate rule to provide an opportunity for plugins
4
+ to run text replacements after text join, but before escape join.
5
+
6
+ For example, `\\:)` shouldn't be replaced with an emoji.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from ..token import Token
12
+ from .state_core import StateCore
13
+
14
+
15
+ def text_join(state: StateCore) -> None:
16
+ """Join raw text for escape sequences (`text_special`) tokens with the rest of the text"""
17
+
18
+ for inline_token in state.tokens[:]:
19
+ if inline_token.type != "inline":
20
+ continue
21
+
22
+ # convert text_special to text and join all adjacent text nodes
23
+ new_tokens: list[Token] = []
24
+ for child_token in inline_token.children or []:
25
+ if child_token.type == "text_special":
26
+ child_token.type = "text"
27
+ if (
28
+ child_token.type == "text"
29
+ and new_tokens
30
+ and new_tokens[-1].type == "text"
31
+ ):
32
+ new_tokens[-1].content += child_token.content
33
+ else:
34
+ new_tokens.append(child_token)
35
+ inline_token.children = new_tokens
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/backticks.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Parse backticks
2
+ import re
3
+
4
+ from .state_inline import StateInline
5
+
6
+ regex = re.compile("^ (.+) $")
7
+
8
+
9
+ def backtick(state: StateInline, silent: bool) -> bool:
10
+ pos = state.pos
11
+
12
+ if state.src[pos] != "`":
13
+ return False
14
+
15
+ start = pos
16
+ pos += 1
17
+ maximum = state.posMax
18
+
19
+ # scan marker length
20
+ while pos < maximum and (state.src[pos] == "`"):
21
+ pos += 1
22
+
23
+ marker = state.src[start:pos]
24
+ openerLength = len(marker)
25
+
26
+ if state.backticksScanned and state.backticks.get(openerLength, 0) <= start:
27
+ if not silent:
28
+ state.pending += marker
29
+ state.pos += openerLength
30
+ return True
31
+
32
+ matchStart = matchEnd = pos
33
+
34
+ # Nothing found in the cache, scan until the end of the line (or until marker is found)
35
+ while True:
36
+ try:
37
+ matchStart = state.src.index("`", matchEnd)
38
+ except ValueError:
39
+ break
40
+ matchEnd = matchStart + 1
41
+
42
+ # scan marker length
43
+ while matchEnd < maximum and (state.src[matchEnd] == "`"):
44
+ matchEnd += 1
45
+
46
+ closerLength = matchEnd - matchStart
47
+
48
+ if closerLength == openerLength:
49
+ # Found matching closer length.
50
+ if not silent:
51
+ token = state.push("code_inline", "code", 0)
52
+ token.markup = marker
53
+ token.content = state.src[pos:matchStart].replace("\n", " ")
54
+ if (
55
+ token.content.startswith(" ")
56
+ and token.content.endswith(" ")
57
+ and len(token.content.strip()) > 0
58
+ ):
59
+ token.content = token.content[1:-1]
60
+ state.pos = matchEnd
61
+ return True
62
+
63
+ # Some different length found, put it in cache as upper limit of where closer can be found
64
+ state.backticks[closerLength] = matchStart
65
+
66
+ # Scanned through the end, didn't find anything
67
+ state.backticksScanned = True
68
+
69
+ if not silent:
70
+ state.pending += marker
71
+ state.pos += openerLength
72
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/balance_pairs.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Balance paired characters (*, _, etc) in inline tokens."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .state_inline import Delimiter, StateInline
6
+
7
+
8
+ def processDelimiters(state: StateInline, delimiters: list[Delimiter]) -> None:
9
+ """For each opening emphasis-like marker find a matching closing one."""
10
+ if not delimiters:
11
+ return
12
+
13
+ openersBottom = {}
14
+ maximum = len(delimiters)
15
+
16
+ # headerIdx is the first delimiter of the current (where closer is) delimiter run
17
+ headerIdx = 0
18
+ lastTokenIdx = -2 # needs any value lower than -1
19
+ jumps: list[int] = []
20
+ closerIdx = 0
21
+ while closerIdx < maximum:
22
+ closer = delimiters[closerIdx]
23
+
24
+ jumps.append(0)
25
+
26
+ # markers belong to same delimiter run if:
27
+ # - they have adjacent tokens
28
+ # - AND markers are the same
29
+ #
30
+ if (
31
+ delimiters[headerIdx].marker != closer.marker
32
+ or lastTokenIdx != closer.token - 1
33
+ ):
34
+ headerIdx = closerIdx
35
+ lastTokenIdx = closer.token
36
+
37
+ # Length is only used for emphasis-specific "rule of 3",
38
+ # if it's not defined (in strikethrough or 3rd party plugins),
39
+ # we can default it to 0 to disable those checks.
40
+ #
41
+ closer.length = closer.length or 0
42
+
43
+ if not closer.close:
44
+ closerIdx += 1
45
+ continue
46
+
47
+ # Previously calculated lower bounds (previous fails)
48
+ # for each marker, each delimiter length modulo 3,
49
+ # and for whether this closer can be an opener;
50
+ # https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460
51
+ if closer.marker not in openersBottom:
52
+ openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]
53
+
54
+ minOpenerIdx = openersBottom[closer.marker][
55
+ (3 if closer.open else 0) + (closer.length % 3)
56
+ ]
57
+
58
+ openerIdx = headerIdx - jumps[headerIdx] - 1
59
+
60
+ newMinOpenerIdx = openerIdx
61
+
62
+ while openerIdx > minOpenerIdx:
63
+ opener = delimiters[openerIdx]
64
+
65
+ if opener.marker != closer.marker:
66
+ openerIdx -= jumps[openerIdx] + 1
67
+ continue
68
+
69
+ if opener.open and opener.end < 0:
70
+ isOddMatch = False
71
+
72
+ # from spec:
73
+ #
74
+ # If one of the delimiters can both open and close emphasis, then the
75
+ # sum of the lengths of the delimiter runs containing the opening and
76
+ # closing delimiters must not be a multiple of 3 unless both lengths
77
+ # are multiples of 3.
78
+ #
79
+ if (
80
+ (opener.close or closer.open)
81
+ and ((opener.length + closer.length) % 3 == 0)
82
+ and (opener.length % 3 != 0 or closer.length % 3 != 0)
83
+ ):
84
+ isOddMatch = True
85
+
86
+ if not isOddMatch:
87
+ # If previous delimiter cannot be an opener, we can safely skip
88
+ # the entire sequence in future checks. This is required to make
89
+ # sure algorithm has linear complexity (see *_*_*_*_*_... case).
90
+ #
91
+ if openerIdx > 0 and not delimiters[openerIdx - 1].open:
92
+ lastJump = jumps[openerIdx - 1] + 1
93
+ else:
94
+ lastJump = 0
95
+
96
+ jumps[closerIdx] = closerIdx - openerIdx + lastJump
97
+ jumps[openerIdx] = lastJump
98
+
99
+ closer.open = False
100
+ opener.end = closerIdx
101
+ opener.close = False
102
+ newMinOpenerIdx = -1
103
+
104
+ # treat next token as start of run,
105
+ # it optimizes skips in **<...>**a**<...>** pathological case
106
+ lastTokenIdx = -2
107
+
108
+ break
109
+
110
+ openerIdx -= jumps[openerIdx] + 1
111
+
112
+ if newMinOpenerIdx != -1:
113
+ # If match for this delimiter run failed, we want to set lower bound for
114
+ # future lookups. This is required to make sure algorithm has linear
115
+ # complexity.
116
+ #
117
+ # See details here:
118
+ # https:#github.com/commonmark/cmark/issues/178#issuecomment-270417442
119
+ #
120
+ openersBottom[closer.marker][
121
+ (3 if closer.open else 0) + ((closer.length or 0) % 3)
122
+ ] = newMinOpenerIdx
123
+
124
+ closerIdx += 1
125
+
126
+
127
+ def link_pairs(state: StateInline) -> None:
128
+ tokens_meta = state.tokens_meta
129
+ maximum = len(state.tokens_meta)
130
+
131
+ processDelimiters(state, state.delimiters)
132
+
133
+ curr = 0
134
+ while curr < maximum:
135
+ curr_meta = tokens_meta[curr]
136
+ if curr_meta and "delimiters" in curr_meta:
137
+ processDelimiters(state, curr_meta["delimiters"])
138
+ curr += 1
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/emphasis.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Process *this* and _that_
2
+ #
3
+ from __future__ import annotations
4
+
5
+ from .state_inline import Delimiter, StateInline
6
+
7
+
8
+ def tokenize(state: StateInline, silent: bool) -> bool:
9
+ """Insert each marker as a separate text token, and add it to delimiter list"""
10
+ start = state.pos
11
+ marker = state.src[start]
12
+
13
+ if silent:
14
+ return False
15
+
16
+ if marker not in ("_", "*"):
17
+ return False
18
+
19
+ scanned = state.scanDelims(state.pos, marker == "*")
20
+
21
+ for _ in range(scanned.length):
22
+ token = state.push("text", "", 0)
23
+ token.content = marker
24
+ state.delimiters.append(
25
+ Delimiter(
26
+ marker=ord(marker),
27
+ length=scanned.length,
28
+ token=len(state.tokens) - 1,
29
+ end=-1,
30
+ open=scanned.can_open,
31
+ close=scanned.can_close,
32
+ )
33
+ )
34
+
35
+ state.pos += scanned.length
36
+
37
+ return True
38
+
39
+
40
+ def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None:
41
+ i = len(delimiters) - 1
42
+ while i >= 0:
43
+ startDelim = delimiters[i]
44
+
45
+ # /* _ */ /* * */
46
+ if startDelim.marker != 0x5F and startDelim.marker != 0x2A:
47
+ i -= 1
48
+ continue
49
+
50
+ # Process only opening markers
51
+ if startDelim.end == -1:
52
+ i -= 1
53
+ continue
54
+
55
+ endDelim = delimiters[startDelim.end]
56
+
57
+ # If the previous delimiter has the same marker and is adjacent to this one,
58
+ # merge those into one strong delimiter.
59
+ #
60
+ # `<em><em>whatever</em></em>` -> `<strong>whatever</strong>`
61
+ #
62
+ isStrong = (
63
+ i > 0
64
+ and delimiters[i - 1].end == startDelim.end + 1
65
+ # check that first two markers match and adjacent
66
+ and delimiters[i - 1].marker == startDelim.marker
67
+ and delimiters[i - 1].token == startDelim.token - 1
68
+ # check that last two markers are adjacent (we can safely assume they match)
69
+ and delimiters[startDelim.end + 1].token == endDelim.token + 1
70
+ )
71
+
72
+ ch = chr(startDelim.marker)
73
+
74
+ token = state.tokens[startDelim.token]
75
+ token.type = "strong_open" if isStrong else "em_open"
76
+ token.tag = "strong" if isStrong else "em"
77
+ token.nesting = 1
78
+ token.markup = ch + ch if isStrong else ch
79
+ token.content = ""
80
+
81
+ token = state.tokens[endDelim.token]
82
+ token.type = "strong_close" if isStrong else "em_close"
83
+ token.tag = "strong" if isStrong else "em"
84
+ token.nesting = -1
85
+ token.markup = ch + ch if isStrong else ch
86
+ token.content = ""
87
+
88
+ if isStrong:
89
+ state.tokens[delimiters[i - 1].token].content = ""
90
+ state.tokens[delimiters[startDelim.end + 1].token].content = ""
91
+ i -= 1
92
+
93
+ i -= 1
94
+
95
+
96
+ def postProcess(state: StateInline) -> None:
97
+ """Walk through delimiter list and replace text tokens with tags."""
98
+ _postProcess(state, state.delimiters)
99
+
100
+ for token in state.tokens_meta:
101
+ if token and "delimiters" in token:
102
+ _postProcess(state, token["delimiters"])
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/linkify.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Process links like https://example.org/"""
2
+
3
+ import re
4
+
5
+ from .state_inline import StateInline
6
+
7
+ # RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
8
+ SCHEME_RE = re.compile(r"(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$", re.IGNORECASE)
9
+
10
+
11
+ def linkify(state: StateInline, silent: bool) -> bool:
12
+ """Rule for identifying plain-text links."""
13
+ if not state.md.options.linkify:
14
+ return False
15
+ if state.linkLevel > 0:
16
+ return False
17
+ if not state.md.linkify:
18
+ raise ModuleNotFoundError("Linkify enabled but not installed.")
19
+
20
+ pos = state.pos
21
+ maximum = state.posMax
22
+
23
+ if (
24
+ (pos + 3) > maximum
25
+ or state.src[pos] != ":"
26
+ or state.src[pos + 1] != "/"
27
+ or state.src[pos + 2] != "/"
28
+ ):
29
+ return False
30
+
31
+ if not (match := SCHEME_RE.search(state.pending)):
32
+ return False
33
+
34
+ proto = match.group(1)
35
+ if not (link := state.md.linkify.match_at_start(state.src[pos - len(proto) :])):
36
+ return False
37
+ url: str = link.url
38
+
39
+ # disallow '*' at the end of the link (conflicts with emphasis)
40
+ url = url.rstrip("*")
41
+
42
+ full_url = state.md.normalizeLink(url)
43
+ if not state.md.validateLink(full_url):
44
+ return False
45
+
46
+ if not silent:
47
+ state.pending = state.pending[: -len(proto)]
48
+
49
+ token = state.push("link_open", "a", 1)
50
+ token.attrs = {"href": full_url}
51
+ token.markup = "linkify"
52
+ token.info = "auto"
53
+
54
+ token = state.push("text", "", 0)
55
+ token.content = state.md.normalizeLinkText(url)
56
+
57
+ token = state.push("link_close", "a", -1)
58
+ token.markup = "linkify"
59
+ token.info = "auto"
60
+
61
+ state.pos += len(url) - len(proto)
62
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/newline.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Proceess '\n'."""
2
+
3
+ from ..common.utils import charStrAt, isStrSpace
4
+ from .state_inline import StateInline
5
+
6
+
7
+ def newline(state: StateInline, silent: bool) -> bool:
8
+ pos = state.pos
9
+
10
+ if state.src[pos] != "\n":
11
+ return False
12
+
13
+ pmax = len(state.pending) - 1
14
+ maximum = state.posMax
15
+
16
+ # ' \n' -> hardbreak
17
+ # Lookup in pending chars is bad practice! Don't copy to other rules!
18
+ # Pending string is stored in concat mode, indexed lookups will cause
19
+ # conversion to flat mode.
20
+ if not silent:
21
+ if pmax >= 0 and charStrAt(state.pending, pmax) == " ":
22
+ if pmax >= 1 and charStrAt(state.pending, pmax - 1) == " ":
23
+ # Find whitespaces tail of pending chars.
24
+ ws = pmax - 1
25
+ while ws >= 1 and charStrAt(state.pending, ws - 1) == " ":
26
+ ws -= 1
27
+ state.pending = state.pending[:ws]
28
+
29
+ state.push("hardbreak", "br", 0)
30
+ else:
31
+ state.pending = state.pending[:-1]
32
+ state.push("softbreak", "br", 0)
33
+
34
+ else:
35
+ state.push("softbreak", "br", 0)
36
+
37
+ pos += 1
38
+
39
+ # skip heading spaces for next line
40
+ while pos < maximum and isStrSpace(state.src[pos]):
41
+ pos += 1
42
+
43
+ state.pos = pos
44
+ return True
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/token.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, MutableMapping
4
+ import dataclasses as dc
5
+ from typing import Any, Literal
6
+ import warnings
7
+
8
+
9
+ def convert_attrs(value: Any) -> Any:
10
+ """Convert Token.attrs set as ``None`` or ``[[key, value], ...]`` to a dict.
11
+
12
+ This improves compatibility with upstream markdown-it.
13
+ """
14
+ if not value:
15
+ return {}
16
+ if isinstance(value, list):
17
+ return dict(value)
18
+ return value
19
+
20
+
21
+ @dc.dataclass(slots=True)
22
+ class Token:
23
+ type: str
24
+ """Type of the token (string, e.g. "paragraph_open")"""
25
+
26
+ tag: str
27
+ """HTML tag name, e.g. 'p'"""
28
+
29
+ nesting: Literal[-1, 0, 1]
30
+ """Level change (number in {-1, 0, 1} set), where:
31
+ - `1` means the tag is opening
32
+ - `0` means the tag is self-closing
33
+ - `-1` means the tag is closing
34
+ """
35
+
36
+ attrs: dict[str, str | int | float] = dc.field(default_factory=dict)
37
+ """HTML attributes.
38
+ Note this differs from the upstream "list of lists" format,
39
+ although than an instance can still be initialised with this format.
40
+ """
41
+
42
+ map: list[int] | None = None
43
+ """Source map info. Format: `[ line_begin, line_end ]`"""
44
+
45
+ level: int = 0
46
+ """Nesting level, the same as `state.level`"""
47
+
48
+ children: list[Token] | None = None
49
+ """Array of child nodes (inline and img tokens)."""
50
+
51
+ content: str = ""
52
+ """Inner content, in the case of a self-closing tag (code, html, fence, etc.),"""
53
+
54
+ markup: str = ""
55
+ """'*' or '_' for emphasis, fence string for fence, etc."""
56
+
57
+ info: str = ""
58
+ """Additional information:
59
+ - Info string for "fence" tokens
60
+ - The value "auto" for autolink "link_open" and "link_close" tokens
61
+ - The string value of the item marker for ordered-list "list_item_open" tokens
62
+ """
63
+
64
+ meta: dict[Any, Any] = dc.field(default_factory=dict)
65
+ """A place for plugins to store any arbitrary data"""
66
+
67
+ block: bool = False
68
+ """True for block-level tokens, false for inline tokens.
69
+ Used in renderer to calculate line breaks
70
+ """
71
+
72
+ hidden: bool = False
73
+ """If true, ignore this element when rendering.
74
+ Used for tight lists to hide paragraphs.
75
+ """
76
+
77
+ def __post_init__(self) -> None:
78
+ self.attrs = convert_attrs(self.attrs)
79
+
80
+ def attrIndex(self, name: str) -> int:
81
+ warnings.warn( # noqa: B028
82
+ "Token.attrIndex should not be used, since Token.attrs is a dictionary",
83
+ UserWarning,
84
+ )
85
+ if name not in self.attrs:
86
+ return -1
87
+ return list(self.attrs.keys()).index(name)
88
+
89
+ def attrItems(self) -> list[tuple[str, str | int | float]]:
90
+ """Get (key, value) list of attrs."""
91
+ return list(self.attrs.items())
92
+
93
+ def attrPush(self, attrData: tuple[str, str | int | float]) -> None:
94
+ """Add `[ name, value ]` attribute to list. Init attrs if necessary."""
95
+ name, value = attrData
96
+ self.attrSet(name, value)
97
+
98
+ def attrSet(self, name: str, value: str | int | float) -> None:
99
+ """Set `name` attribute to `value`. Override old value if exists."""
100
+ self.attrs[name] = value
101
+
102
+ def attrGet(self, name: str) -> None | str | int | float:
103
+ """Get the value of attribute `name`, or null if it does not exist."""
104
+ return self.attrs.get(name, None)
105
+
106
+ def attrJoin(self, name: str, value: str) -> None:
107
+ """Join value to existing attribute via space.
108
+ Or create new attribute if not exists.
109
+ Useful to operate with token classes.
110
+ """
111
+ if name in self.attrs:
112
+ current = self.attrs[name]
113
+ if not isinstance(current, str):
114
+ raise TypeError(
115
+ f"existing attr 'name' is not a str: {self.attrs[name]}"
116
+ )
117
+ self.attrs[name] = f"{current} {value}"
118
+ else:
119
+ self.attrs[name] = value
120
+
121
+ def copy(self, **changes: Any) -> Token:
122
+ """Return a shallow copy of the instance."""
123
+ return dc.replace(self, **changes)
124
+
125
+ def as_dict(
126
+ self,
127
+ *,
128
+ children: bool = True,
129
+ as_upstream: bool = True,
130
+ meta_serializer: Callable[[dict[Any, Any]], Any] | None = None,
131
+ filter: Callable[[str, Any], bool] | None = None,
132
+ dict_factory: Callable[..., MutableMapping[str, Any]] = dict,
133
+ ) -> MutableMapping[str, Any]:
134
+ """Return the token as a dictionary.
135
+
136
+ :param children: Also convert children to dicts
137
+ :param as_upstream: Ensure the output dictionary is equal to that created by markdown-it
138
+ For example, attrs are converted to null or lists
139
+ :param meta_serializer: hook for serializing ``Token.meta``
140
+ :param filter: A callable whose return code determines whether an
141
+ attribute or element is included (``True``) or dropped (``False``).
142
+ Is called with the (key, value) pair.
143
+ :param dict_factory: A callable to produce dictionaries from.
144
+ For example, to produce ordered dictionaries instead of normal Python
145
+ dictionaries, pass in ``collections.OrderedDict``.
146
+
147
+ """
148
+ mapping = dict_factory((f.name, getattr(self, f.name)) for f in dc.fields(self))
149
+ if filter:
150
+ mapping = dict_factory((k, v) for k, v in mapping.items() if filter(k, v))
151
+ if as_upstream and "attrs" in mapping:
152
+ mapping["attrs"] = (
153
+ None
154
+ if not mapping["attrs"]
155
+ else [[k, v] for k, v in mapping["attrs"].items()]
156
+ )
157
+ if meta_serializer and "meta" in mapping:
158
+ mapping["meta"] = meta_serializer(mapping["meta"])
159
+ if children and mapping.get("children", None):
160
+ mapping["children"] = [
161
+ child.as_dict(
162
+ children=children,
163
+ filter=filter,
164
+ dict_factory=dict_factory,
165
+ as_upstream=as_upstream,
166
+ meta_serializer=meta_serializer,
167
+ )
168
+ for child in mapping["children"]
169
+ ]
170
+ return mapping
171
+
172
+ @classmethod
173
+ def from_dict(cls, dct: MutableMapping[str, Any]) -> Token:
174
+ """Convert a dict to a Token."""
175
+ token = cls(**dct)
176
+ if token.children:
177
+ token.children = [cls.from_dict(c) for c in token.children] # type: ignore[arg-type]
178
+ return token
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [console_scripts]
2
+ markdown-it=markdown_it.cli.parse:main
3
+
.cache/uv/archive-v0/kP2PUXEYMUC0shkt92DN5/idna-3.13.dist-info/METADATA ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: idna
3
+ Version: 3.13
4
+ Summary: Internationalized Domain Names in Applications (IDNA)
5
+ Author-email: Kim Davies <kim+pypi@gumleaf.org>
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/x-rst
8
+ License-Expression: BSD-3-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: System Administrators
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: Implementation :: CPython
24
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
25
+ Classifier: Topic :: Internet :: Name Service (DNS)
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Topic :: Utilities
28
+ License-File: LICENSE.md
29
+ Requires-Dist: ruff >= 0.6.2 ; extra == "all"
30
+ Requires-Dist: mypy >= 1.11.2 ; extra == "all"
31
+ Requires-Dist: pytest >= 8.3.2 ; extra == "all"
32
+ Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.rst
33
+ Project-URL: Issue tracker, https://github.com/kjd/idna/issues
34
+ Project-URL: Source, https://github.com/kjd/idna
35
+ Provides-Extra: all
36
+
37
+ Internationalized Domain Names in Applications (IDNA)
38
+ =====================================================
39
+
40
+ Support for `Internationalized Domain Names in
41
+ Applications (IDNA) <https://tools.ietf.org/html/rfc5891>`_
42
+ and `Unicode IDNA Compatibility Processing
43
+ <https://unicode.org/reports/tr46/>`_.
44
+
45
+ The latest versions of these standards supplied here provide
46
+ more comprehensive language coverage and reduce the potential of
47
+ allowing domains with known security vulnerabilities. This library
48
+ is a suitable replacement for the “encodings.idna”
49
+ module that comes with the Python standard library, but which
50
+ only supports an older superseded IDNA specification from 2003.
51
+
52
+ Basic functions are simply executed:
53
+
54
+ .. code-block:: pycon
55
+
56
+ >>> import idna
57
+ >>> idna.encode('ドメイン.テスト')
58
+ b'xn--eckwd4c7c.xn--zckzah'
59
+ >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
60
+ ドメイン.テスト
61
+
62
+
63
+ Installation
64
+ ------------
65
+
66
+ This package is available for installation from PyPI via the
67
+ typical mechanisms, such as:
68
+
69
+ .. code-block:: bash
70
+
71
+ $ python3 -m pip install idna
72
+
73
+
74
+ Usage
75
+ -----
76
+
77
+ For typical usage, the ``encode`` and ``decode`` functions will take a
78
+ domain name argument and perform a conversion to ASCII-compatible encoding
79
+ (known as A-labels), or to Unicode strings (known as U-labels)
80
+ respectively.
81
+
82
+ .. code-block:: pycon
83
+
84
+ >>> import idna
85
+ >>> idna.encode('ドメイン.テスト')
86
+ b'xn--eckwd4c7c.xn--zckzah'
87
+ >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah'))
88
+ ドメイン.テスト
89
+
90
+ Conversions can be applied at a per-label basis using the ``ulabel`` or
91
+ ``alabel`` functions if necessary:
92
+
93
+ .. code-block:: pycon
94
+
95
+ >>> idna.alabel('测试')
96
+ b'xn--0zwm56d'
97
+
98
+
99
+ Compatibility Mapping (UTS #46)
100
+ +++++++++++++++++++++++++++++++
101
+
102
+ This library provides support for `Unicode IDNA Compatibility
103
+ Processing <https://unicode.org/reports/tr46/>`_ which normalizes input from
104
+ different potential ways a user may input a domain prior to performing the IDNA
105
+ conversion operations. This functionality, known as a
106
+ `mapping <https://tools.ietf.org/html/rfc5895>`_, is considered by the
107
+ specification to be a local user-interface issue distinct from IDNA
108
+ conversion functionality.
109
+
110
+ For example, “Königsgäßchen” is not a permissible label as *LATIN
111
+ CAPITAL LETTER K* is not allowed (nor are capital letters in general).
112
+ UTS 46 will convert this into lower case prior to applying the IDNA
113
+ conversion.
114
+
115
+ .. code-block:: pycon
116
+
117
+ >>> import idna
118
+ >>> idna.encode('Königsgäßchen')
119
+ ...
120
+ idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed
121
+ >>> idna.encode('Königsgäßchen', uts46=True)
122
+ b'xn--knigsgchen-b4a3dun'
123
+ >>> print(idna.decode('xn--knigsgchen-b4a3dun'))
124
+ königsgäßchen
125
+
126
+
127
+ Exceptions
128
+ ----------
129
+
130
+ All errors raised during the conversion following the specification
131
+ should raise an exception derived from the ``idna.IDNAError`` base
132
+ class.
133
+
134
+ More specific exceptions that may be generated as ``idna.IDNABidiError``
135
+ when the error reflects an illegal combination of left-to-right and
136
+ right-to-left characters in a label; ``idna.InvalidCodepoint`` when
137
+ a specific codepoint is an illegal character in an IDN label (i.e.
138
+ INVALID); and ``idna.InvalidCodepointContext`` when the codepoint is
139
+ illegal based on its position in the string (i.e. it is CONTEXTO or CONTEXTJ
140
+ but the contextual requirements are not satisfied.)
141
+
142
+ Building and Diagnostics
143
+ ------------------------
144
+
145
+ The IDNA and UTS 46 functionality relies upon pre-calculated lookup
146
+ tables for performance. These tables are derived from computing against
147
+ eligibility criteria in the respective standards using the command-line
148
+ script ``tools/idna-data``.
149
+
150
+ This tool will fetch relevant codepoint data from the Unicode repository
151
+ and perform the required calculations to identify eligibility. There are
152
+ three main modes:
153
+
154
+ * ``idna-data make-libdata``. Generates ``idnadata.py`` and
155
+ ``uts46data.py``, the pre-calculated lookup tables used for IDNA and
156
+ UTS 46 conversions. Implementers who wish to track this library against
157
+ a different Unicode version may use this tool to manually generate a
158
+ different version of the ``idnadata.py`` and ``uts46data.py`` files.
159
+
160
+ * ``idna-data make-table``. Generate a table of the IDNA disposition
161
+ (e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix
162
+ B.1 of RFC 5892 and the pre-computed tables published by `IANA
163
+ <https://www.iana.org/>`_.
164
+
165
+ * ``idna-data U+0061``. Prints debugging output on the various
166
+ properties associated with an individual Unicode codepoint (in this
167
+ case, U+0061), that are used to assess the IDNA and UTS 46 status of a
168
+ codepoint. This is helpful in debugging or analysis.
169
+
170
+ The tool accepts a number of arguments, described using ``idna-data -h``.
171
+ Most notably, the ``--version`` argument allows the specification
172
+ of the version of Unicode to be used in computing the table data. For
173
+ example, ``idna-data --version 9.0.0 make-libdata`` will generate
174
+ library data against Unicode 9.0.0.
175
+
176
+
177
+ Additional Notes
178
+ ----------------
179
+
180
+ * **Packages**. The latest tagged release version is published in the
181
+ `Python Package Index <https://pypi.org/project/idna/>`_.
182
+
183
+ * **Version support**. This library supports Python 3.8 and higher.
184
+ As this library serves as a low-level toolkit for a variety of
185
+ applications, many of which strive for broad compatibility with older
186
+ Python versions, there is no rush to remove older interpreter support.
187
+ Support for older versions are likely to be removed from new releases
188
+ as automated tests can no longer easily be run, i.e. once the Python
189
+ version is officially end-of-life.
190
+
191
+ * **Testing**. The library has a test suite based on each rule of the
192
+ IDNA specification, as well as tests that are provided as part of the
193
+ Unicode Technical Standard 46, `Unicode IDNA Compatibility Processing
194
+ <https://unicode.org/reports/tr46/>`_.
195
+
196
+ * **Emoji**. It is an occasional request to support emoji domains in
197
+ this library. Encoding of symbols like emoji is expressly prohibited by
198
+ the IDNA technical standard, and emoji domains are broadly phased
199
+ out across the domain industry due to associated security risks.
200
+
201
+ * **Transitional processing**. Unicode 16.0.0 removed transitional
202
+ processing so the `transitional` argument for the encode() method
203
+ no longer has any effect and will be removed at a later date.
204
+
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging-26.2.dist-info/RECORD ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ packaging/__init__.py,sha256=QhMEdPu2XogrJzV3S0KWS6t7l0I9k8EeDRJl4fnw87s,494
2
+ packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211
3
+ packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559
4
+ packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707
5
+ packaging/_parser.py,sha256=Kf2nsDw4c54X82pY8ba4F02Bve6OygGMAjL-Begqcew,11698
6
+ packaging/_structures.py,sha256=60jRbF78p8z5MKnNd6cAprgOadCJHV0DlmUmRBqFZcs,1109
7
+ packaging/_tokenizer.py,sha256=tFU2Wr-ZZJdAbkXLEJo7qUQDJaIkfft9DqaifiEND7A,5391
8
+ packaging/dependency_groups.py,sha256=XZIAVFK9uHG4RCGprmJn3VInUWMesxha_kytJuMO9eY,10218
9
+ packaging/direct_url.py,sha256=eKmbDiPP1sLV4Mj_kCSZqqknrIyVO9Sr7JpF8KCjp4U,10917
10
+ packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680
11
+ packaging/markers.py,sha256=8fDIUhAF6YMnCNB5FSiwh9pEIusiFzAF73J-0OB8bTk,17055
12
+ packaging/metadata.py,sha256=crAh0E3GVGVqPlu6EdRFsaG-Y6UYznTUqjuGKRGPv6c,38770
13
+ packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ packaging/pylock.py,sha256=G_1gncTmDbRLY1jo4VDI9Uw-b5IErh_Q9V_BbVJTmD8,33890
15
+ packaging/requirements.py,sha256=dd1c9aa1gp5NI6btF6UFRQjPn1nxQXnE_T34yDDTEpc,4383
16
+ packaging/specifiers.py,sha256=Mfp8avQg0lVot17to9lVKBtZD1FsWBTItoGwFUZ3wtg,71514
17
+ packaging/tags.py,sha256=NQ1weo69_Sjte3xBZ1I_G63CIgCmaN0C24mz-z3hGYo,34224
18
+ packaging/utils.py,sha256=M7-JMKic2sP1YtV_8aW7eVGB-x3ADuKCiSrsVeCd2Uo,9848
19
+ packaging/version.py,sha256=Y1aTtxe3sn2xOMa5BdI85-AcHuybbanOVkEvvSRRC8I,38369
20
+ packaging/licenses/__init__.py,sha256=_Jx0XRiD_58palsWnyLrLuh59ZpGCPIPXLKdZo9OJvQ,7293
21
+ packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122
22
+ packaging-26.2.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197
23
+ packaging-26.2.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174
24
+ packaging-26.2.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344
25
+ packaging-26.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
26
+ packaging-26.2.dist-info/METADATA,sha256=T5y815M0FaR5P3dnyYoralEsgj_IHIczeBVwXyMOyr8,3543
27
+ packaging-26.2.dist-info/RECORD,,
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __title__ = "packaging"
6
+ __summary__ = "Core utilities for Python packages"
7
+ __uri__ = "https://github.com/pypa/packaging"
8
+
9
+ __version__ = "26.2"
10
+
11
+ __author__ = "Donald Stufft and individual contributors"
12
+ __email__ = "donald@stufft.io"
13
+
14
+ __license__ = "BSD-2-Clause or Apache-2.0"
15
+ __copyright__ = f"2014 {__author__}"
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_parser.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handwritten parser of dependency specifiers.
2
+
3
+ The docstring for each __parse_* function contains EBNF-inspired grammar representing
4
+ the implementation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ from typing import List, Literal, NamedTuple, Sequence, Tuple, Union
11
+
12
+ from ._tokenizer import DEFAULT_RULES, Tokenizer
13
+
14
+
15
+ class Node:
16
+ __slots__ = ("value",)
17
+
18
+ def __init__(self, value: str) -> None:
19
+ self.value = value
20
+
21
+ def __str__(self) -> str:
22
+ return self.value
23
+
24
+ def __repr__(self) -> str:
25
+ return f"<{self.__class__.__name__}({self.value!r})>"
26
+
27
+ def serialize(self) -> str:
28
+ raise NotImplementedError
29
+
30
+ def __getstate__(self) -> str:
31
+ # Return just the value string for compactness and stability.
32
+ return self.value
33
+
34
+ def _restore_value(self, value: object) -> None:
35
+ if not isinstance(value, str):
36
+ raise TypeError(
37
+ f"Cannot restore {self.__class__.__name__} value from {value!r}"
38
+ )
39
+ self.value = value
40
+
41
+ def __setstate__(self, state: object) -> None:
42
+ if isinstance(state, str):
43
+ # New format (26.2+): just the value string.
44
+ self._restore_value(state)
45
+ return
46
+ if isinstance(state, tuple) and len(state) == 2:
47
+ # Old format (packaging <= 26.0, __slots__): (None, {slot: value}).
48
+ _, slot_dict = state
49
+ if isinstance(slot_dict, dict) and "value" in slot_dict:
50
+ self._restore_value(slot_dict["value"])
51
+ return
52
+ if isinstance(state, dict) and "value" in state:
53
+ # Old format (packaging <= 25.0, no __slots__): plain __dict__.
54
+ self._restore_value(state["value"])
55
+ return
56
+ raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}")
57
+
58
+
59
+ class Variable(Node):
60
+ __slots__ = ()
61
+
62
+ def serialize(self) -> str:
63
+ return str(self)
64
+
65
+
66
+ class Value(Node):
67
+ __slots__ = ()
68
+
69
+ def serialize(self) -> str:
70
+ return f'"{self}"'
71
+
72
+
73
+ class Op(Node):
74
+ __slots__ = ()
75
+
76
+ def serialize(self) -> str:
77
+ return str(self)
78
+
79
+
80
+ MarkerLogical = Literal["and", "or"]
81
+ MarkerVar = Union[Variable, Value]
82
+ MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
83
+ MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
84
+ MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
85
+
86
+
87
+ class ParsedRequirement(NamedTuple):
88
+ name: str
89
+ url: str
90
+ extras: list[str]
91
+ specifier: str
92
+ marker: MarkerList | None
93
+
94
+
95
+ # --------------------------------------------------------------------------------------
96
+ # Recursive descent parser for dependency specifier
97
+ # --------------------------------------------------------------------------------------
98
+ def parse_requirement(source: str) -> ParsedRequirement:
99
+ return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
100
+
101
+
102
+ def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
103
+ """
104
+ requirement = WS? IDENTIFIER WS? extras WS? requirement_details
105
+ """
106
+ tokenizer.consume("WS")
107
+
108
+ name_token = tokenizer.expect(
109
+ "IDENTIFIER", expected="package name at the start of dependency specifier"
110
+ )
111
+ name = name_token.text
112
+ tokenizer.consume("WS")
113
+
114
+ extras = _parse_extras(tokenizer)
115
+ tokenizer.consume("WS")
116
+
117
+ url, specifier, marker = _parse_requirement_details(tokenizer)
118
+ tokenizer.expect("END", expected="end of dependency specifier")
119
+
120
+ return ParsedRequirement(name, url, extras, specifier, marker)
121
+
122
+
123
+ def _parse_requirement_details(
124
+ tokenizer: Tokenizer,
125
+ ) -> tuple[str, str, MarkerList | None]:
126
+ """
127
+ requirement_details = AT URL (WS requirement_marker?)?
128
+ | specifier WS? (requirement_marker)?
129
+ """
130
+
131
+ specifier = ""
132
+ url = ""
133
+ marker = None
134
+
135
+ if tokenizer.check("AT"):
136
+ tokenizer.read()
137
+ tokenizer.consume("WS")
138
+
139
+ url_start = tokenizer.position
140
+ url = tokenizer.expect("URL", expected="URL after @").text
141
+ if tokenizer.check("END", peek=True):
142
+ return (url, specifier, marker)
143
+
144
+ tokenizer.expect("WS", expected="whitespace after URL")
145
+
146
+ # The input might end after whitespace.
147
+ if tokenizer.check("END", peek=True):
148
+ return (url, specifier, marker)
149
+
150
+ marker = _parse_requirement_marker(
151
+ tokenizer,
152
+ span_start=url_start,
153
+ expected="semicolon (after URL and whitespace)",
154
+ )
155
+ else:
156
+ specifier_start = tokenizer.position
157
+ specifier = _parse_specifier(tokenizer)
158
+ tokenizer.consume("WS")
159
+
160
+ if tokenizer.check("END", peek=True):
161
+ return (url, specifier, marker)
162
+
163
+ marker = _parse_requirement_marker(
164
+ tokenizer,
165
+ span_start=specifier_start,
166
+ expected=(
167
+ "comma (within version specifier), semicolon (after version specifier)"
168
+ if specifier
169
+ else "semicolon (after name with no version specifier)"
170
+ ),
171
+ )
172
+
173
+ return (url, specifier, marker)
174
+
175
+
176
+ def _parse_requirement_marker(
177
+ tokenizer: Tokenizer, *, span_start: int, expected: str
178
+ ) -> MarkerList:
179
+ """
180
+ requirement_marker = SEMICOLON marker WS?
181
+ """
182
+
183
+ if not tokenizer.check("SEMICOLON"):
184
+ tokenizer.raise_syntax_error(
185
+ f"Expected {expected} or end",
186
+ span_start=span_start,
187
+ span_end=None,
188
+ )
189
+ tokenizer.read()
190
+
191
+ marker = _parse_marker(tokenizer)
192
+ tokenizer.consume("WS")
193
+
194
+ return marker
195
+
196
+
197
+ def _parse_extras(tokenizer: Tokenizer) -> list[str]:
198
+ """
199
+ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
200
+ """
201
+ if not tokenizer.check("LEFT_BRACKET", peek=True):
202
+ return []
203
+
204
+ with tokenizer.enclosing_tokens(
205
+ "LEFT_BRACKET",
206
+ "RIGHT_BRACKET",
207
+ around="extras",
208
+ ):
209
+ tokenizer.consume("WS")
210
+ extras = _parse_extras_list(tokenizer)
211
+ tokenizer.consume("WS")
212
+
213
+ return extras
214
+
215
+
216
+ def _parse_extras_list(tokenizer: Tokenizer) -> list[str]:
217
+ """
218
+ extras_list = identifier (wsp* ',' wsp* identifier)*
219
+ """
220
+ extras: list[str] = []
221
+
222
+ if not tokenizer.check("IDENTIFIER"):
223
+ return extras
224
+
225
+ extras.append(tokenizer.read().text)
226
+
227
+ while True:
228
+ tokenizer.consume("WS")
229
+ if tokenizer.check("IDENTIFIER", peek=True):
230
+ tokenizer.raise_syntax_error("Expected comma between extra names")
231
+ elif not tokenizer.check("COMMA"):
232
+ break
233
+
234
+ tokenizer.read()
235
+ tokenizer.consume("WS")
236
+
237
+ extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
238
+ extras.append(extra_token.text)
239
+
240
+ return extras
241
+
242
+
243
+ def _parse_specifier(tokenizer: Tokenizer) -> str:
244
+ """
245
+ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
246
+ | WS? version_many WS?
247
+ """
248
+ with tokenizer.enclosing_tokens(
249
+ "LEFT_PARENTHESIS",
250
+ "RIGHT_PARENTHESIS",
251
+ around="version specifier",
252
+ ):
253
+ tokenizer.consume("WS")
254
+ parsed_specifiers = _parse_version_many(tokenizer)
255
+ tokenizer.consume("WS")
256
+
257
+ return parsed_specifiers
258
+
259
+
260
+ def _parse_version_many(tokenizer: Tokenizer) -> str:
261
+ """
262
+ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
263
+ """
264
+ parsed_specifiers = ""
265
+ while tokenizer.check("SPECIFIER"):
266
+ span_start = tokenizer.position
267
+ parsed_specifiers += tokenizer.read().text
268
+ if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
269
+ tokenizer.raise_syntax_error(
270
+ ".* suffix can only be used with `==` or `!=` operators",
271
+ span_start=span_start,
272
+ span_end=tokenizer.position + 1,
273
+ )
274
+ if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
275
+ tokenizer.raise_syntax_error(
276
+ "Local version label can only be used with `==` or `!=` operators",
277
+ span_start=span_start,
278
+ span_end=tokenizer.position,
279
+ )
280
+ tokenizer.consume("WS")
281
+ if not tokenizer.check("COMMA"):
282
+ break
283
+ parsed_specifiers += tokenizer.read().text
284
+ tokenizer.consume("WS")
285
+
286
+ return parsed_specifiers
287
+
288
+
289
+ # --------------------------------------------------------------------------------------
290
+ # Recursive descent parser for marker expression
291
+ # --------------------------------------------------------------------------------------
292
+ def parse_marker(source: str) -> MarkerList:
293
+ return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
294
+
295
+
296
+ def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
297
+ retval = _parse_marker(tokenizer)
298
+ tokenizer.expect("END", expected="end of marker expression")
299
+ return retval
300
+
301
+
302
+ def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
303
+ """
304
+ marker = marker_atom (BOOLOP marker_atom)+
305
+ """
306
+ expression = [_parse_marker_atom(tokenizer)]
307
+ while tokenizer.check("BOOLOP"):
308
+ token = tokenizer.read()
309
+ expr_right = _parse_marker_atom(tokenizer)
310
+ expression.extend((token.text, expr_right))
311
+ return expression
312
+
313
+
314
+ def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
315
+ """
316
+ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
317
+ | WS? marker_item WS?
318
+ """
319
+
320
+ tokenizer.consume("WS")
321
+ if tokenizer.check("LEFT_PARENTHESIS", peek=True):
322
+ with tokenizer.enclosing_tokens(
323
+ "LEFT_PARENTHESIS",
324
+ "RIGHT_PARENTHESIS",
325
+ around="marker expression",
326
+ ):
327
+ tokenizer.consume("WS")
328
+ marker: MarkerAtom = _parse_marker(tokenizer)
329
+ tokenizer.consume("WS")
330
+ else:
331
+ marker = _parse_marker_item(tokenizer)
332
+ tokenizer.consume("WS")
333
+ return marker
334
+
335
+
336
+ def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
337
+ """
338
+ marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
339
+ """
340
+ tokenizer.consume("WS")
341
+ marker_var_left = _parse_marker_var(tokenizer)
342
+ tokenizer.consume("WS")
343
+ marker_op = _parse_marker_op(tokenizer)
344
+ tokenizer.consume("WS")
345
+ marker_var_right = _parse_marker_var(tokenizer)
346
+ tokenizer.consume("WS")
347
+ return (marker_var_left, marker_op, marker_var_right)
348
+
349
+
350
+ def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503
351
+ """
352
+ marker_var = VARIABLE | QUOTED_STRING
353
+ """
354
+ if tokenizer.check("VARIABLE"):
355
+ return process_env_var(tokenizer.read().text.replace(".", "_"))
356
+ elif tokenizer.check("QUOTED_STRING"):
357
+ return process_python_str(tokenizer.read().text)
358
+ else:
359
+ tokenizer.raise_syntax_error(
360
+ message="Expected a marker variable or quoted string"
361
+ )
362
+
363
+
364
+ def process_env_var(env_var: str) -> Variable:
365
+ if env_var in ("platform_python_implementation", "python_implementation"):
366
+ return Variable("platform_python_implementation")
367
+ else:
368
+ return Variable(env_var)
369
+
370
+
371
+ def process_python_str(python_str: str) -> Value:
372
+ value = ast.literal_eval(python_str)
373
+ return Value(str(value))
374
+
375
+
376
+ def _parse_marker_op(tokenizer: Tokenizer) -> Op:
377
+ """
378
+ marker_op = IN | NOT IN | OP
379
+ """
380
+ if tokenizer.check("IN"):
381
+ tokenizer.read()
382
+ return Op("in")
383
+ elif tokenizer.check("NOT"):
384
+ tokenizer.read()
385
+ tokenizer.expect("WS", expected="whitespace after 'not'")
386
+ tokenizer.expect("IN", expected="'in' after 'not'")
387
+ return Op("not in")
388
+ elif tokenizer.check("OP"):
389
+ return Op(tokenizer.read().text)
390
+ else:
391
+ return tokenizer.raise_syntax_error(
392
+ "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in"
393
+ )
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_structures.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ """Backward-compatibility shim for unpickling Version objects serialized before
6
+ packaging 26.1.
7
+
8
+ Old pickles reference ``packaging._structures.InfinityType`` and
9
+ ``packaging._structures.NegativeInfinityType``. This module provides minimal
10
+ stand-in classes so that ``pickle.loads()`` can resolve those references.
11
+ The deserialized objects are not used for comparisons — ``Version.__setstate__``
12
+ discards the stale ``_key`` cache and recomputes it from the core version fields.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+
18
+ class InfinityType:
19
+ """Stand-in for the removed ``InfinityType`` used in old comparison keys."""
20
+
21
+ def __repr__(self) -> str:
22
+ return "Infinity"
23
+
24
+
25
+ class NegativeInfinityType:
26
+ """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys."""
27
+
28
+ def __repr__(self) -> str:
29
+ return "-Infinity"
30
+
31
+
32
+ Infinity = InfinityType()
33
+ NegativeInfinity = NegativeInfinityType()
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/dependency_groups.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections.abc import Mapping, Sequence
5
+
6
+ from .errors import _ErrorCollector
7
+ from .requirements import Requirement
8
+
9
+ __all__ = [
10
+ "CyclicDependencyGroup",
11
+ "DependencyGroupInclude",
12
+ "DependencyGroupResolver",
13
+ "DuplicateGroupNames",
14
+ "InvalidDependencyGroupObject",
15
+ "resolve_dependency_groups",
16
+ ]
17
+
18
+
19
+ def __dir__() -> list[str]:
20
+ return __all__
21
+
22
+
23
+ # -----------
24
+ # Error Types
25
+ # -----------
26
+
27
+
28
+ class DuplicateGroupNames(ValueError):
29
+ """
30
+ The same dependency groups were defined twice, with different non-normalized names.
31
+ """
32
+
33
+
34
+ class CyclicDependencyGroup(ValueError):
35
+ """
36
+ The dependency group includes form a cycle.
37
+ """
38
+
39
+ def __init__(self, requested_group: str, group: str, include_group: str) -> None:
40
+ self.requested_group = requested_group
41
+ self.group = group
42
+ self.include_group = include_group
43
+
44
+ if include_group == group:
45
+ reason = f"{group} includes itself"
46
+ else:
47
+ reason = f"{include_group} -> {group}, {group} -> {include_group}"
48
+ super().__init__(
49
+ "Cyclic dependency group include while resolving "
50
+ f"{requested_group}: {reason}"
51
+ )
52
+
53
+
54
+ # in the PEP 735 spec, the tables in dependency group lists were described as
55
+ # "Dependency Object Specifiers", but the only defined type of object was a
56
+ # "Dependency Group Include" -- hence the naming of this error as "Object"
57
+ class InvalidDependencyGroupObject(ValueError):
58
+ """
59
+ A member of a dependency group was identified as a dict, but was not in a valid
60
+ format.
61
+ """
62
+
63
+
64
+ # ------------------------
65
+ # Object Model & Interface
66
+ # ------------------------
67
+
68
+
69
+ class DependencyGroupInclude:
70
+ __slots__ = ("include_group",)
71
+
72
+ def __init__(self, include_group: str) -> None:
73
+ """
74
+ Initialize a DependencyGroupInclude.
75
+
76
+ :param include_group: The name of the group referred to by this include.
77
+ """
78
+ self.include_group = include_group
79
+
80
+ def __repr__(self) -> str:
81
+ return f"{self.__class__.__name__}({self.include_group!r})"
82
+
83
+
84
+ class DependencyGroupResolver:
85
+ """
86
+ A resolver for Dependency Group data.
87
+
88
+ This class handles caching, name normalization, cycle detection, and other
89
+ parsing requirements. There are only two public methods for exploring the data:
90
+ ``lookup()`` and ``resolve()``.
91
+
92
+ :param dependency_groups: A mapping, as provided via pyproject
93
+ ``[dependency-groups]``.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]],
99
+ ) -> None:
100
+ errors = _ErrorCollector()
101
+
102
+ self.dependency_groups = _normalize_group_names(dependency_groups, errors)
103
+
104
+ # a map of group names to parsed data
105
+ self._parsed_groups: dict[
106
+ str, tuple[Requirement | DependencyGroupInclude, ...]
107
+ ] = {}
108
+ # a map of group names to their ancestors, used for cycle detection
109
+ self._include_graph_ancestors: dict[str, tuple[str, ...]] = {}
110
+ # a cache of completed resolutions to Requirement lists
111
+ self._resolve_cache: dict[str, tuple[Requirement, ...]] = {}
112
+
113
+ errors.finalize("[dependency-groups] data was invalid")
114
+
115
+ def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]:
116
+ """
117
+ Lookup a group name, returning the parsed dependency data for that group.
118
+ This will not resolve includes.
119
+
120
+ :param group: the name of the group to lookup
121
+ """
122
+ group = _normalize_name(group)
123
+
124
+ with _ErrorCollector().on_exit(
125
+ f"[dependency-groups] data for {group!r} was malformed"
126
+ ) as errors:
127
+ return self._parse_group(group, errors)
128
+
129
+ def resolve(self, group: str) -> tuple[Requirement, ...]:
130
+ """
131
+ Resolve a dependency group to a list of requirements.
132
+
133
+ :param group: the name of the group to resolve
134
+ """
135
+ group = _normalize_name(group)
136
+
137
+ with _ErrorCollector().on_exit(
138
+ f"[dependency-groups] data for {group!r} was malformed"
139
+ ) as errors:
140
+ return self._resolve(group, group, errors)
141
+
142
+ def _resolve(
143
+ self, group: str, requested_group: str, errors: _ErrorCollector
144
+ ) -> tuple[Requirement, ...]:
145
+ """
146
+ This is a helper for cached resolution to strings. It preserves the name of the
147
+ group which the user initially requested in order to present a clearer error in
148
+ the event that a cycle is detected.
149
+
150
+ :param group: The normalized name of the group to resolve.
151
+ :param requested_group: The group which was used in the original, user-facing
152
+ request.
153
+ """
154
+ if group in self._resolve_cache:
155
+ return self._resolve_cache[group]
156
+
157
+ parsed = self._parse_group(group, errors)
158
+
159
+ resolved_group = []
160
+
161
+ for item in parsed:
162
+ if isinstance(item, Requirement):
163
+ resolved_group.append(item)
164
+ elif isinstance(item, DependencyGroupInclude):
165
+ include_group = _normalize_name(item.include_group)
166
+
167
+ # if a group is cyclic, record the error
168
+ # otherwise, follow the include_group reference
169
+ #
170
+ # this allows us to examine all includes in a group, even in the
171
+ # presence of errors
172
+ if include_group in self._include_graph_ancestors.get(group, ()):
173
+ errors.error(
174
+ CyclicDependencyGroup(
175
+ requested_group, group, item.include_group
176
+ )
177
+ )
178
+ else:
179
+ self._include_graph_ancestors[include_group] = (
180
+ *self._include_graph_ancestors.get(group, ()),
181
+ group,
182
+ )
183
+ resolved_group.extend(
184
+ self._resolve(include_group, requested_group, errors)
185
+ )
186
+ else: # pragma: no cover
187
+ raise NotImplementedError(
188
+ f"Invalid dependency group item after parse: {item}"
189
+ )
190
+
191
+ # in the event that errors were detected, present the group as empty and do not
192
+ # cache the result
193
+ # this ensures that repeated access to a cyclic group will raise multiple errors
194
+ if errors.errors:
195
+ return ()
196
+
197
+ self._resolve_cache[group] = tuple(resolved_group)
198
+ return self._resolve_cache[group]
199
+
200
+ def _parse_group(
201
+ self, group: str, errors: _ErrorCollector
202
+ ) -> tuple[Requirement | DependencyGroupInclude, ...]:
203
+ # short circuit -- never do the work twice
204
+ if group in self._parsed_groups:
205
+ return self._parsed_groups[group]
206
+
207
+ if group not in self.dependency_groups:
208
+ errors.error(LookupError(f"Dependency group '{group}' not found"))
209
+ return ()
210
+
211
+ raw_group = self.dependency_groups[group]
212
+ if isinstance(raw_group, str):
213
+ errors.error(
214
+ TypeError(
215
+ f"Dependency group {group!r} contained a string rather than a list."
216
+ )
217
+ )
218
+ return ()
219
+
220
+ if not isinstance(raw_group, Sequence):
221
+ errors.error(
222
+ TypeError(f"Dependency group {group!r} is not a sequence type.")
223
+ )
224
+ return ()
225
+
226
+ elements: list[Requirement | DependencyGroupInclude] = []
227
+ for item in raw_group:
228
+ if isinstance(item, str):
229
+ # packaging.requirements.Requirement parsing ensures that this is a
230
+ # valid PEP 508 Dependency Specifier
231
+ # raises InvalidRequirement on failure
232
+ elements.append(Requirement(item))
233
+ elif isinstance(item, Mapping):
234
+ if tuple(item.keys()) != ("include-group",):
235
+ errors.error(
236
+ InvalidDependencyGroupObject(
237
+ f"Invalid dependency group item: {item!r}"
238
+ )
239
+ )
240
+ else:
241
+ include_group = item["include-group"]
242
+ elements.append(DependencyGroupInclude(include_group=include_group))
243
+ else:
244
+ errors.error(TypeError(f"Invalid dependency group item: {item!r}"))
245
+
246
+ self._parsed_groups[group] = tuple(elements)
247
+ return self._parsed_groups[group]
248
+
249
+
250
+ # --------------------
251
+ # Functional Interface
252
+ # --------------------
253
+
254
+
255
+ def resolve_dependency_groups(
256
+ dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str
257
+ ) -> tuple[str, ...]:
258
+ """
259
+ Resolve a dependency group to a tuple of requirements, as strings.
260
+
261
+ :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table
262
+ from ``pyproject.toml``
263
+ :param groups: the name of the group(s) to resolve
264
+ """
265
+ resolver = DependencyGroupResolver(dependency_groups)
266
+ return tuple(str(r) for group in groups for r in resolver.resolve(group))
267
+
268
+
269
+ # ----------------
270
+ # internal helpers
271
+ # ----------------
272
+
273
+
274
+ _NORMALIZE_PATTERN = re.compile(r"[-_.]+")
275
+
276
+
277
+ def _normalize_name(name: str) -> str:
278
+ return _NORMALIZE_PATTERN.sub("-", name).lower()
279
+
280
+
281
+ def _normalize_group_names(
282
+ dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]],
283
+ errors: _ErrorCollector,
284
+ ) -> dict[str, Sequence[str | Mapping[str, str]]]:
285
+ original_names: dict[str, list[str]] = {}
286
+ normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {}
287
+
288
+ for group_name, value in dependency_groups.items():
289
+ normed_group_name = _normalize_name(group_name)
290
+ original_names.setdefault(normed_group_name, []).append(group_name)
291
+ normalized_groups[normed_group_name] = value
292
+
293
+ for normed_name, names in original_names.items():
294
+ if len(names) > 1:
295
+ errors.error(
296
+ DuplicateGroupNames(
297
+ "Duplicate dependency group names: "
298
+ f"{normed_name} ({', '.join(names)})"
299
+ )
300
+ )
301
+
302
+ return normalized_groups
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/errors.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dataclasses
5
+ import sys
6
+ import typing
7
+
8
+ __all__ = ["ExceptionGroup"]
9
+
10
+
11
+ def __dir__() -> list[str]:
12
+ return __all__
13
+
14
+
15
+ if sys.version_info >= (3, 11): # pragma: no cover
16
+ from builtins import ExceptionGroup
17
+ else: # pragma: no cover
18
+
19
+ class ExceptionGroup(Exception):
20
+ """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
21
+
22
+ If :external:exc:`ExceptionGroup` is already defined by Python itself,
23
+ that version is used instead.
24
+ """
25
+
26
+ message: str
27
+ exceptions: list[Exception]
28
+
29
+ def __init__(self, message: str, exceptions: list[Exception]) -> None:
30
+ self.message = message
31
+ self.exceptions = exceptions
32
+
33
+ def __repr__(self) -> str:
34
+ return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
35
+
36
+
37
+ @dataclasses.dataclass
38
+ class _ErrorCollector:
39
+ """
40
+ Collect errors into ExceptionGroups.
41
+
42
+ Used like this:
43
+
44
+ collector = _ErrorCollector()
45
+ # Add a single exception
46
+ collector.error(ValueError("one"))
47
+
48
+ # Supports nesting, including combining ExceptionGroups
49
+ with collector.collect():
50
+ raise ValueError("two")
51
+ collector.finalize("Found some errors")
52
+
53
+ Since making a collector and then calling finalize later is a common pattern,
54
+ a convenience method ``on_exit`` is provided.
55
+ """
56
+
57
+ errors: list[Exception] = dataclasses.field(default_factory=list, init=False)
58
+
59
+ def finalize(self, msg: str) -> None:
60
+ """Raise a group exception if there are any errors."""
61
+ if self.errors:
62
+ raise ExceptionGroup(msg, self.errors)
63
+
64
+ @contextlib.contextmanager
65
+ def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]:
66
+ """
67
+ Calls finalize if no uncollected errors were present.
68
+
69
+ Uncollected errors are raised normally.
70
+ """
71
+ yield self
72
+ self.finalize(msg)
73
+
74
+ @contextlib.contextmanager
75
+ def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]:
76
+ """
77
+ Context manager to collect errors into the error list.
78
+
79
+ Must be inside loops, as only one error can be collected at a time.
80
+ """
81
+ error_classes = err_cls or (Exception,)
82
+ try:
83
+ yield
84
+ except ExceptionGroup as error:
85
+ self.errors.extend(error.exceptions)
86
+ except error_classes as error:
87
+ self.errors.append(error)
88
+
89
+ def error(
90
+ self,
91
+ error: Exception,
92
+ ) -> None:
93
+ """Add an error to the list."""
94
+ self.errors.append(error)
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/py.typed ADDED
File without changes