Add files using upload-large-folder tool
Browse filesFiles changed (50)
- .DS_StoreAdded
- .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_backends/_asyncio.pyAdded
- .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_core/_subprocesses.pyAdded+196
- .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_resources.pyAdded+33
- .cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_testing.pyAdded+65
- .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/RECORDAdded+22
- .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/licenses/LICENSE.txtAdded+28
- .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/_textwrap.pyAdded+51
- .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/parser.pyAdded+532
- .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/termui.pyAdded+891
- .cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/testing.pyAdded+669
- .cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec-2026.4.0.dist-info/METADATAAdded+257
- .cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec/callbacks.pyAdded+324
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/__init__.pyAdded
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/html_re.pyAdded+39
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/utils.pyAdded+313
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/__init__.pyAdded+6
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/parse_link_title.pyAdded+75
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/parser_core.pyAdded+46
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/port.yamlAdded+48
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/default.pyAdded+36
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/zero.pyAdded+44
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/ruler.pyAdded+275
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/__init__.pyAdded+27
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/code.pyAdded+36
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/fence.pyAdded+101
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/hr.pyAdded+56
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/lheading.pyAdded+86
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/list.pyAdded+345
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/paragraph.pyAdded+66
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/__init__.pyAdded+19
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/linkify.pyAdded+149
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/normalize.pyAdded+19
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/text_join.pyAdded+35
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/backticks.pyAdded+72
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/balance_pairs.pyAdded+138
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/emphasis.pyAdded+102
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/linkify.pyAdded+62
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/newline.pyAdded+44
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/token.pyAdded+178
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/entry_points.txtAdded+3
- .cache/uv/archive-v0/kP2PUXEYMUC0shkt92DN5/idna-3.13.dist-info/METADATAAdded+204
- .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging-26.2.dist-info/RECORDAdded+27
- .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/__init__.pyAdded+15
- .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_parser.pyAdded+393
- .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_structures.pyAdded+33
- .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/dependency_groups.pyAdded+302
- .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/errors.pyAdded+94
- .cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/py.typedAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196from __future__ import annotations
from collections.abc import AsyncIterable, Iterable, Mapping, Sequencefrom io import BytesIOfrom os import PathLikefrom subprocess import PIPE, CalledProcessError, CompletedProcessfrom typing import IO, Any, TypeAlias, cast
from ..abc import Processfrom ._eventloop import get_async_backendfrom ._tasks import create_task_group
StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes]
async def run_process( command: StrOrBytesPath | Sequence[StrOrBytesPath], *, input: bytes | None = None, stdin: int | IO[Any] | None = None, stdout: int | IO[Any] | None = PIPE, stderr: int | IO[Any] | None = PIPE, check: bool = True, cwd: StrOrBytesPath | None = None, env: Mapping[str, str] | None = None, startupinfo: Any = None, creationflags: int = 0, start_new_session: bool = False, pass_fds: Sequence[int] = (), user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1,) -> CompletedProcess[bytes]: """ Run an external command in a subprocess and wait until it completes.
.. seealso:: :func:`subprocess.run`
:param command: either a string to pass to the shell, or an iterable of strings containing the executable name or path and its arguments :param input: bytes passed to the standard input of the subprocess :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or `None`; ``input`` overrides this :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or `None` :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, :data:`subprocess.STDOUT`, a file-like object, or `None` :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the process terminates with a return code other than 0 :param cwd: If not ``None``, change the working directory to this before running the command :param env: if not ``None``, this mapping replaces the inherited environment variables from the parent process :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used to specify process startup parameters (Windows only) :param creationflags: flags that can be used to control the creation of the subprocess (see :class:`subprocess.Popen` for the specifics) :param start_new_session: if ``true`` the setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only) :param pass_fds: sequence of file descriptors to keep open between the parent and child processes. (POSIX only) :param user: effective user to run the process as (Python >= 3.9, POSIX only) :param group: effective group to run the process as (Python >= 3.9, POSIX only) :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9, POSIX only) :param umask: if not negative, this umask is applied in the child process before running the given command (Python >= 3.9, POSIX only) :return: an object representing the completed process :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process exits with a nonzero return code
"""
async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None: buffer = BytesIO() async for chunk in stream: buffer.write(chunk)
stream_contents[index] = buffer.getvalue()
if stdin is not None and input is not None: raise ValueError("only one of stdin and input is allowed")
async with await open_process( command, stdin=PIPE if input else stdin, stdout=stdout, stderr=stderr, cwd=cwd, env=env, startupinfo=startupinfo, creationflags=creationflags, start_new_session=start_new_session, pass_fds=pass_fds, user=user, group=group, extra_groups=extra_groups, umask=umask, ) as process: stream_contents: list[bytes | None] = [None, None] async with create_task_group() as tg: if process.stdout: tg.start_soon(drain_stream, process.stdout, 0)
if process.stderr: tg.start_soon(drain_stream, process.stderr, 1)
if process.stdin and input: await process.stdin.send(input) await process.stdin.aclose()
await process.wait()
output, errors = stream_contents if check and process.returncode != 0: raise CalledProcessError(cast(int, process.returncode), command, output, errors)
return CompletedProcess(command, cast(int, process.returncode), output, errors)
async def open_process( command: StrOrBytesPath | Sequence[StrOrBytesPath], *, stdin: int | IO[Any] | None = PIPE, stdout: int | IO[Any] | None = PIPE, stderr: int | IO[Any] | None = PIPE, cwd: StrOrBytesPath | None = None, env: Mapping[str, str] | None = None, startupinfo: Any = None, creationflags: int = 0, start_new_session: bool = False, pass_fds: Sequence[int] = (), user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1,) -> Process: """ Start an external command in a subprocess.
.. seealso:: :class:`subprocess.Popen`
:param command: either a string to pass to the shell, or an iterable of strings containing the executable name or path and its arguments :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or ``None`` :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a file-like object, or ``None`` :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, :data:`subprocess.STDOUT`, a file-like object, or ``None`` :param cwd: If not ``None``, the working directory is changed before executing :param env: If env is not ``None``, it must be a mapping that defines the environment variables for the new process :param creationflags: flags that can be used to control the creation of the subprocess (see :class:`subprocess.Popen` for the specifics) :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used to specify process startup parameters (Windows only) :param start_new_session: if ``true`` the setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only) :param pass_fds: sequence of file descriptors to keep open between the parent and child processes. (POSIX only) :param user: effective user to run the process as (POSIX only) :param group: effective group to run the process as (POSIX only) :param extra_groups: supplementary groups to set in the subprocess (POSIX only) :param umask: if not negative, this umask is applied in the child process before running the given command (POSIX only) :return: an asynchronous process object
""" kwargs: dict[str, Any] = {} if user is not None: kwargs["user"] = user
if group is not None: kwargs["group"] = group
if extra_groups is not None: kwargs["extra_groups"] = group
if umask >= 0: kwargs["umask"] = umask
return await get_async_backend().open_process( command, stdin=stdin, stdout=stdout, stderr=stderr, cwd=cwd, env=env, startupinfo=startupinfo, creationflags=creationflags, start_new_session=start_new_session, pass_fds=pass_fds, **kwargs, )123456789101112131415161718192021222324252627282930313233from __future__ import annotations
from abc import ABCMeta, abstractmethodfrom types import TracebackTypefrom typing import TypeVar
T = TypeVar("T")
class AsyncResource(metaclass=ABCMeta): """ Abstract base class for all closeable asynchronous resources.
Works as an asynchronous context manager which returns the instance itself on enter, and calls :meth:`aclose` on exit. """
__slots__ = ()
async def __aenter__(self: T) -> T: return self
async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: await self.aclose()
@abstractmethod async def aclose(self) -> None: """Close the resource."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465from __future__ import annotations
import typesfrom abc import ABCMeta, abstractmethodfrom collections.abc import AsyncGenerator, Callable, Coroutine, Iterablefrom typing import Any, TypeVar
_T = TypeVar("_T")
class TestRunner(metaclass=ABCMeta): """ Encapsulates a running event loop. Every call made through this object will use the same event loop. """
def __enter__(self) -> TestRunner: return self
@abstractmethod def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None, ) -> bool | None: ...
@abstractmethod def run_asyncgen_fixture( self, fixture_func: Callable[..., AsyncGenerator[_T, Any]], kwargs: dict[str, Any], ) -> Iterable[_T]: """ Run an async generator fixture.
:param fixture_func: the fixture function :param kwargs: keyword arguments to call the fixture function with :return: an iterator yielding the value yielded from the async generator """
@abstractmethod def run_fixture( self, fixture_func: Callable[..., Coroutine[Any, Any, _T]], kwargs: dict[str, Any], ) -> _T: """ Run an async fixture.
:param fixture_func: the fixture function :param kwargs: keyword arguments to call the fixture function with :return: the return value of the fixture function """
@abstractmethod def run_test( self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] ) -> None: """ Run an async test function.
:param test_func: the test function :param kwargs: keyword arguments to call the test function with """12345678910111213141516171819202122click/__init__.py,sha256=tq5olp0lVuUNbwOj0p5nMVdqhOyYz4aZzF8S5T0aFMU,4526click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693click/_termui_impl.py,sha256=R3aYjPD2x1xgNXiXEqHSR-jAVhbXKkLKeqgr-4eDOkA,28066click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400click/_utils.py,sha256=kZwtTf5gMuCilJJceS2iTCvRvCY-0aN5rJq8gKw7p8g,943click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465click/core.py,sha256=wzDpH4Wh45hBfsdw3BHqn_095457WRrb92dyaeIGkHk,134478click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461click/exceptions.py,sha256=8utf8w6V5hJXMnO_ic1FNrtbwuEn1NUu1aDwV8UqnG4,9954click/formatting.py,sha256=RVfwwr0rwWNpgGr8NaHodPzkIr7_tUyVh_nDdanLMNc,9730click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923click/parser.py,sha256=Q31pH0FlQZEq-UXE_ABRzlygEfvxPTuZbWNh4xfXmzw,19010click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0click/shell_completion.py,sha256=Cc4GQUFuWpfQBa9sF5qXeeYI7n3tI_1k6ZdSn4BZbT0,20994click/termui.py,sha256=0xjUaEZJz1_1y8eqon2kOe2OXrmHzZCJoVohFb43yTs,31434click/testing.py,sha256=PYLYW4ZjCAP6HRWtNhFpr3imJxQVEPFq3EW3JL0LTfA,22714click/types.py,sha256=ek54BNSFwPKsqtfT7jsqcc4WHui8AIFVMKM4oVZIXhc,39927click/utils.py,sha256=vep6qqMkv3WkzA9OCu7f6Ku-3beZHNpo8qJqL-uzUk8,20282click-8.3.3.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475click-8.3.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82click-8.3.3.dist-info/METADATA,sha256=_sjhT7_ZKYkyseqbWJtQA8eAcV2CeDJdcNrX_92pSCY,2621click-8.3.3.dist-info/RECORD,,12345678910111213141516171819202122232425262728Copyright 2014 Pallets
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITEDTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051from __future__ import annotations
import collections.abc as cabcimport textwrapfrom contextlib import contextmanager
class TextWrapper(textwrap.TextWrapper): def _handle_long_word( self, reversed_chunks: list[str], cur_line: list[str], cur_len: int, width: int, ) -> None: space_left = max(width - cur_len, 1)
if self.break_long_words: last = reversed_chunks[-1] cut = last[:space_left] res = last[space_left:] cur_line.append(cut) reversed_chunks[-1] = res elif not cur_line: cur_line.append(reversed_chunks.pop())
@contextmanager def extra_indent(self, indent: str) -> cabc.Iterator[None]: old_initial_indent = self.initial_indent old_subsequent_indent = self.subsequent_indent self.initial_indent += indent self.subsequent_indent += indent
try: yield finally: self.initial_indent = old_initial_indent self.subsequent_indent = old_subsequent_indent
def indent_only(self, text: str) -> str: rv = []
for idx, line in enumerate(text.splitlines()): indent = self.initial_indent
if idx > 0: indent = self.subsequent_indent
rv.append(f"{indent}{line}")
return "\n".join(rv)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532"""This module started out as largely a copy paste from the stdlib'soptparse module with the features removed that we do not need fromoptparse because we implement them in Click on a higher level (forinstance type handling, help formatting and a lot more).
The plan is to remove more and more from here over time.
The reason this is a different module and not optparse from the stdlibis that there are differences in 2.x and 3.x about the error messagesgenerated and optparse in the stdlib uses gettext for no good reasonand might cause us issues.
Click uses parts of optparse written by Gregory P. Ward and maintainedby the Python Software Foundation. This is limited to code in parser.py.
Copyright 2001-2006 Gregory P. Ward. All rights reserved.Copyright 2002-2006 Python Software Foundation. All rights reserved."""
# This code uses parts of optparse written by Gregory P. Ward and# maintained by the Python Software Foundation.# Copyright 2001-2006 Gregory P. Ward# Copyright 2002-2006 Python Software Foundationfrom __future__ import annotations
import collections.abc as cabcimport typing as tfrom collections import dequefrom gettext import gettext as _from gettext import ngettext
from ._utils import FLAG_NEEDS_VALUEfrom ._utils import UNSETfrom .exceptions import BadArgumentUsagefrom .exceptions import BadOptionUsagefrom .exceptions import NoSuchOptionfrom .exceptions import UsageError
if t.TYPE_CHECKING: from ._utils import T_FLAG_NEEDS_VALUE from ._utils import T_UNSET from .core import Argument as CoreArgument from .core import Context from .core import Option as CoreOption from .core import Parameter as CoreParameter
V = t.TypeVar("V")
def _unpack_args( args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]: """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders.
Missing items are filled with ``UNSET``. """ args = deque(args) nargs_spec = deque(nargs_spec) rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = [] spos: int | None = None
def _fetch(c: deque[V]) -> V | T_UNSET: try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return UNSET
while nargs_spec: nargs = _fetch(nargs_spec)
if nargs is None: continue
if nargs == 1: rv.append(_fetch(args)) # type: ignore[arg-type] elif nargs > 1: x = [_fetch(args) for _ in range(nargs)]
# If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse()
rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError("Cannot have two nargs < 0")
spos = len(rv) rv.append(UNSET)
# spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1 :] = reversed(rv[spos + 1 :])
return tuple(rv), list(args)
def _split_opt(opt: str) -> tuple[str, str]: first = opt[:1] if first.isalnum(): return "", opt if opt[1:2] == first: return opt[:2], opt[2:] return first, opt[1:]
def _normalize_opt(opt: str, ctx: Context | None) -> str: if ctx is None or ctx.token_normalize_func is None: return opt prefix, opt = _split_opt(opt) return f"{prefix}{ctx.token_normalize_func(opt)}"
class _Option: def __init__( self, obj: CoreOption, opts: cabc.Sequence[str], dest: str | None, action: str | None = None, nargs: int = 1, const: t.Any | None = None, ): self._short_opts = [] self._long_opts = [] self.prefixes: set[str] = set()
for opt in opts: prefix, value = _split_opt(opt) if not prefix: raise ValueError(f"Invalid start character for option ({opt})") self.prefixes.add(prefix[0]) if len(prefix) == 1 and len(value) == 1: self._short_opts.append(opt) else: self._long_opts.append(opt) self.prefixes.add(prefix)
if action is None: action = "store"
self.dest = dest self.action = action self.nargs = nargs self.const = const self.obj = obj
@property def takes_value(self) -> bool: return self.action in ("store", "append")
def process(self, value: t.Any, state: _ParsingState) -> None: if self.action == "store": state.opts[self.dest] = value # type: ignore elif self.action == "store_const": state.opts[self.dest] = self.const # type: ignore elif self.action == "append": state.opts.setdefault(self.dest, []).append(value) # type: ignore elif self.action == "append_const": state.opts.setdefault(self.dest, []).append(self.const) # type: ignore elif self.action == "count": state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore else: raise ValueError(f"unknown action '{self.action}'") state.order.append(self.obj)
class _Argument: def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1): self.dest = dest self.nargs = nargs self.obj = obj
def process( self, value: str | cabc.Sequence[str | None] | None | T_UNSET, state: _ParsingState, ) -> None: if self.nargs > 1: assert isinstance(value, cabc.Sequence) holes = sum(1 for x in value if x is UNSET) if holes == len(value): value = UNSET elif holes != 0: raise BadArgumentUsage( _("Argument {name!r} takes {nargs} values.").format( name=self.dest, nargs=self.nargs ) )
# We failed to collect any argument value so we consider the argument as unset. if value == (): value = UNSET
state.opts[self.dest] = value # type: ignore state.order.append(self.obj)
class _ParsingState: def __init__(self, rargs: list[str]) -> None: self.opts: dict[str, t.Any] = {} self.largs: list[str] = [] self.rargs = rargs self.order: list[CoreParameter] = []
class _OptionParser: """The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you.
It's not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults).
:param ctx: optionally the :class:`~click.Context` where this parser should go with.
.. deprecated:: 8.2 Will be removed in Click 9.0. """
def __init__(self, ctx: Context | None = None) -> None: #: The :class:`~click.Context` for this parser. This might be #: `None` for some advanced use cases. self.ctx = ctx #: This controls how the parser deals with interspersed arguments. #: If this is set to `False`, the parser will stop on the first #: non-option. Click uses this to implement nested subcommands #: safely. self.allow_interspersed_args: bool = True #: This tells the parser how to deal with unknown options. By #: default it will error out (which is sensible), but there is a #: second mode where it will ignore it and continue processing #: after shifting all the unknown options into the resulting args. self.ignore_unknown_options: bool = False
if ctx is not None: self.allow_interspersed_args = ctx.allow_interspersed_args self.ignore_unknown_options = ctx.ignore_unknown_options
self._short_opt: dict[str, _Option] = {} self._long_opt: dict[str, _Option] = {} self._opt_prefixes = {"-", "--"} self._args: list[_Argument] = []
def add_option( self, obj: CoreOption, opts: cabc.Sequence[str], dest: str | None, action: str | None = None, nargs: int = 1, const: t.Any | None = None, ) -> None: """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``append_const`` or ``count``.
The `obj` can be used to identify the option in the order list that is returned from the parser. """ opts = [_normalize_opt(opt, self.ctx) for opt in opts] option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option
def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None: """Adds a positional argument named `dest` to the parser.
The `obj` can be used to identify the option in the order list that is returned from the parser. """ self._args.append(_Argument(obj, dest=dest, nargs=nargs))
def parse_args( self, args: list[str] ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]: """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = _ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order
def _process_args_for_args(self, state: _ParsingState) -> None: pargs, args = _unpack_args( state.largs + state.rargs, [x.nargs for x in self._args] )
for idx, arg in enumerate(self._args): arg.process(pargs[idx], state)
state.largs = args state.rargs = []
def _process_args_for_options(self, state: _ParsingState) -> None: while state.rargs: arg = state.rargs.pop(0) arglen = len(arg) # Double dashes always handled explicitly regardless of what # prefixes are valid. if arg == "--": return elif arg[:1] in self._opt_prefixes and arglen > 1: self._process_opts(arg, state) elif self.allow_interspersed_args: state.largs.append(arg) else: state.rargs.insert(0, arg) return
# Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset!
def _match_long_opt( self, opt: str, explicit_value: str | None, state: _ParsingState ) -> None: if opt not in self._long_opt: from difflib import get_close_matches
possibilities = get_close_matches(opt, self._long_opt) raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
option = self._long_opt[opt] if option.takes_value: # At this point it's safe to modify rargs by injecting the # explicit value, because no exception is raised in this # branch. This means that the inserted value will be fully # consumed. if explicit_value is not None: state.rargs.insert(0, explicit_value)
value = self._get_value_from_state(opt, option, state)
elif explicit_value is not None: raise BadOptionUsage( opt, _("Option {name!r} does not take a value.").format(name=opt) )
else: value = UNSET
option.process(value, state)
def _match_short_opt(self, arg: str, state: _ParsingState) -> None: stop = False i = 1 prefix = arg[0] unknown_options = []
for ch in arg[1:]: opt = _normalize_opt(f"{prefix}{ch}", self.ctx) option = self._short_opt.get(opt) i += 1
if not option: if self.ignore_unknown_options: unknown_options.append(ch) continue raise NoSuchOption(opt, ctx=self.ctx) if option.takes_value: # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): state.rargs.insert(0, arg[i:]) stop = True
value = self._get_value_from_state(opt, option, state)
else: value = UNSET
option.process(value, state)
if stop: break
# If we got any unknown options we recombine the string of the # remaining options and re-attach the prefix, then report that # to the state as new larg. This way there is basic combinatorics # that can be achieved while still ignoring unknown arguments. if self.ignore_unknown_options and unknown_options: state.largs.append(f"{prefix}{''.join(unknown_options)}")
def _get_value_from_state( self, option_name: str, option: _Option, state: _ParsingState ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE: nargs = option.nargs
value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE
if len(state.rargs) < nargs: if option.obj._flag_needs_value: # Option allows omitting the value. value = FLAG_NEEDS_VALUE else: raise BadOptionUsage( option_name, ngettext( "Option {name!r} requires an argument.", "Option {name!r} requires {nargs} arguments.", nargs, ).format(name=option_name, nargs=nargs), ) elif nargs == 1: next_rarg = state.rargs[0]
if ( option.obj._flag_needs_value and isinstance(next_rarg, str) and next_rarg[:1] in self._opt_prefixes and len(next_rarg) > 1 ): # The next arg looks like the start of an option, don't # use it as the value if omitting the value is allowed. value = FLAG_NEEDS_VALUE else: value = state.rargs.pop(0) else: value = tuple(state.rargs[:nargs]) del state.rargs[:nargs]
return value
def _process_opts(self, arg: str, state: _ParsingState) -> None: explicit_value = None # Long option handling happens in two parts. The first part is # supporting explicitly attached values. In any case, we will try # to long match the option first. if "=" in arg: long_opt, explicit_value = arg.split("=", 1) else: long_opt = arg norm_long_opt = _normalize_opt(long_opt, self.ctx)
# At this point we will match the (assumed) long option through # the long option matching code. Note that this allows options # like "-foo" to be matched as long options. try: self._match_long_opt(norm_long_opt, explicit_value, state) except NoSuchOption: # At this point the long option matching failed, and we need # to try with short options. However there is a special rule # which says, that if we have a two character options prefix # (applies to "--foo" for instance), we do not dispatch to the # short option code and will instead raise the no option # error. if arg[:2] not in self._opt_prefixes: self._match_short_opt(arg, state) return
if not self.ignore_unknown_options: raise
state.largs.append(arg)
def __getattr__(name: str) -> object: import warnings
if name in { "OptionParser", "Argument", "Option", "split_opt", "normalize_opt", "ParsingState", }: warnings.warn( f"'parser.{name}' is deprecated and will be removed in Click 9.0." " The old parser is available in 'optparse'.", DeprecationWarning, stacklevel=2, ) return globals()[f"_{name}"]
if name == "split_arg_string": from .shell_completion import split_arg_string
warnings.warn( "Importing 'parser.split_arg_string' is deprecated, it will only be" " available in 'shell_completion' in Click 9.0.", DeprecationWarning, stacklevel=2, ) return split_arg_string
raise AttributeError(name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891from __future__ import annotations
import collections.abc as cabcimport inspectimport ioimport itertoolsimport sysimport typing as tfrom contextlib import AbstractContextManagerfrom gettext import gettext as _
from ._compat import isattyfrom ._compat import strip_ansifrom .exceptions import Abortfrom .exceptions import UsageErrorfrom .globals import resolve_color_defaultfrom .types import Choicefrom .types import convert_typefrom .types import ParamTypefrom .utils import echofrom .utils import LazyFile
if t.TYPE_CHECKING: from ._termui_impl import ProgressBar
V = t.TypeVar("V")
# The prompt functions to use. The doc tools currently override these# functions to customize how they work.visible_prompt_func: t.Callable[[str], str] = input
_ansi_colors = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "reset": 39, "bright_black": 90, "bright_red": 91, "bright_green": 92, "bright_yellow": 93, "bright_blue": 94, "bright_magenta": 95, "bright_cyan": 96, "bright_white": 97,}_ansi_reset_all = "\033[0m"
def hidden_prompt_func(prompt: str) -> str: import getpass
return getpass.getpass(prompt)
def _build_prompt( text: str, suffix: str, show_default: bool | str = False, default: t.Any | None = None, show_choices: bool = True, type: ParamType | None = None,) -> str: prompt = text if type is not None and show_choices and isinstance(type, Choice): prompt += f" ({', '.join(map(str, type.choices))})" if isinstance(show_default, str): default = f"({show_default})" if default is not None and show_default: prompt = f"{prompt} [{_format_default(default)}]" return f"{prompt}{suffix}"
def _format_default(default: t.Any) -> t.Any: if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): return default.name
return default
def prompt( text: str, default: t.Any | None = None, hide_input: bool = False, confirmation_prompt: bool | str = False, type: ParamType | t.Any | None = None, value_proc: t.Callable[[str], t.Any] | None = None, prompt_suffix: str = ": ", show_default: bool | str = True, err: bool = False, show_choices: bool = True,) -> t.Any: """Prompts a user for input. This is a convenience function that can be used to prompt a user for input later.
If the user aborts the input by sending an interrupt signal, this function will catch it and raise a :exc:`Abort` exception.
:param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. :param confirmation_prompt: Prompt a second time to confirm the value. Can be set to a string instead of ``True`` to customize the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to convert a value. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. If this value is a string, it shows that string in parentheses instead of the actual value. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. :param show_choices: Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ".
.. versionchanged:: 8.3.3 ``show_default`` can be a string to show a custom value instead of the actual default, matching the help text behavior.
.. versionchanged:: 8.3.1 A space is no longer appended to the prompt.
.. versionadded:: 8.0 ``confirmation_prompt`` can be a custom string.
.. versionadded:: 7.0 Added the ``show_choices`` parameter.
.. versionadded:: 6.0 Added unicode support for cmd.exe on Windows.
.. versionadded:: 4.0 Added the `err` parameter.
"""
def prompt_func(text: str) -> str: f = hidden_prompt_func if hide_input else visible_prompt_func try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(text[:-1], nl=False, err=err) # Echo the last character to stdout to work around an issue where # readline causes backspace to clear the whole line. return f(text[-1:]) except (KeyboardInterrupt, EOFError): # getpass doesn't print a newline if the user aborts input with ^C. # Allegedly this behavior is inherited from getpass(3). # A doc bug has been filed at https://bugs.python.org/issue24711 if hide_input: echo(None, err=err) raise Abort() from None
if value_proc is None: value_proc = convert_type(type, default)
prompt = _build_prompt( text, prompt_suffix, show_default, default, show_choices, type )
if confirmation_prompt: if confirmation_prompt is True: confirmation_prompt = _("Repeat for confirmation")
confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
while True: while True: value = prompt_func(prompt) if value: break elif default is not None: value = default break try: result = value_proc(value) except UsageError as e: if hide_input: echo(_("Error: The value you entered was invalid."), err=err) else: echo(_("Error: {e.message}").format(e=e), err=err) continue if not confirmation_prompt: return result while True: value2 = prompt_func(confirmation_prompt) is_empty = not value and not value2 if value2 or is_empty: break if value == value2: return result echo(_("Error: The two entered values do not match."), err=err)
def confirm( text: str, default: bool | None = False, abort: bool = False, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False,) -> bool: """Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception.
:param text: the question to ask. :param default: The default value to use when no input is given. If ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo.
.. versionchanged:: 8.3.1 A space is no longer appended to the prompt.
.. versionchanged:: 8.0 Repeat until input is given if ``default`` is ``None``.
.. versionadded:: 4.0 Added the ``err`` parameter. """ prompt = _build_prompt( text, prompt_suffix, show_default, "y/n" if default is None else ("Y/n" if default else "y/N"), )
while True: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt[:-1], nl=False, err=err) # Echo the last character to stdout to work around an issue where # readline causes backspace to clear the whole line. value = visible_prompt_func(prompt[-1:]).lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() from None if value in ("y", "yes"): rv = True elif value in ("n", "no"): rv = False elif default is not None and value == "": rv = default else: echo(_("Error: invalid input"), err=err) continue break if abort and not rv: raise Abort() return rv
def echo_via_pager( text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str, color: bool | None = None,) -> None: """This function takes a text and shows it via an environment specific pager on stdout.
.. versionchanged:: 3.0 Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection. """ color = resolve_color_default(color)
if inspect.isgeneratorfunction(text_or_generator): i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)() elif isinstance(text_or_generator, str): i = [text_or_generator] else: i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
# convert every element of i to a text type if necessary text_generator = (el if isinstance(el, str) else str(el) for el in i)
from ._termui_impl import pager
return pager(itertools.chain(text_generator, "\n"), color)
@t.overloaddef progressbar( *, length: int, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1,) -> ProgressBar[int]: ...
@t.overloaddef progressbar( iterable: cabc.Iterable[V] | None = None, length: int | None = None, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1,) -> ProgressBar[V]: ...
def progressbar( iterable: cabc.Iterable[V] | None = None, length: int | None = None, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1,) -> ProgressBar[V]: """This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal.
The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen.
Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won't display progress that is considered too fast, and progress where the time between steps is less than a second.
No printing must happen or the progress bar will be unintentionally destroyed.
Example usage::
with progressbar(items) as bar: for item in bar: do_something_with(item)
Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with::
with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes)
The ``update()`` method also takes an optional value specifying the ``current_item`` at the new position. This is useful when used together with ``item_show_func`` to customize the output for each manual step::
with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive)
:param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param hidden: hide the progressbar. Defaults to ``False``. When no tty is detected, it will only print the progressbar label. Setting this to ``False`` also disables that. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: A function called with the current item which can return a string to show next to the progress bar. If the function returns ``None`` nothing is shown. The current item can be ``None``, such as when entering and exiting the bar. :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: The file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators.
.. versionadded:: 8.2 The ``hidden`` argument.
.. versionchanged:: 8.0 Output is shown even if execution time is less than 0.5 seconds.
.. versionchanged:: 8.0 ``item_show_func`` shows the current item, not the previous one.
.. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output.
.. versionadded:: 8.0 The ``update_min_steps`` parameter.
.. versionadded:: 4.0 The ``color`` parameter and ``update`` method.
.. versionadded:: 2.0 """ from ._termui_impl import ProgressBar
color = resolve_color_default(color) return ProgressBar( iterable=iterable, length=length, hidden=hidden, show_eta=show_eta, show_percent=show_percent, show_pos=show_pos, item_show_func=item_show_func, fill_char=fill_char, empty_char=empty_char, bar_template=bar_template, info_sep=info_sep, file=file, label=label, width=width, color=color, update_min_steps=update_min_steps, )
def clear() -> None: """Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal.
.. versionadded:: 2.0 """ if not isatty(sys.stdout): return
# ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor echo("\033[2J\033[1;1H", nl=False)
def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str: if isinstance(color, int): return f"{38 + offset};5;{color:d}"
if isinstance(color, (tuple, list)): r, g, b = color return f"{38 + offset};2;{r:d};{g:d};{b:d}"
return str(_ansi_colors[color] + offset)
def style( text: t.Any, fg: int | tuple[int, int, int] | str | None = None, bg: int | tuple[int, int, int] | str | None = None, bold: bool | None = None, dim: bool | None = None, underline: bool | None = None, overline: bool | None = None, italic: bool | None = None, blink: bool | None = None, reverse: bool | None = None, strikethrough: bool | None = None, reset: bool = True,) -> str: """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``.
Examples::
click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
Supported color names:
* ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``bright_black`` * ``bright_red`` * ``bright_green`` * ``bright_yellow`` * ``bright_blue`` * ``bright_magenta`` * ``bright_cyan`` * ``bright_white`` * ``reset`` (reset the color code only)
If the terminal supports it, color may also be specified as:
- An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode. - An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode.
See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information.
:param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param overline: if provided this will enable or disable overline. :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param strikethrough: if provided this will enable or disable striking through text. :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.
.. versionchanged:: 8.0 A non-string ``message`` is converted to a string.
.. versionchanged:: 8.0 Added support for 256 and RGB color codes.
.. versionchanged:: 8.0 Added the ``strikethrough``, ``italic``, and ``overline`` parameters.
.. versionchanged:: 7.0 Added support for bright colors.
.. versionadded:: 2.0 """ if not isinstance(text, str): text = str(text)
bits = []
if fg: try: bits.append(f"\033[{_interpret_color(fg)}m") except KeyError: raise TypeError(f"Unknown color {fg!r}") from None
if bg: try: bits.append(f"\033[{_interpret_color(bg, 10)}m") except KeyError: raise TypeError(f"Unknown color {bg!r}") from None
if bold is not None: bits.append(f"\033[{1 if bold else 22}m") if dim is not None: bits.append(f"\033[{2 if dim else 22}m") if underline is not None: bits.append(f"\033[{4 if underline else 24}m") if overline is not None: bits.append(f"\033[{53 if overline else 55}m") if italic is not None: bits.append(f"\033[{3 if italic else 23}m") if blink is not None: bits.append(f"\033[{5 if blink else 25}m") if reverse is not None: bits.append(f"\033[{7 if reverse else 27}m") if strikethrough is not None: bits.append(f"\033[{9 if strikethrough else 29}m") bits.append(text) if reset: bits.append(_ansi_reset_all) return "".join(bits)
def unstyle(text: str) -> str: """Removes ANSI styling information from a string. Usually it's not necessary to use this function as Click's echo function will automatically remove styling if necessary.
.. versionadded:: 2.0
:param text: the text to remove style information from. """ return strip_ansi(text)
def secho( message: t.Any | None = None, file: t.IO[t.AnyStr] | None = None, nl: bool = True, err: bool = False, color: bool | None = None, **styles: t.Any,) -> None: """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same::
click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green'))
All keyword arguments are forwarded to the underlying functions depending on which one they go with.
Non-string types will be converted to :class:`str`. However, :class:`bytes` are passed directly to :meth:`echo` without applying style. If you want to style bytes that represent text, call :meth:`bytes.decode` first.
.. versionchanged:: 8.0 A non-string ``message`` is converted to a string. Bytes are passed through without style applied.
.. versionadded:: 2.0 """ if message is not None and not isinstance(message, (bytes, bytearray)): message = style(message, **styles)
return echo(message, file=file, nl=nl, err=err, color=color)
@t.overloaddef edit( text: bytes | bytearray, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = False, extension: str = ".txt",) -> bytes | None: ...
@t.overloaddef edit( text: str, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt",) -> str | None: ...
@t.overloaddef edit( text: None = None, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", filename: str | cabc.Iterable[str] | None = None,) -> None: ...
def edit( text: str | bytes | bytearray | None = None, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", filename: str | cabc.Iterable[str] | None = None,) -> str | bytes | bytearray | None: r"""Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored.
If the editor cannot be opened a :exc:`UsageError` is raised.
Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers.
:param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. If the editor supports editing multiple files at once, a sequence of files may be passed as well. Invoke `click.file` once per file instead if multiple files cannot be managed at once or editing the files serially is desired.
.. versionchanged:: 8.2.0 ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str`` if the ``editor`` supports editing multiple files at once.
""" from ._termui_impl import Editor
ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
if filename is None: return ed.edit(text)
if isinstance(filename, str): filename = (filename,)
ed.edit_files(filenames=filename) return None
def launch(url: str, wait: bool = False, locate: bool = False) -> int: """This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, ``0`` indicates success.
Examples::
click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True)
.. versionadded:: 2.0
:param url: URL or filename of the thing to launch. :param wait: Wait for the program to exit before returning. This only works if the launched program blocks. In particular, ``xdg-open`` on Linux does not block. :param locate: if this is set to `True` then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. """ from ._termui_impl import open_url
return open_url(url, wait=wait, locate=locate)
# If this is provided, getchar() calls into this instead. This is used# for unittesting purposes._getchar: t.Callable[[bool], str] | None = None
def getchar(echo: bool = False) -> str: """Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.
Note that this will always read from the terminal, even if something is piped into the standard input.
Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers.
.. versionadded:: 2.0
:param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. """ global _getchar
if _getchar is None: from ._termui_impl import getchar as f
_getchar = f
return _getchar(echo)
def raw_terminal() -> AbstractContextManager[int]: from ._termui_impl import raw_terminal as f
return f()
def pause(info: str | None = None, err: bool = False) -> None: """This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing.
.. versionadded:: 2.0
.. versionadded:: 4.0 Added the `err` parameter.
:param info: The message to print before pausing. Defaults to ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return
if info is None: info = _("Press any key to continue...")
try: if info: echo(info, nl=False, err=err) try: getchar() except (KeyboardInterrupt, EOFError): pass finally: if info: echo(err=err)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669from __future__ import annotations
import collections.abc as cabcimport contextlibimport ioimport osimport pdbimport shleximport sysimport tempfileimport typing as tfrom types import TracebackType
from . import _compatfrom . import formattingfrom . import termuifrom . import utilsfrom ._compat import _find_binary_reader
if t.TYPE_CHECKING: from _typeshed import ReadableBuffer
from .core import Command
class EchoingStdin: def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None: self._input = input self._output = output self._paused = False
def __getattr__(self, x: str) -> t.Any: return getattr(self._input, x)
def _echo(self, rv: bytes) -> bytes: if not self._paused: self._output.write(rv)
return rv
def read(self, n: int = -1) -> bytes: return self._echo(self._input.read(n))
def read1(self, n: int = -1) -> bytes: return self._echo(self._input.read1(n)) # type: ignore
def readline(self, n: int = -1) -> bytes: return self._echo(self._input.readline(n))
def readlines(self) -> list[bytes]: return [self._echo(x) for x in self._input.readlines()]
def __iter__(self) -> cabc.Iterator[bytes]: return iter(self._echo(x) for x in self._input)
def __repr__(self) -> str: return repr(self._input)
@contextlib.contextmanagerdef _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]: if stream is None: yield else: stream._paused = True yield stream._paused = False
class BytesIOCopy(io.BytesIO): """Patch ``io.BytesIO`` to let the written stream be copied to another.
.. versionadded:: 8.2 """
def __init__(self, copy_to: io.BytesIO) -> None: super().__init__() self.copy_to = copy_to
def flush(self) -> None: super().flush() self.copy_to.flush()
def write(self, b: ReadableBuffer) -> int: self.copy_to.write(b) return super().write(b)
class StreamMixer: """Mixes `<stdout>` and `<stderr>` streams.
The result is available in the ``output`` attribute.
.. versionadded:: 8.2 """
def __init__(self) -> None: self.output: io.BytesIO = io.BytesIO() self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output) self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)
class _NamedTextIOWrapper(io.TextIOWrapper): """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode`` that does not close its underlying buffer.
An optional ``original_fd`` preserves the file descriptor of the stream being replaced, so that C-level consumers that call :meth:`fileno` (``faulthandler``, ``subprocess``, ...) still work. Inspired by pytest's ``capsys``/``capfd`` split: see :doc:`/testing` for details.
.. versionchanged:: 8.3.3 Added ``original_fd`` parameter and :meth:`fileno` override. """
def __init__( self, buffer: t.BinaryIO, name: str, mode: str, *, original_fd: int = -1, **kwargs: t.Any, ) -> None: super().__init__(buffer, **kwargs) self._name = name self._mode = mode self._original_fd = original_fd
def close(self) -> None: """The buffer this object contains belongs to some other object, so prevent the default ``__del__`` implementation from closing that buffer.
.. versionadded:: 8.3.2 """
def fileno(self) -> int: """Return the file descriptor of the original stream, if one was provided at construction time.
This allows C-level consumers (``faulthandler``, ``subprocess``, signal handlers, ...) to obtain a valid fd without crashing, even though the Python-level writes are redirected to an in-memory buffer.
.. versionadded:: 8.3.3 """ if self._original_fd >= 0: return self._original_fd return super().fileno()
@property def name(self) -> str: return self._name
@property def mode(self) -> str: return self._mode
def make_input_stream( input: str | bytes | t.IO[t.Any] | None, charset: str) -> t.BinaryIO: # Is already an input stream. if hasattr(input, "read"): rv = _find_binary_reader(t.cast("t.IO[t.Any]", input))
if rv is not None: return rv
raise TypeError("Could not find binary reader for input stream.")
if input is None: input = b"" elif isinstance(input, str): input = input.encode(charset)
return io.BytesIO(input)
class Result: """Holds the captured result of an invoked CLI script.
:param runner: The runner that created the result :param stdout_bytes: The standard output as bytes. :param stderr_bytes: The standard error as bytes. :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would see it in its terminal. :param return_value: The value returned from the invoked command. :param exit_code: The exit code as integer. :param exception: The exception that happened if one did. :param exc_info: Exception information (exception type, exception instance, traceback type).
.. versionchanged:: 8.2 ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and ``mix_stderr`` has been removed.
.. versionadded:: 8.0 Added ``return_value``. """
def __init__( self, runner: CliRunner, stdout_bytes: bytes, stderr_bytes: bytes, output_bytes: bytes, return_value: t.Any, exit_code: int, exception: BaseException | None, exc_info: tuple[type[BaseException], BaseException, TracebackType] | None = None, ): self.runner = runner self.stdout_bytes = stdout_bytes self.stderr_bytes = stderr_bytes self.output_bytes = output_bytes self.return_value = return_value self.exit_code = exit_code self.exception = exception self.exc_info = exc_info
@property def output(self) -> str: """The terminal output as unicode string, as the user would see it.
.. versionchanged:: 8.2 No longer a proxy for ``self.stdout``. Now has its own independent stream that is mixing `<stdout>` and `<stderr>`, in the order they were written. """ return self.output_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" )
@property def stdout(self) -> str: """The standard output as unicode string.""" return self.stdout_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" )
@property def stderr(self) -> str: """The standard error as unicode string.
.. versionchanged:: 8.2 No longer raise an exception, always returns the `<stderr>` string. """ return self.stderr_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" )
def __repr__(self) -> str: exc_str = repr(self.exception) if self.exception else "okay" return f"<{type(self).__name__} {exc_str}>"
class CliRunner: """The CLI runner provides functionality to invoke a Click command line script for unittesting purposes in a isolated environment. This only works in single-threaded systems without any concurrency as it changes the global interpreter state.
:param charset: the character set for the input and output data. :param env: a dictionary with environment variables for overriding. :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes to `<stdout>`. This is useful for showing examples in some circumstances. Note that regular prompts will automatically echo the input. :param catch_exceptions: Whether to catch any exceptions other than ``SystemExit`` when running :meth:`~CliRunner.invoke`.
.. versionchanged:: 8.2 Added the ``catch_exceptions`` parameter.
.. versionchanged:: 8.2 ``mix_stderr`` parameter has been removed. """
def __init__( self, charset: str = "utf-8", env: cabc.Mapping[str, str | None] | None = None, echo_stdin: bool = False, catch_exceptions: bool = True, ) -> None: self.charset = charset self.env: cabc.Mapping[str, str | None] = env or {} self.echo_stdin = echo_stdin self.catch_exceptions = catch_exceptions
def get_default_prog_name(self, cli: Command) -> str: """Given a command object it will return the default program name for it. The default is the `name` attribute or ``"root"`` if not set. """ return cli.name or "root"
def make_env( self, overrides: cabc.Mapping[str, str | None] | None = None ) -> cabc.Mapping[str, str | None]: """Returns the environment overrides for invoking a script.""" rv = dict(self.env) if overrides: rv.update(overrides) return rv
@contextlib.contextmanager def isolation( self, input: str | bytes | t.IO[t.Any] | None = None, env: cabc.Mapping[str, str | None] | None = None, color: bool = False, ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]: """A context manager that sets up the isolation for invoking of a command line tool. This sets up `<stdin>` with the given input data and `os.environ` with the overrides from the given dictionary. This also rebinds some internals in Click to be mocked (like the prompt functionality).
This is automatically done in the :meth:`invoke` method.
:param input: the input stream to put into `sys.stdin`. :param env: the environment overrides as dictionary. :param color: whether the output should contain color codes. The application can still override this explicitly.
.. versionadded:: 8.2 An additional output stream is returned, which is a mix of `<stdout>` and `<stderr>` streams.
.. versionchanged:: 8.2 Always returns the `<stderr>` stream.
.. versionchanged:: 8.0 `<stderr>` is opened with ``errors="backslashreplace"`` instead of the default ``"strict"``.
.. versionchanged:: 4.0 Added the ``color`` parameter. """ bytes_input = make_input_stream(input, self.charset) echo_input = None
old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr old_forced_width = formatting.FORCED_WIDTH formatting.FORCED_WIDTH = 80
env = self.make_env(env)
stream_mixer = StreamMixer()
# Preserve the original file descriptors so that C-level # consumers (faulthandler, subprocess, etc.) can still obtain a # valid fd from the redirected streams. The original streams # may themselves lack a fileno() (e.g. when CliRunner is used # inside pytest's capsys), so we fall back to -1. def _safe_fileno(stream: t.IO[t.Any]) -> int: try: return stream.fileno() except (AttributeError, io.UnsupportedOperation): return -1
old_stdout_fd = _safe_fileno(old_stdout) old_stderr_fd = _safe_fileno(old_stderr)
if self.echo_stdin: bytes_input = echo_input = t.cast( t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout) )
sys.stdin = text_input = _NamedTextIOWrapper( bytes_input, encoding=self.charset, name="<stdin>", mode="r" )
if self.echo_stdin: # Force unbuffered reads, otherwise TextIOWrapper reads a # large chunk which is echoed early. text_input._CHUNK_SIZE = 1 # type: ignore
sys.stdout = _NamedTextIOWrapper( stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w", original_fd=old_stdout_fd, )
sys.stderr = _NamedTextIOWrapper( stream_mixer.stderr, encoding=self.charset, name="<stderr>", mode="w", errors="backslashreplace", original_fd=old_stderr_fd, )
@_pause_echo(echo_input) # type: ignore def visible_input(prompt: str | None = None) -> str: sys.stdout.write(prompt or "") try: val = next(text_input).rstrip("\r\n") except StopIteration as e: raise EOFError() from e sys.stdout.write(f"{val}\n") sys.stdout.flush() return val
@_pause_echo(echo_input) # type: ignore def hidden_input(prompt: str | None = None) -> str: sys.stdout.write(f"{prompt or ''}\n") sys.stdout.flush() try: return next(text_input).rstrip("\r\n") except StopIteration as e: raise EOFError() from e
@_pause_echo(echo_input) # type: ignore def _getchar(echo: bool) -> str: char = sys.stdin.read(1)
if echo: sys.stdout.write(char)
sys.stdout.flush() return char
default_color = color
def should_strip_ansi( stream: t.IO[t.Any] | None = None, color: bool | None = None ) -> bool: if color is None: return not default_color return not color
old_visible_prompt_func = termui.visible_prompt_func old_hidden_prompt_func = termui.hidden_prompt_func old__getchar_func = termui._getchar old_should_strip_ansi = utils.should_strip_ansi # type: ignore old__compat_should_strip_ansi = _compat.should_strip_ansi old_pdb_init = pdb.Pdb.__init__ termui.visible_prompt_func = visible_input termui.hidden_prompt_func = hidden_input termui._getchar = _getchar utils.should_strip_ansi = should_strip_ansi # type: ignore _compat.should_strip_ansi = should_strip_ansi
def _patched_pdb_init( self: pdb.Pdb, completekey: str = "tab", stdin: t.IO[str] | None = None, stdout: t.IO[str] | None = None, **kwargs: t.Any, ) -> None: """Default ``pdb.Pdb`` to real terminal streams during ``CliRunner`` isolation.
Without this patch, ``pdb.Pdb.__init__`` inherits from ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout`` when no explicit streams are provided. During isolation those are ``BytesIO``-backed wrappers, so the debugger reads from an empty buffer and writes to captured output, making interactive debugging impossible.
By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the original terminal streams Python preserves regardless of redirection), debuggers can interact with the user while ``click.echo`` output is still captured normally.
This covers ``pdb.set_trace()``, ``breakpoint()``, ``pdb.post_mortem()``, and debuggers that subclass ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout`` arguments are honored and not overridden. Debuggers that do not subclass ``pdb.Pdb`` (pudb, debugpy) are not covered. """ if stdin is None: stdin = sys.__stdin__ if stdout is None: stdout = sys.__stdout__ old_pdb_init( self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs )
pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment]
old_env = {} try: for key, value in env.items(): old_env[key] = os.environ.get(key) if value is None: try: del os.environ[key] except Exception: pass else: os.environ[key] = value yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output) finally: for key, value in old_env.items(): if value is None: try: del os.environ[key] except Exception: pass else: os.environ[key] = value sys.stdout = old_stdout sys.stderr = old_stderr sys.stdin = old_stdin termui.visible_prompt_func = old_visible_prompt_func termui.hidden_prompt_func = old_hidden_prompt_func termui._getchar = old__getchar_func utils.should_strip_ansi = old_should_strip_ansi # type: ignore _compat.should_strip_ansi = old__compat_should_strip_ansi formatting.FORCED_WIDTH = old_forced_width pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign]
def invoke( self, cli: Command, args: str | cabc.Sequence[str] | None = None, input: str | bytes | t.IO[t.Any] | None = None, env: cabc.Mapping[str, str | None] | None = None, catch_exceptions: bool | None = None, color: bool = False, **extra: t.Any, ) -> Result: """Invokes a command in an isolated environment. The arguments are forwarded directly to the command line script, the `extra` keyword arguments are passed to the :meth:`~clickpkg.Command.main` function of the command.
This returns a :class:`Result` object.
:param cli: the command to invoke :param args: the arguments to invoke. It may be given as an iterable or a string. When given as string it will be interpreted as a Unix shell command. More details at :func:`shlex.split`. :param input: the input data for `sys.stdin`. :param env: the environment overrides. :param catch_exceptions: Whether to catch any other exceptions than ``SystemExit``. If :data:`None`, the value from :class:`CliRunner` is used. :param extra: the keyword arguments to pass to :meth:`main`. :param color: whether the output should contain color codes. The application can still override this explicitly.
.. versionadded:: 8.2 The result object has the ``output_bytes`` attribute with the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would see it in its terminal.
.. versionchanged:: 8.2 The result object always returns the ``stderr_bytes`` stream.
.. versionchanged:: 8.0 The result object has the ``return_value`` attribute with the value returned from the invoked command.
.. versionchanged:: 4.0 Added the ``color`` parameter.
.. versionchanged:: 3.0 Added the ``catch_exceptions`` parameter.
.. versionchanged:: 3.0 The result object has the ``exc_info`` attribute with the traceback if available. """ exc_info = None if catch_exceptions is None: catch_exceptions = self.catch_exceptions
with self.isolation(input=input, env=env, color=color) as outstreams: return_value = None exception: BaseException | None = None exit_code = 0
if isinstance(args, str): args = shlex.split(args)
try: prog_name = extra.pop("prog_name") except KeyError: prog_name = self.get_default_prog_name(cli)
try: return_value = cli.main(args=args or (), prog_name=prog_name, **extra) except SystemExit as e: exc_info = sys.exc_info() e_code = t.cast("int | t.Any | None", e.code)
if e_code is None: e_code = 0
if e_code != 0: exception = e
if not isinstance(e_code, int): sys.stdout.write(str(e_code)) sys.stdout.write("\n") e_code = 1
exit_code = e_code
except Exception as e: if not catch_exceptions: raise exception = e exit_code = 1 exc_info = sys.exc_info() finally: sys.stdout.flush() sys.stderr.flush() stdout = outstreams[0].getvalue() stderr = outstreams[1].getvalue() output = outstreams[2].getvalue()
return Result( runner=self, stdout_bytes=stdout, stderr_bytes=stderr, output_bytes=output, return_value=return_value, exit_code=exit_code, exception=exception, exc_info=exc_info, # type: ignore )
@contextlib.contextmanager def isolated_filesystem( self, temp_dir: str | os.PathLike[str] | None = None ) -> cabc.Iterator[str]: """A context manager that creates a temporary directory and changes the current working directory to it. This isolates tests that affect the contents of the CWD to prevent them from interfering with each other.
:param temp_dir: Create the temporary directory under this directory. If given, the created directory is not removed when exiting.
.. versionchanged:: 8.0 Added the ``temp_dir`` parameter. """ cwd = os.getcwd() dt = tempfile.mkdtemp(dir=temp_dir) os.chdir(dt)
try: yield dt finally: os.chdir(cwd)
if temp_dir is None: import shutil
try: shutil.rmtree(dt) except OSError: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257Metadata-Version: 2.4Name: fsspecVersion: 2026.4.0Summary: File-system specificationProject-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.htmlProject-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/Project-URL: Homepage, https://github.com/fsspec/filesystem_specMaintainer-email: Martin Durant <mdurant@anaconda.com>License-Expression: BSD-3-ClauseLicense-File: LICENSEKeywords: fileClassifier: Development Status :: 4 - BetaClassifier: Intended Audience :: DevelopersClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Requires-Python: >=3.10Provides-Extra: abfsRequires-Dist: adlfs; extra == 'abfs'Provides-Extra: adlRequires-Dist: adlfs; extra == 'adl'Provides-Extra: arrowRequires-Dist: pyarrow>=1; extra == 'arrow'Provides-Extra: daskRequires-Dist: dask; extra == 'dask'Requires-Dist: distributed; extra == 'dask'Provides-Extra: devRequires-Dist: pre-commit; extra == 'dev'Requires-Dist: ruff>=0.5; extra == 'dev'Provides-Extra: docRequires-Dist: numpydoc; extra == 'doc'Requires-Dist: sphinx; extra == 'doc'Requires-Dist: sphinx-design; extra == 'doc'Requires-Dist: sphinx-rtd-theme; extra == 'doc'Requires-Dist: yarl; extra == 'doc'Provides-Extra: dropboxRequires-Dist: dropbox; extra == 'dropbox'Requires-Dist: dropboxdrivefs; extra == 'dropbox'Requires-Dist: requests; extra == 'dropbox'Provides-Extra: entrypointsProvides-Extra: fullRequires-Dist: adlfs; extra == 'full'Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full'Requires-Dist: dask; extra == 'full'Requires-Dist: distributed; extra == 'full'Requires-Dist: dropbox; extra == 'full'Requires-Dist: dropboxdrivefs; extra == 'full'Requires-Dist: fusepy; extra == 'full'Requires-Dist: gcsfs>2024.2.0; extra == 'full'Requires-Dist: libarchive-c; extra == 'full'Requires-Dist: ocifs; extra == 'full'Requires-Dist: panel; extra == 'full'Requires-Dist: paramiko; extra == 'full'Requires-Dist: pyarrow>=1; extra == 'full'Requires-Dist: pygit2; extra == 'full'Requires-Dist: requests; extra == 'full'Requires-Dist: s3fs>2024.2.0; extra == 'full'Requires-Dist: smbprotocol; extra == 'full'Requires-Dist: tqdm; extra == 'full'Provides-Extra: fuseRequires-Dist: fusepy; extra == 'fuse'Provides-Extra: gcsRequires-Dist: gcsfs>2024.2.0; extra == 'gcs'Provides-Extra: gitRequires-Dist: pygit2; extra == 'git'Provides-Extra: githubRequires-Dist: requests; extra == 'github'Provides-Extra: gsRequires-Dist: gcsfs; extra == 'gs'Provides-Extra: guiRequires-Dist: panel; extra == 'gui'Provides-Extra: hdfsRequires-Dist: pyarrow>=1; extra == 'hdfs'Provides-Extra: httpRequires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http'Provides-Extra: libarchiveRequires-Dist: libarchive-c; extra == 'libarchive'Provides-Extra: ociRequires-Dist: ocifs; extra == 'oci'Provides-Extra: s3Requires-Dist: s3fs>2024.2.0; extra == 's3'Provides-Extra: sftpRequires-Dist: paramiko; extra == 'sftp'Provides-Extra: smbRequires-Dist: smbprotocol; extra == 'smb'Provides-Extra: sshRequires-Dist: paramiko; extra == 'ssh'Provides-Extra: testRequires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test'Requires-Dist: numpy; extra == 'test'Requires-Dist: pytest; extra == 'test'Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test'Requires-Dist: pytest-benchmark; extra == 'test'Requires-Dist: pytest-cov; extra == 'test'Requires-Dist: pytest-mock; extra == 'test'Requires-Dist: pytest-recording; extra == 'test'Requires-Dist: pytest-rerunfailures; extra == 'test'Requires-Dist: requests; extra == 'test'Provides-Extra: test-downstreamRequires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream'Requires-Dist: dask[dataframe,test]; extra == 'test-downstream'Requires-Dist: moto[server]<5,>4; extra == 'test-downstream'Requires-Dist: pytest-timeout; extra == 'test-downstream'Requires-Dist: xarray; extra == 'test-downstream'Provides-Extra: test-fullRequires-Dist: adlfs; extra == 'test-full'Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full'Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full'Requires-Dist: cloudpickle; extra == 'test-full'Requires-Dist: dask; extra == 'test-full'Requires-Dist: distributed; extra == 'test-full'Requires-Dist: dropbox; extra == 'test-full'Requires-Dist: dropboxdrivefs; extra == 'test-full'Requires-Dist: fastparquet; extra == 'test-full'Requires-Dist: fusepy; extra == 'test-full'Requires-Dist: gcsfs; extra == 'test-full'Requires-Dist: jinja2; extra == 'test-full'Requires-Dist: kerchunk; extra == 'test-full'Requires-Dist: libarchive-c; extra == 'test-full'Requires-Dist: lz4; extra == 'test-full'Requires-Dist: notebook; extra == 'test-full'Requires-Dist: numpy; extra == 'test-full'Requires-Dist: ocifs; extra == 'test-full'Requires-Dist: pandas<3.0.0; extra == 'test-full'Requires-Dist: panel; extra == 'test-full'Requires-Dist: paramiko; extra == 'test-full'Requires-Dist: pyarrow; extra == 'test-full'Requires-Dist: pyarrow>=1; extra == 'test-full'Requires-Dist: pyftpdlib; extra == 'test-full'Requires-Dist: pygit2; extra == 'test-full'Requires-Dist: pytest; extra == 'test-full'Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full'Requires-Dist: pytest-benchmark; extra == 'test-full'Requires-Dist: pytest-cov; extra == 'test-full'Requires-Dist: pytest-mock; extra == 'test-full'Requires-Dist: pytest-recording; extra == 'test-full'Requires-Dist: pytest-rerunfailures; extra == 'test-full'Requires-Dist: python-snappy; extra == 'test-full'Requires-Dist: requests; extra == 'test-full'Requires-Dist: smbprotocol; extra == 'test-full'Requires-Dist: tqdm; extra == 'test-full'Requires-Dist: urllib3; extra == 'test-full'Requires-Dist: zarr; extra == 'test-full'Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full'Provides-Extra: tqdmRequires-Dist: tqdm; extra == 'tqdm'Description-Content-Type: text/markdown
# filesystem_spec
[](https://pypi.python.org/pypi/fsspec/)[](https://anaconda.org/conda-forge/fsspec)[](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
A specification for pythonic filesystems.
## Install
```bashpip install fsspec```
would install the base fsspec. Various optionally supported features might require specification of customextra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support.Use `pip install fsspec[full]` for installation of all known extra dependencies.
Up-to-date package also provided through conda-forge distribution:
```bashconda install -c conda-forge fsspec```
## Purpose
To produce a template or specification for a file-system interface, that specific implementations should follow,so that applications making use of them can rely on a common behaviour and not have to worry about the specificinternal implementation decisions with any given backend. Many such implementations are included in this package,or in sister projects such as `s3fs` and `gcsfs`.
In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSEmounting of the file-system implementation may be available for all implementations "for free".
## Documentation
Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest)
## Develop
fsspec uses GitHub Actions for CI. Environment files can be foundin the "ci/" directory. Note that the main environment is called "py38",but it is expected that the version of python installed be adjustable atCI runtime. For local use, pick a version suitable for you.
```bash# For a new environment (mamba / conda).mamba create -n fsspec -c conda-forge python=3.10 -yconda activate fsspec
# Standard dev install with docs and tests.pip install -e ".[dev,doc,test]"
# Full tests except for downstreampip install s3fspip uninstall s3fspip install -e .[dev,doc,test_full]pip install s3fs --no-depspytest -v
# Downstream tests.sh install_s3fs.sh# Windows powershell.install_s3fs.sh```
### Testing
Tests can be run in the dev environment, if activated, via ``pytest fsspec``.
The full fsspec suite requires a system-level docker, docker-compose, and fuseinstallation. If only making changes to one backend implementation, it isnot generally necessary to run all tests locally.
It is expected that contributors ensure that any change to fsspec does notcause issues or regressions for either other fsspec-related packages suchas gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CIrun and corresponding environment file run a set of tests from the dasktest suite, and very minimal tests against pandas and zarr from thetest_downstream.py module in this repo.
### Code Formatting
fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensurea consistent code format throughout the project.Run ``black fsspec`` from the root of the filesystem_spec repository toauto-format your code. Additionally, many editors have plugins that will apply``black`` as you edit files. ``black`` is included in the ``tox`` environments.
Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) toautomatically run ``black`` when you make a git commit.Run ``pre-commit install --install-hooks`` from the root of thefilesystem_spec repository to setup pre-commit hooks. ``black`` will now be runbefore you commit, reformatting any changed files. You can format withoutcommitting via ``pre-commit run`` or skip these checks with ``git commit--no-verify``.
## Support
Work on this repository is supported in part by:
"Anaconda, Inc. - Advancing AI through open source."
<a href="https://anaconda.com/"><img src="https://camo.githubusercontent.com/b8555ef2222598ed37ce38ac86955febbd25de7619931bb7dd3c58432181d3b6/68747470733a2f2f626565776172652e6f72672f636f6d6d756e6974792f6d656d626572732f616e61636f6e64612f616e61636f6e64612d6c617267652e706e67" alt="anaconda logo" width="40%"/></a>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324from functools import wraps
class Callback: """ Base class and interface for callback mechanism
This class can be used directly for monitoring file transfers by providing ``callback=Callback(hooks=...)`` (see the ``hooks`` argument, below), or subclassed for more specialised behaviour.
Parameters ---------- size: int (optional) Nominal quantity for the value that corresponds to a complete transfer, e.g., total number of tiles or total number of bytes value: int (0) Starting internal counter value hooks: dict or None A dict of named functions to be called on each update. The signature of these must be ``f(size, value, **kwargs)`` """
def __init__(self, size=None, value=0, hooks=None, **kwargs): self.size = size self.value = value self.hooks = hooks or {} self.kw = kwargs
def __enter__(self): return self
def __exit__(self, *exc_args): self.close()
def close(self): """Close callback."""
def branched(self, path_1, path_2, **kwargs): """ Return callback for child transfers
If this callback is operating at a higher level, e.g., put, which may trigger transfers that can also be monitored. The function returns a callback that has to be passed to the child method, e.g., put_file, as `callback=` argument.
The implementation uses `callback.branch` for compatibility. When implementing callbacks, it is recommended to override this function instead of `branch` and avoid calling `super().branched(...)`.
Prefer using this function over `branch`.
Parameters ---------- path_1: str Child's source path path_2: str Child's destination path **kwargs: Arbitrary keyword arguments
Returns ------- callback: Callback A callback instance to be passed to the child method """ self.branch(path_1, path_2, kwargs) # mutate kwargs so that we can force the caller to pass "callback=" explicitly return kwargs.pop("callback", DEFAULT_CALLBACK)
def branch_coro(self, fn): """ Wraps a coroutine, and pass a new child callback to it. """
@wraps(fn) async def func(path1, path2: str, **kwargs): with self.branched(path1, path2, **kwargs) as child: return await fn(path1, path2, callback=child, **kwargs)
return func
def set_size(self, size): """ Set the internal maximum size attribute
Usually called if not initially set at instantiation. Note that this triggers a ``call()``.
Parameters ---------- size: int """ self.size = size self.call()
def absolute_update(self, value): """ Set the internal value state
Triggers ``call()``
Parameters ---------- value: int """ self.value = value self.call()
def relative_update(self, inc=1): """ Delta increment the internal counter
Triggers ``call()``
Parameters ---------- inc: int """ self.value += inc self.call()
def call(self, hook_name=None, **kwargs): """ Execute hook(s) with current state
Each function is passed the internal size and current value
Parameters ---------- hook_name: str or None If given, execute on this hook kwargs: passed on to (all) hook(s) """ if not self.hooks: return kw = self.kw.copy() kw.update(kwargs) if hook_name: if hook_name not in self.hooks: return return self.hooks[hook_name](self.size, self.value, **kw) for hook in self.hooks.values() or []: hook(self.size, self.value, **kw)
def wrap(self, iterable): """ Wrap an iterable to call ``relative_update`` on each iterations
Parameters ---------- iterable: Iterable The iterable that is being wrapped """ for item in iterable: self.relative_update() yield item
def branch(self, path_1, path_2, kwargs): """ Set callbacks for child transfers
If this callback is operating at a higher level, e.g., put, which may trigger transfers that can also be monitored. The passed kwargs are to be *mutated* to add ``callback=``, if this class supports branching to children.
Parameters ---------- path_1: str Child's source path path_2: str Child's destination path kwargs: dict arguments passed to child method, e.g., put_file.
Returns -------
""" return None
def no_op(self, *_, **__): pass
def __getattr__(self, item): """ If undefined methods are called on this class, nothing happens """ return self.no_op
@classmethod def as_callback(cls, maybe_callback=None): """Transform callback=... into Callback instance
For the special value of ``None``, return the global instance of ``NoOpCallback``. This is an alternative to including ``callback=DEFAULT_CALLBACK`` directly in a method signature. """ if maybe_callback is None: return DEFAULT_CALLBACK return maybe_callback
class NoOpCallback(Callback): """ This implementation of Callback does exactly nothing """
def call(self, *args, **kwargs): return None
class DotPrinterCallback(Callback): """ Simple example Callback implementation
Almost identical to Callback with a hook that prints a char; here we demonstrate how the outer layer may print "#" and the inner layer "." """
def __init__(self, chr_to_print="#", **kwargs): self.chr = chr_to_print super().__init__(**kwargs)
def branch(self, path_1, path_2, kwargs): """Mutate kwargs to add new instance with different print char""" kwargs["callback"] = DotPrinterCallback(".")
def call(self, **kwargs): """Just outputs a character""" print(self.chr, end="")
class TqdmCallback(Callback): """ A callback to display a progress bar using tqdm
Parameters ---------- tqdm_kwargs : dict, (optional) Any argument accepted by the tqdm constructor. See the `tqdm doc <https://tqdm.github.io/docs/tqdm/#__init__>`_. Will be forwarded to `tqdm_cls`. tqdm_cls: (optional) subclass of `tqdm.tqdm`. If not passed, it will default to `tqdm.tqdm`.
Examples -------- >>> import fsspec >>> from fsspec.callbacks import TqdmCallback >>> fs = fsspec.filesystem("memory") >>> path2distant_data = "/your-path" >>> fs.upload( ".", path2distant_data, recursive=True, callback=TqdmCallback(), )
You can forward args to tqdm using the ``tqdm_kwargs`` parameter.
>>> fs.upload( ".", path2distant_data, recursive=True, callback=TqdmCallback(tqdm_kwargs={"desc": "Your tqdm description"}), )
You can also customize the progress bar by passing a subclass of `tqdm`.
.. code-block:: python
class TqdmFormat(tqdm): '''Provides a `total_time` format parameter''' @property def format_dict(self): d = super().format_dict total_time = d["elapsed"] * (d["total"] or 0) / max(d["n"], 1) d.update(total_time=self.format_interval(total_time) + " in total") return d
>>> with TqdmCallback( tqdm_kwargs={ "desc": "desc", "bar_format": "{total_time}: {percentage:.0f}%|{bar}{r_bar}", }, tqdm_cls=TqdmFormat, ) as callback: fs.upload(".", path2distant_data, recursive=True, callback=callback) """
def __init__(self, tqdm_kwargs=None, *args, **kwargs): try: from tqdm import tqdm
except ImportError as exce: raise ImportError( "Using TqdmCallback requires tqdm to be installed" ) from exce
self._tqdm_cls = kwargs.pop("tqdm_cls", tqdm) self._tqdm_kwargs = tqdm_kwargs or {} self.tqdm = None super().__init__(*args, **kwargs)
def call(self, *args, **kwargs): if self.tqdm is None: self.tqdm = self._tqdm_cls(total=self.size, **self._tqdm_kwargs) self.tqdm.total = self.size self.tqdm.update(self.value - self.tqdm.n)
def close(self): if self.tqdm is not None: self.tqdm.close() self.tqdm = None
def __del__(self): return self.close()
DEFAULT_CALLBACK = _DEFAULT_CALLBACK = NoOpCallback()123456789101112131415161718192021222324252627282930313233343536373839"""Regexps to match html elements"""
import re
attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*"
unquoted = "[^\"'=<>`\\x00-\\x20]+"single_quoted = "'[^']*'"double_quoted = '"[^"]*"'
attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")"
attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)"
open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>"
close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>"comment = "<!---?>|<!--(?:[^-]|-[^-]|--[^>])*-->"processing = "<[?][\\s\\S]*?[?]>"declaration = "<![A-Za-z][^>]*>"cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>"
HTML_TAG_RE = re.compile( "^(?:" + open_tag + "|" + close_tag + "|" + comment + "|" + processing + "|" + declaration + "|" + cdata + ")")HTML_OPEN_CLOSE_TAG_STR = "^(?:" + open_tag + "|" + close_tag + ")"HTML_OPEN_CLOSE_TAG_RE = re.compile(HTML_OPEN_CLOSE_TAG_STR)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313"""Utilities for parsing source text"""
from __future__ import annotations
import refrom re import Matchfrom typing import TypeVarimport unicodedata
from .entities import entities
def charCodeAt(src: str, pos: int) -> int | None: """ Returns the Unicode value of the character at the specified location.
@param - index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.
This was added for compatibility with python """ try: return ord(src[pos]) except IndexError: return None
def charStrAt(src: str, pos: int) -> str | None: """ Returns the Unicode value of the character at the specified location.
@param - index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned.
This was added for compatibility with python """ try: return src[pos] except IndexError: return None
_ItemTV = TypeVar("_ItemTV")
def arrayReplaceAt( src: list[_ItemTV], pos: int, newElements: list[_ItemTV]) -> list[_ItemTV]: """ Remove element from array and put another array at those position. Useful for some operations with tokens """ return src[:pos] + newElements + src[pos + 1 :]
def isValidEntityCode(c: int) -> bool: # broken sequence if c >= 0xD800 and c <= 0xDFFF: return False # never used if c >= 0xFDD0 and c <= 0xFDEF: return False if ((c & 0xFFFF) == 0xFFFF) or ((c & 0xFFFF) == 0xFFFE): return False # control codes if c >= 0x00 and c <= 0x08: return False if c == 0x0B: return False if c >= 0x0E and c <= 0x1F: return False if c >= 0x7F and c <= 0x9F: return False # out of range return not (c > 0x10FFFF)
def fromCodePoint(c: int) -> str: """Convert ordinal to unicode.
Note, in the original Javascript two string characters were required, for codepoints larger than `0xFFFF`. But Python 3 can represent any unicode codepoint in one character. """ return chr(c)
# UNESCAPE_MD_RE = re.compile(r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])')# ENTITY_RE_g = re.compile(r'&([a-z#][a-z0-9]{1,31})', re.IGNORECASE)UNESCAPE_ALL_RE = re.compile( r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])' + "|" + r"&([a-z#][a-z0-9]{1,31});", re.IGNORECASE,)DIGITAL_ENTITY_BASE10_RE = re.compile(r"#([0-9]{1,8})")DIGITAL_ENTITY_BASE16_RE = re.compile(r"#x([a-f0-9]{1,8})", re.IGNORECASE)
def replaceEntityPattern(match: str, name: str) -> str: """Convert HTML entity patterns, see https://spec.commonmark.org/0.30/#entity-references """ if name in entities: return entities[name]
code: None | int = None if pat := DIGITAL_ENTITY_BASE10_RE.fullmatch(name): code = int(pat.group(1), 10) elif pat := DIGITAL_ENTITY_BASE16_RE.fullmatch(name): code = int(pat.group(1), 16)
if code is not None and isValidEntityCode(code): return fromCodePoint(code)
return match
def unescapeAll(string: str) -> str: def replacer_func(match: Match[str]) -> str: escaped = match.group(1) if escaped: return escaped entity = match.group(2) return replaceEntityPattern(match.group(), entity)
if "\\" not in string and "&" not in string: return string return UNESCAPE_ALL_RE.sub(replacer_func, string)
ESCAPABLE = r"""\\!"#$%&'()*+,./:;<=>?@\[\]^`{}|_~-"""ESCAPE_CHAR = re.compile(r"\\([" + ESCAPABLE + r"])")
def stripEscape(string: str) -> str: """Strip escape \\ characters""" return ESCAPE_CHAR.sub(r"\1", string)
def escapeHtml(raw: str) -> str: """Replace special characters "&", "<", ">" and '"' to HTML-safe sequences.""" # like html.escape, but without escaping single quotes raw = raw.replace("&", "&") # Must be done first! raw = raw.replace("<", "<") raw = raw.replace(">", ">") raw = raw.replace('"', """) return raw
# //////////////////////////////////////////////////////////////////////////////
REGEXP_ESCAPE_RE = re.compile(r"[.?*+^$[\]\\(){}|-]")
def escapeRE(string: str) -> str: string = REGEXP_ESCAPE_RE.sub("\\$&", string) return string
# //////////////////////////////////////////////////////////////////////////////
def isSpace(code: int | None) -> bool: """Check if character code is a whitespace.""" return code in (0x09, 0x20)
def isStrSpace(ch: str | None) -> bool: """Check if character is a whitespace.""" return ch in ("\t", " ")
MD_WHITESPACE = { 0x09, # \t 0x0A, # \n 0x0B, # \v 0x0C, # \f 0x0D, # \r 0x20, # space 0xA0, 0x1680, 0x202F, 0x205F, 0x3000,}
def isWhiteSpace(code: int) -> bool: r"""Zs (unicode class) || [\t\f\v\r\n]""" if code >= 0x2000 and code <= 0x200A: return True return code in MD_WHITESPACE
# //////////////////////////////////////////////////////////////////////////////
def isPunctChar(ch: str) -> bool: """Check if character is a punctuation character.""" return unicodedata.category(ch).startswith(("P", "S"))
MD_ASCII_PUNCT = { 0x21, # /* ! */ 0x22, # /* " */ 0x23, # /* # */ 0x24, # /* $ */ 0x25, # /* % */ 0x26, # /* & */ 0x27, # /* ' */ 0x28, # /* ( */ 0x29, # /* ) */ 0x2A, # /* * */ 0x2B, # /* + */ 0x2C, # /* , */ 0x2D, # /* - */ 0x2E, # /* . */ 0x2F, # /* / */ 0x3A, # /* : */ 0x3B, # /* ; */ 0x3C, # /* < */ 0x3D, # /* = */ 0x3E, # /* > */ 0x3F, # /* ? */ 0x40, # /* @ */ 0x5B, # /* [ */ 0x5C, # /* \ */ 0x5D, # /* ] */ 0x5E, # /* ^ */ 0x5F, # /* _ */ 0x60, # /* ` */ 0x7B, # /* { */ 0x7C, # /* | */ 0x7D, # /* } */ 0x7E, # /* ~ */}
def isMdAsciiPunct(ch: int) -> bool: """Markdown ASCII punctuation characters.
::
!, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \\, ], ^, _, `, {, |, }, or ~
See http://spec.commonmark.org/0.15/#ascii-punctuation-character
Don't confuse with unicode punctuation !!! It lacks some chars in ascii range.
""" return ch in MD_ASCII_PUNCT
def normalizeReference(string: str) -> str: """Helper to unify [reference labels].""" # Trim and collapse whitespace # string = re.sub(r"\s+", " ", string.strip())
# In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug # fixed in v12 (couldn't find any details). # # So treat this one as a special case # (remove this when node v10 is no longer supported). # # if ('ẞ'.toLowerCase() === 'Ṿ') { # str = str.replace(/ẞ/g, 'ß') # }
# .toLowerCase().toUpperCase() should get rid of all differences # between letter variants. # # Simple .toLowerCase() doesn't normalize 125 code points correctly, # and .toUpperCase doesn't normalize 6 of them (list of exceptions: # İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently # uppercased versions). # # Here's an example showing how it happens. Lets take greek letter omega: # uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) # # Unicode entries: # 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8 # 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 # 03D1;GREEK THETA SYMBOL;Ll;0;L;<compat> 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 # 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L;<compat> 0398;;;;N;;;;03B8 # # Case-insensitive comparison should treat all of them as equivalent. # # But .toLowerCase() doesn't change ϑ (it's already lowercase), # and .toUpperCase() doesn't change ϴ (already uppercase). # # Applying first lower then upper case normalizes any character: # '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' # # Note: this is equivalent to unicode case folding; unicode normalization # is a different step that is not required here. # # Final result should be uppercased, because it's later stored in an object # (this avoid a conflict with Object.prototype members, # most notably, `__proto__`) # return string.lower().upper()
LINK_OPEN_RE = re.compile(r"^<a[>\s]", flags=re.IGNORECASE)LINK_CLOSE_RE = re.compile(r"^</a\s*>", flags=re.IGNORECASE)
def isLinkOpen(string: str) -> bool: return bool(LINK_OPEN_RE.search(string))
def isLinkClose(string: str) -> bool: return bool(LINK_CLOSE_RE.search(string))123456"""Functions for parsing Links"""
__all__ = ("parseLinkDestination", "parseLinkLabel", "parseLinkTitle")from .parse_link_destination import parseLinkDestinationfrom .parse_link_label import parseLinkLabelfrom .parse_link_title import parseLinkTitle123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475"""Parse link title"""
from ..common.utils import charCodeAt, unescapeAll
class _State: __slots__ = ("can_continue", "marker", "ok", "pos", "str")
def __init__(self) -> None: self.ok = False """if `true`, this is a valid link title""" self.can_continue = False """if `true`, this link can be continued on the next line""" self.pos = 0 """if `ok`, it's the position of the first character after the closing marker""" self.str = "" """if `ok`, it's the unescaped title""" self.marker = 0 """expected closing marker character code"""
def __str__(self) -> str: return self.str
def parseLinkTitle( string: str, start: int, maximum: int, prev_state: _State | None = None) -> _State: """Parse link title within `str` in [start, max] range, or continue previous parsing if `prev_state` is defined (equal to result of last execution). """ pos = start state = _State()
if prev_state is not None: # this is a continuation of a previous parseLinkTitle call on the next line, # used in reference links only state.str = prev_state.str state.marker = prev_state.marker else: if pos >= maximum: return state
marker = charCodeAt(string, pos)
# /* " */ /* ' */ /* ( */ if marker != 0x22 and marker != 0x27 and marker != 0x28: return state
start += 1 pos += 1
# if opening marker is "(", switch it to closing marker ")" if marker == 0x28: marker = 0x29
state.marker = marker
while pos < maximum: code = charCodeAt(string, pos) if code == state.marker: state.pos = pos + 1 state.str += unescapeAll(string[start:pos]) state.ok = True return state elif code == 0x28 and state.marker == 0x29: # /* ( */ /* ) */ return state elif code == 0x5C and pos + 1 < maximum: # /* \ */ pos += 1
pos += 1
# no closing marker found, but this link title may continue on the next line (for references) state.can_continue = True state.str += unescapeAll(string[start:pos]) return state12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""* class Core** Top-level rules executor. Glues block/inline parsers and does intermediate* transformations."""
from __future__ import annotations
from collections.abc import Callable
from .ruler import Rulerfrom .rules_core import ( block, inline, linkify, normalize, replace, smartquotes, text_join,)from .rules_core.state_core import StateCore
RuleFuncCoreType = Callable[[StateCore], None]
_rules: list[tuple[str, RuleFuncCoreType]] = [ ("normalize", normalize), ("block", block), ("inline", inline), ("linkify", linkify), ("replacements", replace), ("smartquotes", smartquotes), ("text_join", text_join),]
class ParserCore: def __init__(self) -> None: self.ruler = Ruler[RuleFuncCoreType]() for name, rule in _rules: self.ruler.push(name, rule)
def process(self, state: StateCore) -> None: """Executes core chain rules.""" for rule in self.ruler.getRules(""): rule(state)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748- package: markdown-it/markdown-it version: 14.1.0 commit: 0fe7ccb4b7f30236fb05f623be6924961d296d3d date: Mar 19, 2024 notes: - Rename variables that use python built-in names, e.g. - `max` -> `maximum` - `len` -> `length` - `str` -> `string` - | Convert JS `for` loops to `while` loops this is generally the main difference between the codes, because in python you can't do e.g. `for {i=1;i<x;i++} {}` - | `env` is a common Python dictionary, and so does not have attribute access to keys, as with JavaScript dictionaries. `options` have attribute access only to core markdownit configuration options - | `Token.attrs` is a dictionary, instead of a list of lists. Upstream the list format is only used to guarantee order: https://github.com/markdown-it/markdown-it/issues/142, but in Python 3.7+ order of dictionaries is guaranteed. One should anyhow use the `attrGet`, `attrSet`, `attrPush` and `attrJoin` methods to manipulate `Token.attrs`, which have an identical signature to those upstream. - Use python version of `charCodeAt` - | Use `str` units instead of `int`s to represent Unicode codepoints. This provides a significant performance boost - | In markdown_it/rules_block/reference.py, record line range in state.env["references"] and add state.env["duplicate_refs"] This is to allow renderers to report on issues regarding references - | The `MarkdownIt.__init__` signature is slightly different for updating options, since you must always specify the config first, e.g. use `MarkdownIt("commonmark", {"html": False})` instead of `MarkdownIt({"html": False})` - The default configuration preset for `MarkdownIt` is "commonmark" not "default" - Allow custom renderer to be passed to `MarkdownIt` - | change render method signatures `func(tokens, idx, options, env, slf)` to `func(self, tokens, idx, options, env)` - | Extensions add render methods by format `MarkdownIt.add_render_rule(name, function, fmt="html")`, rather than `MarkdownIt.renderer.rules[name] = function` and renderers should declare a class property `__output__ = "html"`. This allows for extensibility to more than just HTML renderers - inline tokens in tables are assigned a map (this is helpful for propagation to children)123456789101112131415161718192021222324252627282930313233343536"""markdown-it default options."""
from ..utils import PresetType
def make() -> PresetType: return { "options": { "maxNesting": 100, # Internal protection, recursion limit "html": False, # Enable HTML tags in source # this is just a shorthand for .disable(["html_inline", "html_block"]) # used by the linkify rule: "linkify": False, # autoconvert URL-like texts to links # used by the replacements and smartquotes rules: # Enable some language-neutral replacements + quotes beautification "typographer": False, # used by the smartquotes rule: # Double + single quotes replacement pairs, when typographer enabled, # and smartquotes on. Could be either a String or an Array. # For example, you can use '«»„“' for Russian, '„“‚‘' for German, # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ # Renderer specific; these options are used directly in the HTML renderer "xhtmlOut": False, # Use '/' to close single tags (<br />) "breaks": False, # Convert '\n' in paragraphs into <br> "langPrefix": "language-", # CSS language prefix for fenced blocks # Highlighter function. Should return escaped HTML, # or '' if the source string is not changed and should be escaped externally. # If result starts with <pre... internal wrapper is skipped. # # function (/*str, lang, attrs*/) { return ''; } # "highlight": None, }, "components": {"core": {}, "block": {}, "inline": {}}, }1234567891011121314151617181920212223242526272829303132333435363738394041424344""""Zero" preset, with nothing enabled. Useful for manual configuring of simplemodes. For example, to parse bold/italic only."""
from ..utils import PresetType
def make() -> PresetType: return { "options": { "maxNesting": 20, # Internal protection, recursion limit "html": False, # Enable HTML tags in source # this is just a shorthand for .disable(["html_inline", "html_block"]) # used by the linkify rule: "linkify": False, # autoconvert URL-like texts to links # used by the replacements and smartquotes rules: # Enable some language-neutral replacements + quotes beautification "typographer": False, # used by the smartquotes rule: # Double + single quotes replacement pairs, when typographer enabled, # and smartquotes on. Could be either a String or an Array. # For example, you can use '«»„“' for Russian, '„“‚‘' for German, # and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). "quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */ # Renderer specific; these options are used directly in the HTML renderer "xhtmlOut": False, # Use '/' to close single tags (<br />) "breaks": False, # Convert '\n' in paragraphs into <br> "langPrefix": "language-", # CSS language prefix for fenced blocks # Highlighter function. Should return escaped HTML, # or '' if the source string is not changed and should be escaped externally. # If result starts with <pre... internal wrapper is skipped. # function (/*str, lang, attrs*/) { return ''; } "highlight": None, }, "components": { "core": {"rules": ["normalize", "block", "inline", "text_join"]}, "block": {"rules": ["paragraph"]}, "inline": { "rules": ["text"], "rules2": ["balance_pairs", "fragments_join"], }, }, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""class Ruler
Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and[[MarkdownIt#inline]] to manage sequences of functions (rules):
- keep rules in defined order- assign the name to each rule- enable/disable rules- add/replace rules- allow assign rules to additional named chains (in the same)- caching lists of active rules
You will not need use this class directly until write plugins. For simplerules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and[[MarkdownIt.use]]."""
from __future__ import annotations
from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Generic, TypedDict, TypeVarimport warnings
from .utils import EnvType
if TYPE_CHECKING: from markdown_it import MarkdownIt
class StateBase: def __init__(self, src: str, md: MarkdownIt, env: EnvType): self.src = src self.env = env self.md = md
@property def src(self) -> str: return self._src
@src.setter def src(self, value: str) -> None: self._src = value self._srcCharCode: tuple[int, ...] | None = None
@property def srcCharCode(self) -> tuple[int, ...]: warnings.warn( "StateBase.srcCharCode is deprecated. Use StateBase.src instead.", DeprecationWarning, stacklevel=2, ) if self._srcCharCode is None: self._srcCharCode = tuple(ord(c) for c in self._src) return self._srcCharCode
class RuleOptionsType(TypedDict, total=False): alt: list[str]
RuleFuncTv = TypeVar("RuleFuncTv")"""A rule function, whose signature is dependent on the state type."""
@dataclass(slots=True)class Rule(Generic[RuleFuncTv]): name: str enabled: bool fn: RuleFuncTv = field(repr=False) alt: list[str]
class Ruler(Generic[RuleFuncTv]): def __init__(self) -> None: # List of added rules. self.__rules__: list[Rule[RuleFuncTv]] = [] # Cached rule chains. # First level - chain name, '' for default. # Second level - diginal anchor for fast filtering by charcodes. self.__cache__: dict[str, list[RuleFuncTv]] | None = None
def __find__(self, name: str) -> int: """Find rule index by name""" for i, rule in enumerate(self.__rules__): if rule.name == name: return i return -1
def __compile__(self) -> None: """Build rules lookup cache""" chains = {""} # collect unique names for rule in self.__rules__: if not rule.enabled: continue for name in rule.alt: chains.add(name) self.__cache__ = {} for chain in chains: self.__cache__[chain] = [] for rule in self.__rules__: if not rule.enabled: continue if chain and (chain not in rule.alt): continue self.__cache__[chain].append(rule.fn)
def at( self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None ) -> None: """Replace rule by name with new function & options.
:param ruleName: rule name to replace. :param fn: new rule function. :param options: new rule options (not mandatory). :raises: KeyError if name not found """ index = self.__find__(ruleName) options = options or {} if index == -1: raise KeyError(f"Parser rule not found: {ruleName}") self.__rules__[index].fn = fn self.__rules__[index].alt = options.get("alt", []) self.__cache__ = None
def before( self, beforeName: str, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None, ) -> None: """Add new rule to chain before one with given name.
:param beforeName: new rule will be added before this one. :param ruleName: new rule will be added before this one. :param fn: new rule function. :param options: new rule options (not mandatory). :raises: KeyError if name not found """ index = self.__find__(beforeName) options = options or {} if index == -1: raise KeyError(f"Parser rule not found: {beforeName}") self.__rules__.insert( index, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", [])) ) self.__cache__ = None
def after( self, afterName: str, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None, ) -> None: """Add new rule to chain after one with given name.
:param afterName: new rule will be added after this one. :param ruleName: new rule will be added after this one. :param fn: new rule function. :param options: new rule options (not mandatory). :raises: KeyError if name not found """ index = self.__find__(afterName) options = options or {} if index == -1: raise KeyError(f"Parser rule not found: {afterName}") self.__rules__.insert( index + 1, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", [])) ) self.__cache__ = None
def push( self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None ) -> None: """Push new rule to the end of chain.
:param ruleName: new rule will be added to the end of chain. :param fn: new rule function. :param options: new rule options (not mandatory).
""" self.__rules__.append( Rule[RuleFuncTv](ruleName, True, fn, (options or {}).get("alt", [])) ) self.__cache__ = None
def enable( self, names: str | Iterable[str], ignoreInvalid: bool = False ) -> list[str]: """Enable rules with given names.
:param names: name or list of rule names to enable. :param ignoreInvalid: ignore errors when rule not found :raises: KeyError if name not found and not ignoreInvalid :return: list of found rule names """ if isinstance(names, str): names = [names] result: list[str] = [] for name in names: idx = self.__find__(name) if (idx < 0) and ignoreInvalid: continue if (idx < 0) and not ignoreInvalid: raise KeyError(f"Rules manager: invalid rule name {name}") self.__rules__[idx].enabled = True result.append(name) self.__cache__ = None return result
def enableOnly( self, names: str | Iterable[str], ignoreInvalid: bool = False ) -> list[str]: """Enable rules with given names, and disable everything else.
:param names: name or list of rule names to enable. :param ignoreInvalid: ignore errors when rule not found :raises: KeyError if name not found and not ignoreInvalid :return: list of found rule names """ if isinstance(names, str): names = [names] for rule in self.__rules__: rule.enabled = False return self.enable(names, ignoreInvalid)
def disable( self, names: str | Iterable[str], ignoreInvalid: bool = False ) -> list[str]: """Disable rules with given names.
:param names: name or list of rule names to enable. :param ignoreInvalid: ignore errors when rule not found :raises: KeyError if name not found and not ignoreInvalid :return: list of found rule names """ if isinstance(names, str): names = [names] result = [] for name in names: idx = self.__find__(name) if (idx < 0) and ignoreInvalid: continue if (idx < 0) and not ignoreInvalid: raise KeyError(f"Rules manager: invalid rule name {name}") self.__rules__[idx].enabled = False result.append(name) self.__cache__ = None return result
def getRules(self, chainName: str = "") -> list[RuleFuncTv]: """Return array of active functions (rules) for given chain name. It analyzes rules configuration, compiles caches if not exists and returns result.
Default chain name is `''` (empty string). It can't be skipped. That's done intentionally, to keep signature monomorphic for high speed.
""" if self.__cache__ is None: self.__compile__() assert self.__cache__ is not None # Chain can be empty, if rules disabled. But we still have to return Array. return self.__cache__.get(chainName, []) or []
def get_all_rules(self) -> list[str]: """Return all available rule names.""" return [r.name for r in self.__rules__]
def get_active_rules(self) -> list[str]: """Return the active rule names.""" return [r.name for r in self.__rules__ if r.enabled]123456789101112131415161718192021222324252627__all__ = ( "StateBlock", "blockquote", "code", "fence", "heading", "hr", "html_block", "lheading", "list_block", "paragraph", "reference", "table",)
from .blockquote import blockquotefrom .code import codefrom .fence import fencefrom .heading import headingfrom .hr import hrfrom .html_block import html_blockfrom .lheading import lheadingfrom .list import list_blockfrom .paragraph import paragraphfrom .reference import referencefrom .state_block import StateBlockfrom .table import table123456789101112131415161718192021222324252627282930313233343536"""Code block (4 spaces padded)."""
import logging
from .state_block import StateBlock
LOGGER = logging.getLogger(__name__)
def code(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: LOGGER.debug("entering code: %s, %s, %s, %s", state, startLine, endLine, silent)
if not state.is_code_block(startLine): return False
last = nextLine = startLine + 1
while nextLine < endLine: if state.isEmpty(nextLine): nextLine += 1 continue
if state.is_code_block(nextLine): nextLine += 1 last = nextLine continue
break
state.line = last
token = state.push("code_block", "code", 0) token.content = state.getLines(startLine, last, 4 + state.blkIndent, False) + "\n" token.map = [startLine, state.line]
return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# fences (``` lang, ~~~ lang)import logging
from .state_block import StateBlock
LOGGER = logging.getLogger(__name__)
def fence(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: LOGGER.debug("entering fence: %s, %s, %s, %s", state, startLine, endLine, silent)
haveEndMarker = False pos = state.bMarks[startLine] + state.tShift[startLine] maximum = state.eMarks[startLine]
if state.is_code_block(startLine): return False
if pos + 3 > maximum: return False
marker = state.src[pos]
if marker not in ("~", "`"): return False
# scan marker length mem = pos pos = state.skipCharsStr(pos, marker)
length = pos - mem
if length < 3: return False
markup = state.src[mem:pos] params = state.src[pos:maximum]
if marker == "`" and marker in params: return False
# Since start is found, we can report success here in validation mode if silent: return True
# search end of block nextLine = startLine
while True: nextLine += 1 if nextLine >= endLine: # unclosed block should be autoclosed by end of document. # also block seems to be autoclosed by end of parent break
pos = mem = state.bMarks[nextLine] + state.tShift[nextLine] maximum = state.eMarks[nextLine]
if pos < maximum and state.sCount[nextLine] < state.blkIndent: # non-empty line with negative indent should stop the list: # - ``` # test break
try: if state.src[pos] != marker: continue except IndexError: break
if state.is_code_block(nextLine): continue
pos = state.skipCharsStr(pos, marker)
# closing code fence must be at least as long as the opening one if pos - mem < length: continue
# make sure tail has spaces only pos = state.skipSpaces(pos)
if pos < maximum: continue
haveEndMarker = True # found! break
# If a fence has heading spaces, they should be removed from its inner block length = state.sCount[startLine]
state.line = nextLine + (1 if haveEndMarker else 0)
token = state.push("fence", "code", 0) token.info = params token.content = state.getLines(startLine + 1, nextLine, length, True) token.markup = markup token.map = [startLine, state.line]
return True1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""Horizontal rule
At least 3 of these characters on a line * - _"""
import logging
from ..common.utils import isStrSpacefrom .state_block import StateBlock
LOGGER = logging.getLogger(__name__)
def hr(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: LOGGER.debug("entering hr: %s, %s, %s, %s", state, startLine, endLine, silent)
pos = state.bMarks[startLine] + state.tShift[startLine] maximum = state.eMarks[startLine]
if state.is_code_block(startLine): return False
try: marker = state.src[pos] except IndexError: return False pos += 1
# Check hr marker if marker not in ("*", "-", "_"): return False
# markers can be mixed with spaces, but there should be at least 3 of them
cnt = 1 while pos < maximum: ch = state.src[pos] pos += 1 if ch != marker and not isStrSpace(ch): return False if ch == marker: cnt += 1
if cnt < 3: return False
if silent: return True
state.line = startLine + 1
token = state.push("hr", "hr", 0) token.map = [startLine, state.line] token.markup = marker * (cnt + 1)
return True1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# lheading (---, ==)import logging
from .state_block import StateBlock
LOGGER = logging.getLogger(__name__)
def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: LOGGER.debug("entering lheading: %s, %s, %s, %s", state, startLine, endLine, silent)
level = None nextLine = startLine + 1 ruler = state.md.block.ruler terminatorRules = ruler.getRules("paragraph")
if state.is_code_block(startLine): return False
oldParentType = state.parentType state.parentType = "paragraph" # use paragraph to match terminatorRules
# jump line-by-line until empty one or EOF while nextLine < endLine and not state.isEmpty(nextLine): # this would be a code block normally, but after paragraph # it's considered a lazy continuation regardless of what's there if state.sCount[nextLine] - state.blkIndent > 3: nextLine += 1 continue
# Check for underline in setext header if state.sCount[nextLine] >= state.blkIndent: pos = state.bMarks[nextLine] + state.tShift[nextLine] maximum = state.eMarks[nextLine]
if pos < maximum: marker = state.src[pos]
if marker in ("-", "="): pos = state.skipCharsStr(pos, marker) pos = state.skipSpaces(pos)
# /* = */ if pos >= maximum: level = 1 if marker == "=" else 2 break
# quirk for blockquotes, this line should already be checked by that rule if state.sCount[nextLine] < 0: nextLine += 1 continue
# Some tags can terminate paragraph without empty line. terminate = False for terminatorRule in terminatorRules: if terminatorRule(state, nextLine, endLine, True): terminate = True break if terminate: break
nextLine += 1
if not level: # Didn't find valid underline return False
content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
state.line = nextLine + 1
token = state.push("heading_open", "h" + str(level), 1) token.markup = marker token.map = [startLine, state.line]
token = state.push("inline", "", 0) token.content = content token.map = [startLine, state.line - 1] token.children = []
token = state.push("heading_close", "h" + str(level), -1) token.markup = marker
state.parentType = oldParentType
return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345# Listsimport logging
from ..common.utils import isStrSpacefrom .state_block import StateBlock
LOGGER = logging.getLogger(__name__)
# Search `[-+*][\n ]`, returns next pos after marker on success# or -1 on fail.def skipBulletListMarker(state: StateBlock, startLine: int) -> int: pos = state.bMarks[startLine] + state.tShift[startLine] maximum = state.eMarks[startLine]
try: marker = state.src[pos] except IndexError: return -1 pos += 1
if marker not in ("*", "-", "+"): return -1
if pos < maximum: ch = state.src[pos]
if not isStrSpace(ch): # " -test " - is not a list item return -1
return pos
# Search `\d+[.)][\n ]`, returns next pos after marker on success# or -1 on fail.def skipOrderedListMarker(state: StateBlock, startLine: int) -> int: start = state.bMarks[startLine] + state.tShift[startLine] pos = start maximum = state.eMarks[startLine]
# List marker should have at least 2 chars (digit + dot) if pos + 1 >= maximum: return -1
ch = state.src[pos] pos += 1
ch_ord = ord(ch) # /* 0 */ /* 9 */ if ch_ord < 0x30 or ch_ord > 0x39: return -1
while True: # EOL -> fail if pos >= maximum: return -1
ch = state.src[pos] pos += 1
# /* 0 */ /* 9 */ ch_ord = ord(ch) if ch_ord >= 0x30 and ch_ord <= 0x39: # List marker should have no more than 9 digits # (prevents integer overflow in browsers) if pos - start >= 10: return -1
continue
# found valid marker if ch in (")", "."): break
return -1
if pos < maximum: ch = state.src[pos]
if not isStrSpace(ch): # " 1.test " - is not a list item return -1
return pos
def markTightParagraphs(state: StateBlock, idx: int) -> None: level = state.level + 2
i = idx + 2 length = len(state.tokens) - 2 while i < length: if state.tokens[i].level == level and state.tokens[i].type == "paragraph_open": state.tokens[i + 2].hidden = True state.tokens[i].hidden = True i += 2 i += 1
def list_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: LOGGER.debug("entering list: %s, %s, %s, %s", state, startLine, endLine, silent)
isTerminatingParagraph = False tight = True
if state.is_code_block(startLine): return False
# Special case: # - item 1 # - item 2 # - item 3 # - item 4 # - this one is a paragraph continuation if ( state.listIndent >= 0 and state.sCount[startLine] - state.listIndent >= 4 and state.sCount[startLine] < state.blkIndent ): return False
# limit conditions when list can interrupt # a paragraph (validation mode only) # Next list item should still terminate previous list item # # This code can fail if plugins use blkIndent as well as lists, # but I hope the spec gets fixed long before that happens. # if ( silent and state.parentType == "paragraph" and state.sCount[startLine] >= state.blkIndent ): isTerminatingParagraph = True
# Detect list type and position after marker posAfterMarker = skipOrderedListMarker(state, startLine) if posAfterMarker >= 0: isOrdered = True start = state.bMarks[startLine] + state.tShift[startLine] markerValue = int(state.src[start : posAfterMarker - 1])
# If we're starting a new ordered list right after # a paragraph, it should start with 1. if isTerminatingParagraph and markerValue != 1: return False else: posAfterMarker = skipBulletListMarker(state, startLine) if posAfterMarker >= 0: isOrdered = False else: return False
# If we're starting a new unordered list right after # a paragraph, first line should not be empty. if ( isTerminatingParagraph and state.skipSpaces(posAfterMarker) >= state.eMarks[startLine] ): return False
# We should terminate list on style change. Remember first one to compare. markerChar = state.src[posAfterMarker - 1]
# For validation mode we can terminate immediately if silent: return True
# Start list listTokIdx = len(state.tokens)
if isOrdered: token = state.push("ordered_list_open", "ol", 1) if markerValue != 1: token.attrs = {"start": markerValue}
else: token = state.push("bullet_list_open", "ul", 1)
token.map = listLines = [startLine, 0] token.markup = markerChar
# # Iterate list items #
nextLine = startLine prevEmptyEnd = False terminatorRules = state.md.block.ruler.getRules("list")
oldParentType = state.parentType state.parentType = "list"
while nextLine < endLine: pos = posAfterMarker maximum = state.eMarks[nextLine]
initial = offset = ( state.sCount[nextLine] + posAfterMarker - (state.bMarks[startLine] + state.tShift[startLine]) )
while pos < maximum: ch = state.src[pos]
if ch == "\t": offset += 4 - (offset + state.bsCount[nextLine]) % 4 elif ch == " ": offset += 1 else: break
pos += 1
contentStart = pos
# trimming space in "- \n 3" case, indent is 1 here indentAfterMarker = 1 if contentStart >= maximum else offset - initial
# If we have more than 4 spaces, the indent is 1 # (the rest is just indented code block) if indentAfterMarker > 4: indentAfterMarker = 1
# " - test" # ^^^^^ - calculating total length of this thing indent = initial + indentAfterMarker
# Run subparser & write tokens token = state.push("list_item_open", "li", 1) token.markup = markerChar token.map = itemLines = [startLine, 0] if isOrdered: token.info = state.src[start : posAfterMarker - 1]
# change current state, then restore it after parser subcall oldTight = state.tight oldTShift = state.tShift[startLine] oldSCount = state.sCount[startLine]
# - example list # ^ listIndent position will be here # ^ blkIndent position will be here # oldListIndent = state.listIndent state.listIndent = state.blkIndent state.blkIndent = indent
state.tight = True state.tShift[startLine] = contentStart - state.bMarks[startLine] state.sCount[startLine] = offset
if contentStart >= maximum and state.isEmpty(startLine + 1): # workaround for this case # (list item is empty, list terminates before "foo"): # ~~~~~~~~ # - # # foo # ~~~~~~~~ state.line = min(state.line + 2, endLine) else: # NOTE in list.js this was: # state.md.block.tokenize(state, startLine, endLine, True) # but tokeniz does not take the final parameter state.md.block.tokenize(state, startLine, endLine)
# If any of list item is tight, mark list as tight if (not state.tight) or prevEmptyEnd: tight = False
# Item become loose if finish with empty line, # but we should filter last element, because it means list finish prevEmptyEnd = (state.line - startLine) > 1 and state.isEmpty(state.line - 1)
state.blkIndent = state.listIndent state.listIndent = oldListIndent state.tShift[startLine] = oldTShift state.sCount[startLine] = oldSCount state.tight = oldTight
token = state.push("list_item_close", "li", -1) token.markup = markerChar
nextLine = startLine = state.line itemLines[1] = nextLine
if nextLine >= endLine: break
contentStart = state.bMarks[startLine]
# # Try to check if list is terminated or continued. # if state.sCount[nextLine] < state.blkIndent: break
if state.is_code_block(startLine): break
# fail if terminating block found terminate = False for terminatorRule in terminatorRules: if terminatorRule(state, nextLine, endLine, True): terminate = True break
if terminate: break
# fail if list has another type if isOrdered: posAfterMarker = skipOrderedListMarker(state, nextLine) if posAfterMarker < 0: break start = state.bMarks[nextLine] + state.tShift[nextLine] else: posAfterMarker = skipBulletListMarker(state, nextLine) if posAfterMarker < 0: break
if markerChar != state.src[posAfterMarker - 1]: break
# Finalize list if isOrdered: token = state.push("ordered_list_close", "ol", -1) else: token = state.push("bullet_list_close", "ul", -1)
token.markup = markerChar
listLines[1] = nextLine state.line = nextLine
state.parentType = oldParentType
# mark paragraphs tight if needed if tight: markTightParagraphs(state, listTokIdx)
return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Paragraph."""
import logging
from .state_block import StateBlock
LOGGER = logging.getLogger(__name__)
def paragraph(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: LOGGER.debug( "entering paragraph: %s, %s, %s, %s", state, startLine, endLine, silent )
nextLine = startLine + 1 ruler = state.md.block.ruler terminatorRules = ruler.getRules("paragraph") endLine = state.lineMax
oldParentType = state.parentType state.parentType = "paragraph"
# jump line-by-line until empty one or EOF while nextLine < endLine: if state.isEmpty(nextLine): break # this would be a code block normally, but after paragraph # it's considered a lazy continuation regardless of what's there if state.sCount[nextLine] - state.blkIndent > 3: nextLine += 1 continue
# quirk for blockquotes, this line should already be checked by that rule if state.sCount[nextLine] < 0: nextLine += 1 continue
# Some tags can terminate paragraph without empty line. terminate = False for terminatorRule in terminatorRules: if terminatorRule(state, nextLine, endLine, True): terminate = True break
if terminate: break
nextLine += 1
content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
state.line = nextLine
token = state.push("paragraph_open", "p", 1) token.map = [startLine, state.line]
token = state.push("inline", "", 0) token.content = content token.map = [startLine, state.line] token.children = []
token = state.push("paragraph_close", "p", -1)
state.parentType = oldParentType
return True12345678910111213141516171819__all__ = ( "StateCore", "block", "inline", "linkify", "normalize", "replace", "smartquotes", "text_join",)
from .block import blockfrom .inline import inlinefrom .linkify import linkifyfrom .normalize import normalizefrom .replacements import replacefrom .smartquotes import smartquotesfrom .state_core import StateCorefrom .text_join import text_join123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149from __future__ import annotations
import refrom typing import Protocol
from ..common.utils import arrayReplaceAt, isLinkClose, isLinkOpenfrom ..token import Tokenfrom .state_core import StateCore
HTTP_RE = re.compile(r"^http://")MAILTO_RE = re.compile(r"^mailto:")TEST_MAILTO_RE = re.compile(r"^mailto:", flags=re.IGNORECASE)
def linkify(state: StateCore) -> None: """Rule for identifying plain-text links.""" if not state.md.options.linkify: return
if not state.md.linkify: raise ModuleNotFoundError("Linkify enabled but not installed.")
for inline_token in state.tokens: if inline_token.type != "inline" or not state.md.linkify.pretest( inline_token.content ): continue
tokens = inline_token.children
htmlLinkLevel = 0
# We scan from the end, to keep position when new tags added. # Use reversed logic in links start/end match assert tokens is not None i = len(tokens) while i >= 1: i -= 1 assert isinstance(tokens, list) currentToken = tokens[i]
# Skip content of markdown links if currentToken.type == "link_close": i -= 1 while ( tokens[i].level != currentToken.level and tokens[i].type != "link_open" ): i -= 1 continue
# Skip content of html tag links if currentToken.type == "html_inline": if isLinkOpen(currentToken.content) and htmlLinkLevel > 0: htmlLinkLevel -= 1 if isLinkClose(currentToken.content): htmlLinkLevel += 1 if htmlLinkLevel > 0: continue
if currentToken.type == "text" and state.md.linkify.test( currentToken.content ): text = currentToken.content links: list[_LinkType] = state.md.linkify.match(text) or []
# Now split string to nodes nodes = [] level = currentToken.level lastPos = 0
# forbid escape sequence at the start of the string, # this avoids http\://example.com/ from being linkified as # http:<a href="//example.com/">//example.com/</a> if ( links and links[0].index == 0 and i > 0 and tokens[i - 1].type == "text_special" ): links = links[1:]
for link in links: url = link.url fullUrl = state.md.normalizeLink(url) if not state.md.validateLink(fullUrl): continue
urlText = link.text
# Linkifier might send raw hostnames like "example.com", where url # starts with domain name. So we prepend http:// in those cases, # and remove it afterwards. if not link.schema: urlText = HTTP_RE.sub( "", state.md.normalizeLinkText("http://" + urlText) ) elif link.schema == "mailto:" and TEST_MAILTO_RE.search(urlText): urlText = MAILTO_RE.sub( "", state.md.normalizeLinkText("mailto:" + urlText) ) else: urlText = state.md.normalizeLinkText(urlText)
pos = link.index
if pos > lastPos: token = Token("text", "", 0) token.content = text[lastPos:pos] token.level = level nodes.append(token)
token = Token("link_open", "a", 1) token.attrs = {"href": fullUrl} token.level = level level += 1 token.markup = "linkify" token.info = "auto" nodes.append(token)
token = Token("text", "", 0) token.content = urlText token.level = level nodes.append(token)
token = Token("link_close", "a", -1) level -= 1 token.level = level token.markup = "linkify" token.info = "auto" nodes.append(token)
lastPos = link.last_index
if lastPos < len(text): token = Token("text", "", 0) token.content = text[lastPos:] token.level = level nodes.append(token)
inline_token.children = tokens = arrayReplaceAt(tokens, i, nodes)
class _LinkType(Protocol): url: str text: str index: int last_index: int schema: str | None12345678910111213141516171819"""Normalize input string."""
import re
from .state_core import StateCore
# https://spec.commonmark.org/0.29/#line-endingNEWLINES_RE = re.compile(r"\r\n?|\n")NULL_RE = re.compile(r"\0")
def normalize(state: StateCore) -> None: # Normalize newlines string = NEWLINES_RE.sub("\n", state.src)
# Replace NULL characters string = NULL_RE.sub("\ufffd", string)
state.src = string1234567891011121314151617181920212223242526272829303132333435"""Join raw text tokens with the rest of the text
This is set as a separate rule to provide an opportunity for pluginsto run text replacements after text join, but before escape join.
For example, `\\:)` shouldn't be replaced with an emoji."""
from __future__ import annotations
from ..token import Tokenfrom .state_core import StateCore
def text_join(state: StateCore) -> None: """Join raw text for escape sequences (`text_special`) tokens with the rest of the text"""
for inline_token in state.tokens[:]: if inline_token.type != "inline": continue
# convert text_special to text and join all adjacent text nodes new_tokens: list[Token] = [] for child_token in inline_token.children or []: if child_token.type == "text_special": child_token.type = "text" if ( child_token.type == "text" and new_tokens and new_tokens[-1].type == "text" ): new_tokens[-1].content += child_token.content else: new_tokens.append(child_token) inline_token.children = new_tokens123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172# Parse backticksimport re
from .state_inline import StateInline
regex = re.compile("^ (.+) $")
def backtick(state: StateInline, silent: bool) -> bool: pos = state.pos
if state.src[pos] != "`": return False
start = pos pos += 1 maximum = state.posMax
# scan marker length while pos < maximum and (state.src[pos] == "`"): pos += 1
marker = state.src[start:pos] openerLength = len(marker)
if state.backticksScanned and state.backticks.get(openerLength, 0) <= start: if not silent: state.pending += marker state.pos += openerLength return True
matchStart = matchEnd = pos
# Nothing found in the cache, scan until the end of the line (or until marker is found) while True: try: matchStart = state.src.index("`", matchEnd) except ValueError: break matchEnd = matchStart + 1
# scan marker length while matchEnd < maximum and (state.src[matchEnd] == "`"): matchEnd += 1
closerLength = matchEnd - matchStart
if closerLength == openerLength: # Found matching closer length. if not silent: token = state.push("code_inline", "code", 0) token.markup = marker token.content = state.src[pos:matchStart].replace("\n", " ") if ( token.content.startswith(" ") and token.content.endswith(" ") and len(token.content.strip()) > 0 ): token.content = token.content[1:-1] state.pos = matchEnd return True
# Some different length found, put it in cache as upper limit of where closer can be found state.backticks[closerLength] = matchStart
# Scanned through the end, didn't find anything state.backticksScanned = True
if not silent: state.pending += marker state.pos += openerLength return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Balance paired characters (*, _, etc) in inline tokens."""
from __future__ import annotations
from .state_inline import Delimiter, StateInline
def processDelimiters(state: StateInline, delimiters: list[Delimiter]) -> None: """For each opening emphasis-like marker find a matching closing one.""" if not delimiters: return
openersBottom = {} maximum = len(delimiters)
# headerIdx is the first delimiter of the current (where closer is) delimiter run headerIdx = 0 lastTokenIdx = -2 # needs any value lower than -1 jumps: list[int] = [] closerIdx = 0 while closerIdx < maximum: closer = delimiters[closerIdx]
jumps.append(0)
# markers belong to same delimiter run if: # - they have adjacent tokens # - AND markers are the same # if ( delimiters[headerIdx].marker != closer.marker or lastTokenIdx != closer.token - 1 ): headerIdx = closerIdx lastTokenIdx = closer.token
# Length is only used for emphasis-specific "rule of 3", # if it's not defined (in strikethrough or 3rd party plugins), # we can default it to 0 to disable those checks. # closer.length = closer.length or 0
if not closer.close: closerIdx += 1 continue
# Previously calculated lower bounds (previous fails) # for each marker, each delimiter length modulo 3, # and for whether this closer can be an opener; # https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 if closer.marker not in openersBottom: openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]
minOpenerIdx = openersBottom[closer.marker][ (3 if closer.open else 0) + (closer.length % 3) ]
openerIdx = headerIdx - jumps[headerIdx] - 1
newMinOpenerIdx = openerIdx
while openerIdx > minOpenerIdx: opener = delimiters[openerIdx]
if opener.marker != closer.marker: openerIdx -= jumps[openerIdx] + 1 continue
if opener.open and opener.end < 0: isOddMatch = False
# from spec: # # If one of the delimiters can both open and close emphasis, then the # sum of the lengths of the delimiter runs containing the opening and # closing delimiters must not be a multiple of 3 unless both lengths # are multiples of 3. # if ( (opener.close or closer.open) and ((opener.length + closer.length) % 3 == 0) and (opener.length % 3 != 0 or closer.length % 3 != 0) ): isOddMatch = True
if not isOddMatch: # If previous delimiter cannot be an opener, we can safely skip # the entire sequence in future checks. This is required to make # sure algorithm has linear complexity (see *_*_*_*_*_... case). # if openerIdx > 0 and not delimiters[openerIdx - 1].open: lastJump = jumps[openerIdx - 1] + 1 else: lastJump = 0
jumps[closerIdx] = closerIdx - openerIdx + lastJump jumps[openerIdx] = lastJump
closer.open = False opener.end = closerIdx opener.close = False newMinOpenerIdx = -1
# treat next token as start of run, # it optimizes skips in **<...>**a**<...>** pathological case lastTokenIdx = -2
break
openerIdx -= jumps[openerIdx] + 1
if newMinOpenerIdx != -1: # If match for this delimiter run failed, we want to set lower bound for # future lookups. This is required to make sure algorithm has linear # complexity. # # See details here: # https:#github.com/commonmark/cmark/issues/178#issuecomment-270417442 # openersBottom[closer.marker][ (3 if closer.open else 0) + ((closer.length or 0) % 3) ] = newMinOpenerIdx
closerIdx += 1
def link_pairs(state: StateInline) -> None: tokens_meta = state.tokens_meta maximum = len(state.tokens_meta)
processDelimiters(state, state.delimiters)
curr = 0 while curr < maximum: curr_meta = tokens_meta[curr] if curr_meta and "delimiters" in curr_meta: processDelimiters(state, curr_meta["delimiters"]) curr += 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Process *this* and _that_#from __future__ import annotations
from .state_inline import Delimiter, StateInline
def tokenize(state: StateInline, silent: bool) -> bool: """Insert each marker as a separate text token, and add it to delimiter list""" start = state.pos marker = state.src[start]
if silent: return False
if marker not in ("_", "*"): return False
scanned = state.scanDelims(state.pos, marker == "*")
for _ in range(scanned.length): token = state.push("text", "", 0) token.content = marker state.delimiters.append( Delimiter( marker=ord(marker), length=scanned.length, token=len(state.tokens) - 1, end=-1, open=scanned.can_open, close=scanned.can_close, ) )
state.pos += scanned.length
return True
def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None: i = len(delimiters) - 1 while i >= 0: startDelim = delimiters[i]
# /* _ */ /* * */ if startDelim.marker != 0x5F and startDelim.marker != 0x2A: i -= 1 continue
# Process only opening markers if startDelim.end == -1: i -= 1 continue
endDelim = delimiters[startDelim.end]
# If the previous delimiter has the same marker and is adjacent to this one, # merge those into one strong delimiter. # # `<em><em>whatever</em></em>` -> `<strong>whatever</strong>` # isStrong = ( i > 0 and delimiters[i - 1].end == startDelim.end + 1 # check that first two markers match and adjacent and delimiters[i - 1].marker == startDelim.marker and delimiters[i - 1].token == startDelim.token - 1 # check that last two markers are adjacent (we can safely assume they match) and delimiters[startDelim.end + 1].token == endDelim.token + 1 )
ch = chr(startDelim.marker)
token = state.tokens[startDelim.token] token.type = "strong_open" if isStrong else "em_open" token.tag = "strong" if isStrong else "em" token.nesting = 1 token.markup = ch + ch if isStrong else ch token.content = ""
token = state.tokens[endDelim.token] token.type = "strong_close" if isStrong else "em_close" token.tag = "strong" if isStrong else "em" token.nesting = -1 token.markup = ch + ch if isStrong else ch token.content = ""
if isStrong: state.tokens[delimiters[i - 1].token].content = "" state.tokens[delimiters[startDelim.end + 1].token].content = "" i -= 1
i -= 1
def postProcess(state: StateInline) -> None: """Walk through delimiter list and replace text tokens with tags.""" _postProcess(state, state.delimiters)
for token in state.tokens_meta: if token and "delimiters" in token: _postProcess(state, token["delimiters"])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Process links like https://example.org/"""
import re
from .state_inline import StateInline
# RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )SCHEME_RE = re.compile(r"(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$", re.IGNORECASE)
def linkify(state: StateInline, silent: bool) -> bool: """Rule for identifying plain-text links.""" if not state.md.options.linkify: return False if state.linkLevel > 0: return False if not state.md.linkify: raise ModuleNotFoundError("Linkify enabled but not installed.")
pos = state.pos maximum = state.posMax
if ( (pos + 3) > maximum or state.src[pos] != ":" or state.src[pos + 1] != "/" or state.src[pos + 2] != "/" ): return False
if not (match := SCHEME_RE.search(state.pending)): return False
proto = match.group(1) if not (link := state.md.linkify.match_at_start(state.src[pos - len(proto) :])): return False url: str = link.url
# disallow '*' at the end of the link (conflicts with emphasis) url = url.rstrip("*")
full_url = state.md.normalizeLink(url) if not state.md.validateLink(full_url): return False
if not silent: state.pending = state.pending[: -len(proto)]
token = state.push("link_open", "a", 1) token.attrs = {"href": full_url} token.markup = "linkify" token.info = "auto"
token = state.push("text", "", 0) token.content = state.md.normalizeLinkText(url)
token = state.push("link_close", "a", -1) token.markup = "linkify" token.info = "auto"
state.pos += len(url) - len(proto) return True1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Proceess '\n'."""
from ..common.utils import charStrAt, isStrSpacefrom .state_inline import StateInline
def newline(state: StateInline, silent: bool) -> bool: pos = state.pos
if state.src[pos] != "\n": return False
pmax = len(state.pending) - 1 maximum = state.posMax
# ' \n' -> hardbreak # Lookup in pending chars is bad practice! Don't copy to other rules! # Pending string is stored in concat mode, indexed lookups will cause # conversion to flat mode. if not silent: if pmax >= 0 and charStrAt(state.pending, pmax) == " ": if pmax >= 1 and charStrAt(state.pending, pmax - 1) == " ": # Find whitespaces tail of pending chars. ws = pmax - 1 while ws >= 1 and charStrAt(state.pending, ws - 1) == " ": ws -= 1 state.pending = state.pending[:ws]
state.push("hardbreak", "br", 0) else: state.pending = state.pending[:-1] state.push("softbreak", "br", 0)
else: state.push("softbreak", "br", 0)
pos += 1
# skip heading spaces for next line while pos < maximum and isStrSpace(state.src[pos]): pos += 1
state.pos = pos return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178from __future__ import annotations
from collections.abc import Callable, MutableMappingimport dataclasses as dcfrom typing import Any, Literalimport warnings
def convert_attrs(value: Any) -> Any: """Convert Token.attrs set as ``None`` or ``[[key, value], ...]`` to a dict.
This improves compatibility with upstream markdown-it. """ if not value: return {} if isinstance(value, list): return dict(value) return value
@dc.dataclass(slots=True)class Token: type: str """Type of the token (string, e.g. "paragraph_open")"""
tag: str """HTML tag name, e.g. 'p'"""
nesting: Literal[-1, 0, 1] """Level change (number in {-1, 0, 1} set), where: - `1` means the tag is opening - `0` means the tag is self-closing - `-1` means the tag is closing """
attrs: dict[str, str | int | float] = dc.field(default_factory=dict) """HTML attributes. Note this differs from the upstream "list of lists" format, although than an instance can still be initialised with this format. """
map: list[int] | None = None """Source map info. Format: `[ line_begin, line_end ]`"""
level: int = 0 """Nesting level, the same as `state.level`"""
children: list[Token] | None = None """Array of child nodes (inline and img tokens)."""
content: str = "" """Inner content, in the case of a self-closing tag (code, html, fence, etc.),"""
markup: str = "" """'*' or '_' for emphasis, fence string for fence, etc."""
info: str = "" """Additional information: - Info string for "fence" tokens - The value "auto" for autolink "link_open" and "link_close" tokens - The string value of the item marker for ordered-list "list_item_open" tokens """
meta: dict[Any, Any] = dc.field(default_factory=dict) """A place for plugins to store any arbitrary data"""
block: bool = False """True for block-level tokens, false for inline tokens. Used in renderer to calculate line breaks """
hidden: bool = False """If true, ignore this element when rendering. Used for tight lists to hide paragraphs. """
def __post_init__(self) -> None: self.attrs = convert_attrs(self.attrs)
def attrIndex(self, name: str) -> int: warnings.warn( # noqa: B028 "Token.attrIndex should not be used, since Token.attrs is a dictionary", UserWarning, ) if name not in self.attrs: return -1 return list(self.attrs.keys()).index(name)
def attrItems(self) -> list[tuple[str, str | int | float]]: """Get (key, value) list of attrs.""" return list(self.attrs.items())
def attrPush(self, attrData: tuple[str, str | int | float]) -> None: """Add `[ name, value ]` attribute to list. Init attrs if necessary.""" name, value = attrData self.attrSet(name, value)
def attrSet(self, name: str, value: str | int | float) -> None: """Set `name` attribute to `value`. Override old value if exists.""" self.attrs[name] = value
def attrGet(self, name: str) -> None | str | int | float: """Get the value of attribute `name`, or null if it does not exist.""" return self.attrs.get(name, None)
def attrJoin(self, name: str, value: str) -> None: """Join value to existing attribute via space. Or create new attribute if not exists. Useful to operate with token classes. """ if name in self.attrs: current = self.attrs[name] if not isinstance(current, str): raise TypeError( f"existing attr 'name' is not a str: {self.attrs[name]}" ) self.attrs[name] = f"{current} {value}" else: self.attrs[name] = value
def copy(self, **changes: Any) -> Token: """Return a shallow copy of the instance.""" return dc.replace(self, **changes)
def as_dict( self, *, children: bool = True, as_upstream: bool = True, meta_serializer: Callable[[dict[Any, Any]], Any] | None = None, filter: Callable[[str, Any], bool] | None = None, dict_factory: Callable[..., MutableMapping[str, Any]] = dict, ) -> MutableMapping[str, Any]: """Return the token as a dictionary.
:param children: Also convert children to dicts :param as_upstream: Ensure the output dictionary is equal to that created by markdown-it For example, attrs are converted to null or lists :param meta_serializer: hook for serializing ``Token.meta`` :param filter: A callable whose return code determines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the (key, value) pair. :param dict_factory: A callable to produce dictionaries from. For example, to produce ordered dictionaries instead of normal Python dictionaries, pass in ``collections.OrderedDict``.
""" mapping = dict_factory((f.name, getattr(self, f.name)) for f in dc.fields(self)) if filter: mapping = dict_factory((k, v) for k, v in mapping.items() if filter(k, v)) if as_upstream and "attrs" in mapping: mapping["attrs"] = ( None if not mapping["attrs"] else [[k, v] for k, v in mapping["attrs"].items()] ) if meta_serializer and "meta" in mapping: mapping["meta"] = meta_serializer(mapping["meta"]) if children and mapping.get("children", None): mapping["children"] = [ child.as_dict( children=children, filter=filter, dict_factory=dict_factory, as_upstream=as_upstream, meta_serializer=meta_serializer, ) for child in mapping["children"] ] return mapping
@classmethod def from_dict(cls, dct: MutableMapping[str, Any]) -> Token: """Convert a dict to a Token.""" token = cls(**dct) if token.children: token.children = [cls.from_dict(c) for c in token.children] # type: ignore[arg-type] return token1234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any123[console_scripts]markdown-it=markdown_it.cli.parse:main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204Metadata-Version: 2.4Name: idnaVersion: 3.13Summary: Internationalized Domain Names in Applications (IDNA)Author-email: Kim Davies <kim+pypi@gumleaf.org>Requires-Python: >=3.8Description-Content-Type: text/x-rstLicense-Expression: BSD-3-ClauseClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Intended Audience :: System AdministratorsClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Classifier: Programming Language :: Python :: Implementation :: CPythonClassifier: Programming Language :: Python :: Implementation :: PyPyClassifier: Topic :: Internet :: Name Service (DNS)Classifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: UtilitiesLicense-File: LICENSE.mdRequires-Dist: ruff >= 0.6.2 ; extra == "all"Requires-Dist: mypy >= 1.11.2 ; extra == "all"Requires-Dist: pytest >= 8.3.2 ; extra == "all"Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.rstProject-URL: Issue tracker, https://github.com/kjd/idna/issuesProject-URL: Source, https://github.com/kjd/idnaProvides-Extra: all
Internationalized Domain Names in Applications (IDNA)=====================================================
Support for `Internationalized Domain Names inApplications (IDNA) <https://tools.ietf.org/html/rfc5891>`_and `Unicode IDNA Compatibility Processing<https://unicode.org/reports/tr46/>`_.
The latest versions of these standards supplied here providemore comprehensive language coverage and reduce the potential ofallowing domains with known security vulnerabilities. This libraryis a suitable replacement for the “encodings.idna”module that comes with the Python standard library, but whichonly supports an older superseded IDNA specification from 2003.
Basic functions are simply executed:
.. code-block:: pycon
>>> import idna >>> idna.encode('ドメイン.テスト') b'xn--eckwd4c7c.xn--zckzah' >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) ドメイン.テスト
Installation------------
This package is available for installation from PyPI via thetypical mechanisms, such as:
.. code-block:: bash
$ python3 -m pip install idna
Usage-----
For typical usage, the ``encode`` and ``decode`` functions will take adomain name argument and perform a conversion to ASCII-compatible encoding(known as A-labels), or to Unicode strings (known as U-labels)respectively.
.. code-block:: pycon
>>> import idna >>> idna.encode('ドメイン.テスト') b'xn--eckwd4c7c.xn--zckzah' >>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) ドメイン.テスト
Conversions can be applied at a per-label basis using the ``ulabel`` or``alabel`` functions if necessary:
.. code-block:: pycon
>>> idna.alabel('测试') b'xn--0zwm56d'
Compatibility Mapping (UTS #46)+++++++++++++++++++++++++++++++
This library provides support for `Unicode IDNA CompatibilityProcessing <https://unicode.org/reports/tr46/>`_ which normalizes input fromdifferent potential ways a user may input a domain prior to performing the IDNAconversion operations. This functionality, known as a `mapping <https://tools.ietf.org/html/rfc5895>`_, is considered by thespecification to be a local user-interface issue distinct from IDNAconversion functionality.
For example, “Königsgäßchen” is not a permissible label as *LATINCAPITAL LETTER K* is not allowed (nor are capital letters in general).UTS 46 will convert this into lower case prior to applying the IDNAconversion.
.. code-block:: pycon
>>> import idna >>> idna.encode('Königsgäßchen') ... idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed >>> idna.encode('Königsgäßchen', uts46=True) b'xn--knigsgchen-b4a3dun' >>> print(idna.decode('xn--knigsgchen-b4a3dun')) königsgäßchen
Exceptions----------
All errors raised during the conversion following the specificationshould raise an exception derived from the ``idna.IDNAError`` baseclass.
More specific exceptions that may be generated as ``idna.IDNABidiError``when the error reflects an illegal combination of left-to-right andright-to-left characters in a label; ``idna.InvalidCodepoint`` whena specific codepoint is an illegal character in an IDN label (i.e.INVALID); and ``idna.InvalidCodepointContext`` when the codepoint isillegal based on its position in the string (i.e. it is CONTEXTO or CONTEXTJbut the contextual requirements are not satisfied.)
Building and Diagnostics------------------------
The IDNA and UTS 46 functionality relies upon pre-calculated lookuptables for performance. These tables are derived from computing againsteligibility criteria in the respective standards using the command-linescript ``tools/idna-data``.
This tool will fetch relevant codepoint data from the Unicode repositoryand perform the required calculations to identify eligibility. There arethree main modes:
* ``idna-data make-libdata``. Generates ``idnadata.py`` and ``uts46data.py``, the pre-calculated lookup tables used for IDNA and UTS 46 conversions. Implementers who wish to track this library against a different Unicode version may use this tool to manually generate a different version of the ``idnadata.py`` and ``uts46data.py`` files.
* ``idna-data make-table``. Generate a table of the IDNA disposition (e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix B.1 of RFC 5892 and the pre-computed tables published by `IANA <https://www.iana.org/>`_.
* ``idna-data U+0061``. Prints debugging output on the various properties associated with an individual Unicode codepoint (in this case, U+0061), that are used to assess the IDNA and UTS 46 status of a codepoint. This is helpful in debugging or analysis.
The tool accepts a number of arguments, described using ``idna-data -h``.Most notably, the ``--version`` argument allows the specificationof the version of Unicode to be used in computing the table data. Forexample, ``idna-data --version 9.0.0 make-libdata`` will generatelibrary data against Unicode 9.0.0.
Additional Notes----------------
* **Packages**. The latest tagged release version is published in the `Python Package Index <https://pypi.org/project/idna/>`_.
* **Version support**. This library supports Python 3.8 and higher. As this library serves as a low-level toolkit for a variety of applications, many of which strive for broad compatibility with older Python versions, there is no rush to remove older interpreter support. Support for older versions are likely to be removed from new releases as automated tests can no longer easily be run, i.e. once the Python version is officially end-of-life.
* **Testing**. The library has a test suite based on each rule of the IDNA specification, as well as tests that are provided as part of the Unicode Technical Standard 46, `Unicode IDNA Compatibility Processing <https://unicode.org/reports/tr46/>`_.
* **Emoji**. It is an occasional request to support emoji domains in this library. Encoding of symbols like emoji is expressly prohibited by the IDNA technical standard, and emoji domains are broadly phased out across the domain industry due to associated security risks.
* **Transitional processing**. Unicode 16.0.0 removed transitional processing so the `transitional` argument for the encode() method no longer has any effect and will be removed at a later date.
123456789101112131415161718192021222324252627packaging/__init__.py,sha256=QhMEdPu2XogrJzV3S0KWS6t7l0I9k8EeDRJl4fnw87s,494packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707packaging/_parser.py,sha256=Kf2nsDw4c54X82pY8ba4F02Bve6OygGMAjL-Begqcew,11698packaging/_structures.py,sha256=60jRbF78p8z5MKnNd6cAprgOadCJHV0DlmUmRBqFZcs,1109packaging/_tokenizer.py,sha256=tFU2Wr-ZZJdAbkXLEJo7qUQDJaIkfft9DqaifiEND7A,5391packaging/dependency_groups.py,sha256=XZIAVFK9uHG4RCGprmJn3VInUWMesxha_kytJuMO9eY,10218packaging/direct_url.py,sha256=eKmbDiPP1sLV4Mj_kCSZqqknrIyVO9Sr7JpF8KCjp4U,10917packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680packaging/markers.py,sha256=8fDIUhAF6YMnCNB5FSiwh9pEIusiFzAF73J-0OB8bTk,17055packaging/metadata.py,sha256=crAh0E3GVGVqPlu6EdRFsaG-Y6UYznTUqjuGKRGPv6c,38770packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0packaging/pylock.py,sha256=G_1gncTmDbRLY1jo4VDI9Uw-b5IErh_Q9V_BbVJTmD8,33890packaging/requirements.py,sha256=dd1c9aa1gp5NI6btF6UFRQjPn1nxQXnE_T34yDDTEpc,4383packaging/specifiers.py,sha256=Mfp8avQg0lVot17to9lVKBtZD1FsWBTItoGwFUZ3wtg,71514packaging/tags.py,sha256=NQ1weo69_Sjte3xBZ1I_G63CIgCmaN0C24mz-z3hGYo,34224packaging/utils.py,sha256=M7-JMKic2sP1YtV_8aW7eVGB-x3ADuKCiSrsVeCd2Uo,9848packaging/version.py,sha256=Y1aTtxe3sn2xOMa5BdI85-AcHuybbanOVkEvvSRRC8I,38369packaging/licenses/__init__.py,sha256=_Jx0XRiD_58palsWnyLrLuh59ZpGCPIPXLKdZo9OJvQ,7293packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122packaging-26.2.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197packaging-26.2.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174packaging-26.2.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344packaging-26.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82packaging-26.2.dist-info/METADATA,sha256=T5y815M0FaR5P3dnyYoralEsgj_IHIczeBVwXyMOyr8,3543packaging-26.2.dist-info/RECORD,,123456789101112131415# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
__title__ = "packaging"__summary__ = "Core utilities for Python packages"__uri__ = "https://github.com/pypa/packaging"
__version__ = "26.2"
__author__ = "Donald Stufft and individual contributors"__email__ = "donald@stufft.io"
__license__ = "BSD-2-Clause or Apache-2.0"__copyright__ = f"2014 {__author__}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393"""Handwritten parser of dependency specifiers.
The docstring for each __parse_* function contains EBNF-inspired grammar representingthe implementation."""
from __future__ import annotations
import astfrom typing import List, Literal, NamedTuple, Sequence, Tuple, Union
from ._tokenizer import DEFAULT_RULES, Tokenizer
class Node: __slots__ = ("value",)
def __init__(self, value: str) -> None: self.value = value
def __str__(self) -> str: return self.value
def __repr__(self) -> str: return f"<{self.__class__.__name__}({self.value!r})>"
def serialize(self) -> str: raise NotImplementedError
def __getstate__(self) -> str: # Return just the value string for compactness and stability. return self.value
def _restore_value(self, value: object) -> None: if not isinstance(value, str): raise TypeError( f"Cannot restore {self.__class__.__name__} value from {value!r}" ) self.value = value
def __setstate__(self, state: object) -> None: if isinstance(state, str): # New format (26.2+): just the value string. self._restore_value(state) return if isinstance(state, tuple) and len(state) == 2: # Old format (packaging <= 26.0, __slots__): (None, {slot: value}). _, slot_dict = state if isinstance(slot_dict, dict) and "value" in slot_dict: self._restore_value(slot_dict["value"]) return if isinstance(state, dict) and "value" in state: # Old format (packaging <= 25.0, no __slots__): plain __dict__. self._restore_value(state["value"]) return raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}")
class Variable(Node): __slots__ = ()
def serialize(self) -> str: return str(self)
class Value(Node): __slots__ = ()
def serialize(self) -> str: return f'"{self}"'
class Op(Node): __slots__ = ()
def serialize(self) -> str: return str(self)
MarkerLogical = Literal["and", "or"]MarkerVar = Union[Variable, Value]MarkerItem = Tuple[MarkerVar, Op, MarkerVar]MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
class ParsedRequirement(NamedTuple): name: str url: str extras: list[str] specifier: str marker: MarkerList | None
# --------------------------------------------------------------------------------------# Recursive descent parser for dependency specifier# --------------------------------------------------------------------------------------def parse_requirement(source: str) -> ParsedRequirement: return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: """ requirement = WS? IDENTIFIER WS? extras WS? requirement_details """ tokenizer.consume("WS")
name_token = tokenizer.expect( "IDENTIFIER", expected="package name at the start of dependency specifier" ) name = name_token.text tokenizer.consume("WS")
extras = _parse_extras(tokenizer) tokenizer.consume("WS")
url, specifier, marker = _parse_requirement_details(tokenizer) tokenizer.expect("END", expected="end of dependency specifier")
return ParsedRequirement(name, url, extras, specifier, marker)
def _parse_requirement_details( tokenizer: Tokenizer,) -> tuple[str, str, MarkerList | None]: """ requirement_details = AT URL (WS requirement_marker?)? | specifier WS? (requirement_marker)? """
specifier = "" url = "" marker = None
if tokenizer.check("AT"): tokenizer.read() tokenizer.consume("WS")
url_start = tokenizer.position url = tokenizer.expect("URL", expected="URL after @").text if tokenizer.check("END", peek=True): return (url, specifier, marker)
tokenizer.expect("WS", expected="whitespace after URL")
# The input might end after whitespace. if tokenizer.check("END", peek=True): return (url, specifier, marker)
marker = _parse_requirement_marker( tokenizer, span_start=url_start, expected="semicolon (after URL and whitespace)", ) else: specifier_start = tokenizer.position specifier = _parse_specifier(tokenizer) tokenizer.consume("WS")
if tokenizer.check("END", peek=True): return (url, specifier, marker)
marker = _parse_requirement_marker( tokenizer, span_start=specifier_start, expected=( "comma (within version specifier), semicolon (after version specifier)" if specifier else "semicolon (after name with no version specifier)" ), )
return (url, specifier, marker)
def _parse_requirement_marker( tokenizer: Tokenizer, *, span_start: int, expected: str) -> MarkerList: """ requirement_marker = SEMICOLON marker WS? """
if not tokenizer.check("SEMICOLON"): tokenizer.raise_syntax_error( f"Expected {expected} or end", span_start=span_start, span_end=None, ) tokenizer.read()
marker = _parse_marker(tokenizer) tokenizer.consume("WS")
return marker
def _parse_extras(tokenizer: Tokenizer) -> list[str]: """ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? """ if not tokenizer.check("LEFT_BRACKET", peek=True): return []
with tokenizer.enclosing_tokens( "LEFT_BRACKET", "RIGHT_BRACKET", around="extras", ): tokenizer.consume("WS") extras = _parse_extras_list(tokenizer) tokenizer.consume("WS")
return extras
def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: """ extras_list = identifier (wsp* ',' wsp* identifier)* """ extras: list[str] = []
if not tokenizer.check("IDENTIFIER"): return extras
extras.append(tokenizer.read().text)
while True: tokenizer.consume("WS") if tokenizer.check("IDENTIFIER", peek=True): tokenizer.raise_syntax_error("Expected comma between extra names") elif not tokenizer.check("COMMA"): break
tokenizer.read() tokenizer.consume("WS")
extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") extras.append(extra_token.text)
return extras
def _parse_specifier(tokenizer: Tokenizer) -> str: """ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS | WS? version_many WS? """ with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="version specifier", ): tokenizer.consume("WS") parsed_specifiers = _parse_version_many(tokenizer) tokenizer.consume("WS")
return parsed_specifiers
def _parse_version_many(tokenizer: Tokenizer) -> str: """ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? """ parsed_specifiers = "" while tokenizer.check("SPECIFIER"): span_start = tokenizer.position parsed_specifiers += tokenizer.read().text if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): tokenizer.raise_syntax_error( ".* suffix can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position + 1, ) if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): tokenizer.raise_syntax_error( "Local version label can only be used with `==` or `!=` operators", span_start=span_start, span_end=tokenizer.position, ) tokenizer.consume("WS") if not tokenizer.check("COMMA"): break parsed_specifiers += tokenizer.read().text tokenizer.consume("WS")
return parsed_specifiers
# --------------------------------------------------------------------------------------# Recursive descent parser for marker expression# --------------------------------------------------------------------------------------def parse_marker(source: str) -> MarkerList: return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: retval = _parse_marker(tokenizer) tokenizer.expect("END", expected="end of marker expression") return retval
def _parse_marker(tokenizer: Tokenizer) -> MarkerList: """ marker = marker_atom (BOOLOP marker_atom)+ """ expression = [_parse_marker_atom(tokenizer)] while tokenizer.check("BOOLOP"): token = tokenizer.read() expr_right = _parse_marker_atom(tokenizer) expression.extend((token.text, expr_right)) return expression
def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: """ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? | WS? marker_item WS? """
tokenizer.consume("WS") if tokenizer.check("LEFT_PARENTHESIS", peek=True): with tokenizer.enclosing_tokens( "LEFT_PARENTHESIS", "RIGHT_PARENTHESIS", around="marker expression", ): tokenizer.consume("WS") marker: MarkerAtom = _parse_marker(tokenizer) tokenizer.consume("WS") else: marker = _parse_marker_item(tokenizer) tokenizer.consume("WS") return marker
def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: """ marker_item = WS? marker_var WS? marker_op WS? marker_var WS? """ tokenizer.consume("WS") marker_var_left = _parse_marker_var(tokenizer) tokenizer.consume("WS") marker_op = _parse_marker_op(tokenizer) tokenizer.consume("WS") marker_var_right = _parse_marker_var(tokenizer) tokenizer.consume("WS") return (marker_var_left, marker_op, marker_var_right)
def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503 """ marker_var = VARIABLE | QUOTED_STRING """ if tokenizer.check("VARIABLE"): return process_env_var(tokenizer.read().text.replace(".", "_")) elif tokenizer.check("QUOTED_STRING"): return process_python_str(tokenizer.read().text) else: tokenizer.raise_syntax_error( message="Expected a marker variable or quoted string" )
def process_env_var(env_var: str) -> Variable: if env_var in ("platform_python_implementation", "python_implementation"): return Variable("platform_python_implementation") else: return Variable(env_var)
def process_python_str(python_str: str) -> Value: value = ast.literal_eval(python_str) return Value(str(value))
def _parse_marker_op(tokenizer: Tokenizer) -> Op: """ marker_op = IN | NOT IN | OP """ if tokenizer.check("IN"): tokenizer.read() return Op("in") elif tokenizer.check("NOT"): tokenizer.read() tokenizer.expect("WS", expected="whitespace after 'not'") tokenizer.expect("IN", expected="'in' after 'not'") return Op("not in") elif tokenizer.check("OP"): return Op(tokenizer.read().text) else: return tokenizer.raise_syntax_error( "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" )123456789101112131415161718192021222324252627282930313233# This file is dual licensed under the terms of the Apache License, Version# 2.0, and the BSD License. See the LICENSE file in the root of this repository# for complete details.
"""Backward-compatibility shim for unpickling Version objects serialized beforepackaging 26.1.
Old pickles reference ``packaging._structures.InfinityType`` and``packaging._structures.NegativeInfinityType``. This module provides minimalstand-in classes so that ``pickle.loads()`` can resolve those references.The deserialized objects are not used for comparisons — ``Version.__setstate__``discards the stale ``_key`` cache and recomputes it from the core version fields."""
from __future__ import annotations
class InfinityType: """Stand-in for the removed ``InfinityType`` used in old comparison keys."""
def __repr__(self) -> str: return "Infinity"
class NegativeInfinityType: """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys."""
def __repr__(self) -> str: return "-Infinity"
Infinity = InfinityType()NegativeInfinity = NegativeInfinityType()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302from __future__ import annotations
import refrom collections.abc import Mapping, Sequence
from .errors import _ErrorCollectorfrom .requirements import Requirement
__all__ = [ "CyclicDependencyGroup", "DependencyGroupInclude", "DependencyGroupResolver", "DuplicateGroupNames", "InvalidDependencyGroupObject", "resolve_dependency_groups",]
def __dir__() -> list[str]: return __all__
# -----------# Error Types# -----------
class DuplicateGroupNames(ValueError): """ The same dependency groups were defined twice, with different non-normalized names. """
class CyclicDependencyGroup(ValueError): """ The dependency group includes form a cycle. """
def __init__(self, requested_group: str, group: str, include_group: str) -> None: self.requested_group = requested_group self.group = group self.include_group = include_group
if include_group == group: reason = f"{group} includes itself" else: reason = f"{include_group} -> {group}, {group} -> {include_group}" super().__init__( "Cyclic dependency group include while resolving " f"{requested_group}: {reason}" )
# in the PEP 735 spec, the tables in dependency group lists were described as# "Dependency Object Specifiers", but the only defined type of object was a# "Dependency Group Include" -- hence the naming of this error as "Object"class InvalidDependencyGroupObject(ValueError): """ A member of a dependency group was identified as a dict, but was not in a valid format. """
# ------------------------# Object Model & Interface# ------------------------
class DependencyGroupInclude: __slots__ = ("include_group",)
def __init__(self, include_group: str) -> None: """ Initialize a DependencyGroupInclude.
:param include_group: The name of the group referred to by this include. """ self.include_group = include_group
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.include_group!r})"
class DependencyGroupResolver: """ A resolver for Dependency Group data.
This class handles caching, name normalization, cycle detection, and other parsing requirements. There are only two public methods for exploring the data: ``lookup()`` and ``resolve()``.
:param dependency_groups: A mapping, as provided via pyproject ``[dependency-groups]``. """
def __init__( self, dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], ) -> None: errors = _ErrorCollector()
self.dependency_groups = _normalize_group_names(dependency_groups, errors)
# a map of group names to parsed data self._parsed_groups: dict[ str, tuple[Requirement | DependencyGroupInclude, ...] ] = {} # a map of group names to their ancestors, used for cycle detection self._include_graph_ancestors: dict[str, tuple[str, ...]] = {} # a cache of completed resolutions to Requirement lists self._resolve_cache: dict[str, tuple[Requirement, ...]] = {}
errors.finalize("[dependency-groups] data was invalid")
def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]: """ Lookup a group name, returning the parsed dependency data for that group. This will not resolve includes.
:param group: the name of the group to lookup """ group = _normalize_name(group)
with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._parse_group(group, errors)
def resolve(self, group: str) -> tuple[Requirement, ...]: """ Resolve a dependency group to a list of requirements.
:param group: the name of the group to resolve """ group = _normalize_name(group)
with _ErrorCollector().on_exit( f"[dependency-groups] data for {group!r} was malformed" ) as errors: return self._resolve(group, group, errors)
def _resolve( self, group: str, requested_group: str, errors: _ErrorCollector ) -> tuple[Requirement, ...]: """ This is a helper for cached resolution to strings. It preserves the name of the group which the user initially requested in order to present a clearer error in the event that a cycle is detected.
:param group: The normalized name of the group to resolve. :param requested_group: The group which was used in the original, user-facing request. """ if group in self._resolve_cache: return self._resolve_cache[group]
parsed = self._parse_group(group, errors)
resolved_group = []
for item in parsed: if isinstance(item, Requirement): resolved_group.append(item) elif isinstance(item, DependencyGroupInclude): include_group = _normalize_name(item.include_group)
# if a group is cyclic, record the error # otherwise, follow the include_group reference # # this allows us to examine all includes in a group, even in the # presence of errors if include_group in self._include_graph_ancestors.get(group, ()): errors.error( CyclicDependencyGroup( requested_group, group, item.include_group ) ) else: self._include_graph_ancestors[include_group] = ( *self._include_graph_ancestors.get(group, ()), group, ) resolved_group.extend( self._resolve(include_group, requested_group, errors) ) else: # pragma: no cover raise NotImplementedError( f"Invalid dependency group item after parse: {item}" )
# in the event that errors were detected, present the group as empty and do not # cache the result # this ensures that repeated access to a cyclic group will raise multiple errors if errors.errors: return ()
self._resolve_cache[group] = tuple(resolved_group) return self._resolve_cache[group]
def _parse_group( self, group: str, errors: _ErrorCollector ) -> tuple[Requirement | DependencyGroupInclude, ...]: # short circuit -- never do the work twice if group in self._parsed_groups: return self._parsed_groups[group]
if group not in self.dependency_groups: errors.error(LookupError(f"Dependency group '{group}' not found")) return ()
raw_group = self.dependency_groups[group] if isinstance(raw_group, str): errors.error( TypeError( f"Dependency group {group!r} contained a string rather than a list." ) ) return ()
if not isinstance(raw_group, Sequence): errors.error( TypeError(f"Dependency group {group!r} is not a sequence type.") ) return ()
elements: list[Requirement | DependencyGroupInclude] = [] for item in raw_group: if isinstance(item, str): # packaging.requirements.Requirement parsing ensures that this is a # valid PEP 508 Dependency Specifier # raises InvalidRequirement on failure elements.append(Requirement(item)) elif isinstance(item, Mapping): if tuple(item.keys()) != ("include-group",): errors.error( InvalidDependencyGroupObject( f"Invalid dependency group item: {item!r}" ) ) else: include_group = item["include-group"] elements.append(DependencyGroupInclude(include_group=include_group)) else: errors.error(TypeError(f"Invalid dependency group item: {item!r}"))
self._parsed_groups[group] = tuple(elements) return self._parsed_groups[group]
# --------------------# Functional Interface# --------------------
def resolve_dependency_groups( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str) -> tuple[str, ...]: """ Resolve a dependency group to a tuple of requirements, as strings.
:param dependency_groups: the parsed contents of the ``[dependency-groups]`` table from ``pyproject.toml`` :param groups: the name of the group(s) to resolve """ resolver = DependencyGroupResolver(dependency_groups) return tuple(str(r) for group in groups for r in resolver.resolve(group))
# ----------------# internal helpers# ----------------
_NORMALIZE_PATTERN = re.compile(r"[-_.]+")
def _normalize_name(name: str) -> str: return _NORMALIZE_PATTERN.sub("-", name).lower()
def _normalize_group_names( dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], errors: _ErrorCollector,) -> dict[str, Sequence[str | Mapping[str, str]]]: original_names: dict[str, list[str]] = {} normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {}
for group_name, value in dependency_groups.items(): normed_group_name = _normalize_name(group_name) original_names.setdefault(normed_group_name, []).append(group_name) normalized_groups[normed_group_name] = value
for normed_name, names in original_names.items(): if len(names) > 1: errors.error( DuplicateGroupNames( "Duplicate dependency group names: " f"{normed_name} ({', '.join(names)})" ) )
return normalized_groups12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from __future__ import annotations
import contextlibimport dataclassesimport sysimport typing
__all__ = ["ExceptionGroup"]
def __dir__() -> list[str]: return __all__
if sys.version_info >= (3, 11): # pragma: no cover from builtins import ExceptionGroupelse: # pragma: no cover
class ExceptionGroup(Exception): """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
If :external:exc:`ExceptionGroup` is already defined by Python itself, that version is used instead. """
message: str exceptions: list[Exception]
def __init__(self, message: str, exceptions: list[Exception]) -> None: self.message = message self.exceptions = exceptions
def __repr__(self) -> str: return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
@dataclasses.dataclassclass _ErrorCollector: """ Collect errors into ExceptionGroups.
Used like this:
collector = _ErrorCollector() # Add a single exception collector.error(ValueError("one"))
# Supports nesting, including combining ExceptionGroups with collector.collect(): raise ValueError("two") collector.finalize("Found some errors")
Since making a collector and then calling finalize later is a common pattern, a convenience method ``on_exit`` is provided. """
errors: list[Exception] = dataclasses.field(default_factory=list, init=False)
def finalize(self, msg: str) -> None: """Raise a group exception if there are any errors.""" if self.errors: raise ExceptionGroup(msg, self.errors)
@contextlib.contextmanager def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]: """ Calls finalize if no uncollected errors were present.
Uncollected errors are raised normally. """ yield self self.finalize(msg)
@contextlib.contextmanager def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]: """ Context manager to collect errors into the error list.
Must be inside loops, as only one error can be collected at a time. """ error_classes = err_cls or (Exception,) try: yield except ExceptionGroup as error: self.errors.extend(error.exceptions) except error_classes as error: self.errors.append(error)
def error( self, error: Exception, ) -> None: """Add an error to the list.""" self.errors.append(error).DS_StoreAdded
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_backends/_asyncio.pyAdded
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/_core/_subprocesses.pyAdded+196
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_resources.pyAdded+33
.cache/uv/archive-v0/BqdiuzqvjslV9oIioFJpl/anyio/abc/_testing.pyAdded+65
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/RECORDAdded+22
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click-8.3.3.dist-info/licenses/LICENSE.txtAdded+28
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/_textwrap.pyAdded+51
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/parser.pyAdded+532
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/termui.pyAdded+891
.cache/uv/archive-v0/TrowtGVMx34yve39-Z8a7/click/testing.pyAdded+669
.cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec-2026.4.0.dist-info/METADATAAdded+257
.cache/uv/archive-v0/XRAQrQ51jmWVYNQueQxzw/fsspec/callbacks.pyAdded+324
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/__init__.pyAdded
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/html_re.pyAdded+39
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/common/utils.pyAdded+313
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/__init__.pyAdded+6
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/helpers/parse_link_title.pyAdded+75
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/parser_core.pyAdded+46
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/port.yamlAdded+48
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/default.pyAdded+36
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/presets/zero.pyAdded+44
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/ruler.pyAdded+275
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/__init__.pyAdded+27
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/code.pyAdded+36
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/fence.pyAdded+101
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/hr.pyAdded+56
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/lheading.pyAdded+86
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/list.pyAdded+345
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_block/paragraph.pyAdded+66
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/__init__.pyAdded+19
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/linkify.pyAdded+149
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/normalize.pyAdded+19
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_core/text_join.pyAdded+35
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/backticks.pyAdded+72
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/balance_pairs.pyAdded+138
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/emphasis.pyAdded+102
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/linkify.pyAdded+62
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/rules_inline/newline.pyAdded+44
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it/token.pyAdded+178
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/WHEELAdded+4
.cache/uv/archive-v0/a-1PDFmAUFmQcCxwi_KtH/markdown_it_py-4.0.0.dist-info/entry_points.txtAdded+3
.cache/uv/archive-v0/kP2PUXEYMUC0shkt92DN5/idna-3.13.dist-info/METADATAAdded+204
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging-26.2.dist-info/RECORDAdded+27
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/__init__.pyAdded+15
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_parser.pyAdded+393
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/_structures.pyAdded+33
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/dependency_groups.pyAdded+302
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/errors.pyAdded+94
.cache/uv/archive-v0/kfLK0Q1h6oahhV_Ci_JCA/packaging/py.typedAdded