diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..0670bdd3e4480debc6df2ac67b718b810247b123 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/METADATA @@ -0,0 +1,93 @@ +Metadata-Version: 2.4 +Name: anyio +Version: 4.10.0 +Summary: High-level concurrency and networking framework on top of asyncio or Trio +Author-email: Alex Grönholm +License-Expression: MIT +Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/ +Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html +Project-URL: Source code, https://github.com/agronholm/anyio +Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Framework :: AnyIO +Classifier: Typing :: Typed +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11" +Requires-Dist: idna>=2.8 +Requires-Dist: sniffio>=1.1 +Requires-Dist: typing_extensions>=4.5; python_version < "3.13" +Provides-Extra: trio +Requires-Dist: trio>=0.26.1; extra == "trio" +Dynamic: license-file + +.. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg + :target: https://github.com/agronholm/anyio/actions/workflows/test.yml + :alt: Build Status +.. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master + :target: https://coveralls.io/github/agronholm/anyio?branch=master + :alt: Code Coverage +.. image:: https://readthedocs.org/projects/anyio/badge/?version=latest + :target: https://anyio.readthedocs.io/en/latest/?badge=latest + :alt: Documentation +.. image:: https://badges.gitter.im/gitterHQ/gitter.svg + :target: https://gitter.im/python-trio/AnyIO + :alt: Gitter chat + +AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or +Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony +with the native SC of Trio itself. + +Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or +Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full +refactoring necessary. It will blend in with the native libraries of your chosen backend. + +To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it +`here `_. + +Documentation +------------- + +View full documentation at: https://anyio.readthedocs.io/ + +Features +-------- + +AnyIO offers the following functionality: + +* Task groups (nurseries_ in trio terminology) +* High-level networking (TCP, UDP and UNIX sockets) + + * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python + 3.8) + * async/await style UDP sockets (unlike asyncio where you still have to use Transports and + Protocols) + +* A versatile API for byte streams and object streams +* Inter-task synchronization and communication (locks, conditions, events, semaphores, object + streams) +* Worker threads +* Subprocesses +* Asynchronous file I/O (using worker threads) +* Signal handling + +AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures. +It even works with the popular Hypothesis_ library. + +.. _asyncio: https://docs.python.org/3/library/asyncio.html +.. _Trio: https://github.com/python-trio/trio +.. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency +.. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning +.. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs +.. _pytest: https://docs.pytest.org/en/latest/ +.. _Hypothesis: https://hypothesis.works/ diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c363c8581a3e448fd84809df89c504c586e2cd68 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/RECORD @@ -0,0 +1,92 @@ +anyio-4.10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +anyio-4.10.0.dist-info/METADATA,sha256=1AD_60gPgqxWKsO54FUTbKDQHyni5j_56_XQinKJ9LQ,4014 +anyio-4.10.0.dist-info/RECORD,, +anyio-4.10.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio-4.10.0.dist-info/WHEEL,sha256=lTU6B6eIfYoiQJTZNc-fyaR6BpL6ehTzU3xGYxn2n8k,91 +anyio-4.10.0.dist-info/direct_url.json,sha256=_djiGnNnx3NQOth1G4F9V3DODy6L0cLvQ2kejcS-UZ8,95 +anyio-4.10.0.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39 +anyio-4.10.0.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081 +anyio-4.10.0.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6 +anyio/__init__.py,sha256=z3IyWgWQuxCi-KUwma-1LSys4WB50mV2N8FvS9_IePE,5955 +anyio/__pycache__/__init__.cpython-313.pyc,, +anyio/__pycache__/from_thread.cpython-313.pyc,, +anyio/__pycache__/lowlevel.cpython-313.pyc,, +anyio/__pycache__/pytest_plugin.cpython-313.pyc,, +anyio/__pycache__/to_interpreter.cpython-313.pyc,, +anyio/__pycache__/to_process.cpython-313.pyc,, +anyio/__pycache__/to_thread.cpython-313.pyc,, +anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_backends/__pycache__/__init__.cpython-313.pyc,, +anyio/_backends/__pycache__/_asyncio.cpython-313.pyc,, +anyio/_backends/__pycache__/_trio.cpython-313.pyc,, +anyio/_backends/_asyncio.py,sha256=YXpQJ0C-tNiYvZdElVa3zGflG_Jdvf7FNDiG9-THhMg,97359 +anyio/_backends/_trio.py,sha256=tRGDtos6xmqmGlstfI8wEjGvhZq0y_SYTaM2m8zatRU,41963 +anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/_core/__pycache__/__init__.cpython-313.pyc,, +anyio/_core/__pycache__/_asyncio_selector_thread.cpython-313.pyc,, +anyio/_core/__pycache__/_contextmanagers.cpython-313.pyc,, +anyio/_core/__pycache__/_eventloop.cpython-313.pyc,, +anyio/_core/__pycache__/_exceptions.cpython-313.pyc,, +anyio/_core/__pycache__/_fileio.cpython-313.pyc,, +anyio/_core/__pycache__/_resources.cpython-313.pyc,, +anyio/_core/__pycache__/_signals.cpython-313.pyc,, +anyio/_core/__pycache__/_sockets.cpython-313.pyc,, +anyio/_core/__pycache__/_streams.cpython-313.pyc,, +anyio/_core/__pycache__/_subprocesses.cpython-313.pyc,, +anyio/_core/__pycache__/_synchronization.cpython-313.pyc,, +anyio/_core/__pycache__/_tasks.cpython-313.pyc,, +anyio/_core/__pycache__/_tempfile.cpython-313.pyc,, +anyio/_core/__pycache__/_testing.cpython-313.pyc,, +anyio/_core/__pycache__/_typedattr.cpython-313.pyc,, +anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626 +anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215 +anyio/_core/_eventloop.py,sha256=t_tAwBFPjF8jrZGjlJ6bbYy6KA3bjsbZxV9mvh9t1i0,4695 +anyio/_core/_exceptions.py,sha256=uQ9yXs3gRghZiuxiWtbvVlHB6CvCRtxObKMWF-Mnz18,3683 +anyio/_core/_fileio.py,sha256=KATysDZP7bvwwjpUwEaGAc0xGouJgAPqNVpnBMTsToY,23332 +anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435 +anyio/_core/_signals.py,sha256=vulT1M1xdLYtAR-eY5TamIgaf1WTlOwOrMGwswlTTr8,905 +anyio/_core/_sockets.py,sha256=MRo3vVzBLnWwA0DqjWhJ2ICj_XKQ78BtWxdrSAwKcxU,32232 +anyio/_core/_streams.py,sha256=OnaKgoDD-FcMSwLvkoAUGP51sG2ZdRvMpxt9q2w1gYA,1804 +anyio/_core/_subprocesses.py,sha256=EXm5igL7dj55iYkPlbYVAqtbqxJxjU-6OndSTIx9SRg,8047 +anyio/_core/_synchronization.py,sha256=76KyUbGD3A3eCXPrLnOccQfRsNSxIcoR36JeK1P4VFQ,20306 +anyio/_core/_tasks.py,sha256=f3CuWwo06cCZ6jaOv-JHFKWkgpgf2cvaF25Oh4augMA,4757 +anyio/_core/_tempfile.py,sha256=lHb7CW4FyIlpkf5ADAf4VmLHCKwEHF9nxqNyBCFFUiA,19697 +anyio/_core/_testing.py,sha256=YUGwA5cgFFbUTv4WFd7cv_BSVr4ryTtPp8owQA3JdWE,2118 +anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508 +anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869 +anyio/abc/__pycache__/__init__.cpython-313.pyc,, +anyio/abc/__pycache__/_eventloop.cpython-313.pyc,, +anyio/abc/__pycache__/_resources.cpython-313.pyc,, +anyio/abc/__pycache__/_sockets.cpython-313.pyc,, +anyio/abc/__pycache__/_streams.cpython-313.pyc,, +anyio/abc/__pycache__/_subprocesses.cpython-313.pyc,, +anyio/abc/__pycache__/_tasks.cpython-313.pyc,, +anyio/abc/__pycache__/_testing.cpython-313.pyc,, +anyio/abc/_eventloop.py,sha256=_rrVDoNAS9yIFvSE70ewoppYd_9zNbRjPFl5UPMSR8I,10729 +anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783 +anyio/abc/_sockets.py,sha256=ECTY0jLEF18gryANHR3vFzXzGdZ-xPwELq1QdgOb0Jo,13258 +anyio/abc/_streams.py,sha256=005GKSCXGprxnhucILboSqc2JFovECZk9m3p-qqxXVc,7640 +anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067 +anyio/abc/_tasks.py,sha256=Jh4LXVz1DoRacOnw1rwAS9wujNiEWK9oqdF0cTEhhNA,3604 +anyio/abc/_testing.py,sha256=tBJUzkSfOXJw23fe8qSJ03kJlShOYjjaEyFB6k6MYT8,1821 +anyio/from_thread.py,sha256=t8B_amqFBqlJy8X18mhvpYkhzeSXmRsI-ep6Yg04H4M,17678 +anyio/lowlevel.py,sha256=IisVkje5kwqOCpe-RgBjGCvlr-JBFGBrkobR7iZ3Fv4,4153 +anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/pytest_plugin.py,sha256=qXNwk9Pa7hPQKWocgLl9qijqKGMkGzdH2wJa-jPkGUM,9375 +anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +anyio/streams/__pycache__/__init__.cpython-313.pyc,, +anyio/streams/__pycache__/buffered.cpython-313.pyc,, +anyio/streams/__pycache__/file.cpython-313.pyc,, +anyio/streams/__pycache__/memory.cpython-313.pyc,, +anyio/streams/__pycache__/stapled.cpython-313.pyc,, +anyio/streams/__pycache__/text.cpython-313.pyc,, +anyio/streams/__pycache__/tls.cpython-313.pyc,, +anyio/streams/buffered.py,sha256=joUPdz0OoRfKgGmMpHI9vZyMNm6ly9iFlofrZUPs9cQ,6162 +anyio/streams/file.py,sha256=6uoTNb5KbMoj-6gS3_xrrL8uZN8Q4iIvOS1WtGyFfKw,4383 +anyio/streams/memory.py,sha256=GcbF3cahdsdFZtcTZaIKpZXPDZKogj18wWPPmE0OmGU,10620 +anyio/streams/stapled.py,sha256=U09pCrmOw9kkNhe6tKopsm1QIMT1lFTFvtb-A7SIe4k,4302 +anyio/streams/text.py,sha256=tCJ8ljavGM-HY0aL-5Twxv-Kyw1BfR0B4OtVIB6kZ9w,5662 +anyio/streams/tls.py,sha256=siSaaRyX-XnfC7Jbn9VjtIdVzJkDsvIW_2pSEVheDFQ,15275 +anyio/to_interpreter.py,sha256=Z0-kLCxlITjFG_RM_TNdUlEnog94l48GXVDZ80w0URc,6986 +anyio/to_process.py,sha256=ZvruelRM-HNmqDaql4sdNODg2QD_uSlwSCxnV4OhsfQ,9595 +anyio/to_thread.py,sha256=WM2JQ2MbVsd5D5CM08bQiTwzZIvpsGjfH1Fy247KoDQ,2396 diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..370ec5f1aa3524bfd31a19fd21e907335f48a7f6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (78.1.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..43a9d50002a579bf36803ef95f83869cdcc35429 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_175862240717140/conda-bld/anyio_1758622421932/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..44dd9bdc3039122cc98014c1439ca254313fd014 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[pytest11] +anyio = anyio.pytest_plugin diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..104eebf5a3002fccdaceef3a4cb936173c1c2035 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2018 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/top_level.txt b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c77c069ecc9b7f8b1f97dbcfec905725db0253a8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio-4.10.0.dist-info/top_level.txt @@ -0,0 +1 @@ +anyio diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_contextmanagers.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_contextmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..302f32b0c78a7071605b195c55054cfdb0b55f37 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_contextmanagers.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +from abc import abstractmethod +from contextlib import AbstractAsyncContextManager, AbstractContextManager +from inspect import isasyncgen, iscoroutine, isgenerator +from types import TracebackType +from typing import Protocol, TypeVar, cast, final + +_T_co = TypeVar("_T_co", covariant=True) +_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound="bool | None") + + +class _SupportsCtxMgr(Protocol[_T_co, _ExitT_co]): + def __contextmanager__(self) -> AbstractContextManager[_T_co, _ExitT_co]: ... + + +class _SupportsAsyncCtxMgr(Protocol[_T_co, _ExitT_co]): + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[_T_co, _ExitT_co]: ... + + +class ContextManagerMixin: + """ + Mixin class providing context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via :meth:`__contextmanager__` + which should return a generator. The mechanics are meant to mirror those of + :func:`@contextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractContextManager[object, bool | None] | None = None + + @final + def __enter__(self: _SupportsCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__contextmanager__() + if not isinstance(cm, AbstractContextManager): + if isgenerator(cm): + raise TypeError( + "__contextmanager__() returned a generator object instead of " + "a context manager. Did you forget to add the @contextmanager " + "decorator?" + ) + + raise TypeError( + f"__contextmanager__() did not return a context manager object, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__contextmanager__() returned " + f"self. Did you forget to add the @contextmanager decorator and a " + f"'yield' statement?" + ) + + value = cm.__enter__() + self.__cm = cm + return value + + @final + def __exit__( + self: _SupportsCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, cm.__exit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __contextmanager__(self) -> AbstractContextManager[object, bool | None]: + """ + Implement your context manager logic here. + + This method **must** be decorated with + :func:`@contextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: a context manager object + """ + + +class AsyncContextManagerMixin: + """ + Mixin class providing async context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via + :meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of + :func:`@asynccontextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractAsyncContextManager[object, bool | None] | None = None + + @final + async def __aenter__(self: _SupportsAsyncCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__asynccontextmanager__() + if not isinstance(cm, AbstractAsyncContextManager): + if isasyncgen(cm): + raise TypeError( + "__asynccontextmanager__() returned an async generator instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator?" + ) + elif iscoroutine(cm): + cm.close() + raise TypeError( + "__asynccontextmanager__() returned a coroutine object instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator and a 'yield' statement?" + ) + + raise TypeError( + f"__asynccontextmanager__() did not return an async context manager, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__asynccontextmanager__() returned " + f"self. Did you forget to add the @asynccontextmanager decorator and a " + f"'yield' statement?" + ) + + value = await cm.__aenter__() + self.__cm = cm + return value + + @final + async def __aexit__( + self: _SupportsAsyncCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, await cm.__aexit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[object, bool | None]: + """ + Implement your async context manager logic here. + + This method **must** be decorated with + :func:`@asynccontextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: an async context manager object + """ diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_eventloop.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..6dcb45898184ec7ea5143e42bd147138fd8ed304 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_eventloop.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +import math +import sys +import threading +from collections.abc import Awaitable, Callable, Generator +from contextlib import contextmanager +from importlib import import_module +from typing import TYPE_CHECKING, Any, TypeVar + +import sniffio + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from ..abc import AsyncBackend + +# This must be updated when new backends are introduced +BACKENDS = "asyncio", "trio" + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +threadlocals = threading.local() +loaded_backends: dict[str, type[AsyncBackend]] = {} + + +def run( + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, +) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param backend: name of the asynchronous event loop implementation – currently + either ``asyncio`` or ``trio`` + :param backend_options: keyword arguments to call the backend ``run()`` + implementation with (documented :ref:`here `) + :return: the return value of the coroutine function + :raises RuntimeError: if an asynchronous event loop is already running in this + thread + :raises LookupError: if the named backend is not found + + """ + try: + asynclib_name = sniffio.current_async_library() + except sniffio.AsyncLibraryNotFoundError: + pass + else: + raise RuntimeError(f"Already running {asynclib_name} in this thread") + + try: + async_backend = get_async_backend(backend) + except ImportError as exc: + raise LookupError(f"No such backend: {backend}") from exc + + token = None + if sniffio.current_async_library_cvar.get(None) is None: + # Since we're in control of the event loop, we can cache the name of the async + # library + token = sniffio.current_async_library_cvar.set(backend) + + try: + backend_options = backend_options or {} + return async_backend.run(func, args, {}, backend_options) + finally: + if token: + sniffio.current_async_library_cvar.reset(token) + + +async def sleep(delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + + """ + return await get_async_backend().sleep(delay) + + +async def sleep_forever() -> None: + """ + Pause the current task until it's cancelled. + + This is a shortcut for ``sleep(math.inf)``. + + .. versionadded:: 3.1 + + """ + await sleep(math.inf) + + +async def sleep_until(deadline: float) -> None: + """ + Pause the current task until the given time. + + :param deadline: the absolute time to wake up at (according to the internal + monotonic clock of the event loop) + + .. versionadded:: 3.1 + + """ + now = current_time() + await sleep(max(deadline - now, 0)) + + +def current_time() -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + + """ + return get_async_backend().current_time() + + +def get_all_backends() -> tuple[str, ...]: + """Return a tuple of the names of all built-in backends.""" + return BACKENDS + + +def get_cancelled_exc_class() -> type[BaseException]: + """Return the current async library's cancellation exception class.""" + return get_async_backend().cancelled_exception_class() + + +# +# Private API +# + + +@contextmanager +def claim_worker_thread( + backend_class: type[AsyncBackend], token: object +) -> Generator[Any, None, None]: + threadlocals.current_async_backend = backend_class + threadlocals.current_token = token + try: + yield + finally: + del threadlocals.current_async_backend + del threadlocals.current_token + + +def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]: + if asynclib_name is None: + asynclib_name = sniffio.current_async_library() + + # We use our own dict instead of sys.modules to get the already imported back-end + # class because the appropriate modules in sys.modules could potentially be only + # partially initialized + try: + return loaded_backends[asynclib_name] + except KeyError: + module = import_module(f"anyio._backends._{asynclib_name}") + loaded_backends[asynclib_name] = module.backend_class + return module.backend_class diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_exceptions.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..daa067768a3a729662c30e965b67e8d461e22e88 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_exceptions.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import sys +from collections.abc import Generator +from textwrap import dedent +from typing import Any + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup + + +class BrokenResourceError(Exception): + """ + Raised when trying to use a resource that has been rendered unusable due to external + causes (e.g. a send stream whose peer has disconnected). + """ + + +class BrokenWorkerProcess(Exception): + """ + Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or + otherwise misbehaves. + """ + + +class BrokenWorkerInterpreter(Exception): + """ + Raised by :meth:`~anyio.to_interpreter.run_sync` if an unexpected exception is + raised in the subinterpreter. + """ + + def __init__(self, excinfo: Any): + # This was adapted from concurrent.futures.interpreter.ExecutionFailed + msg = excinfo.formatted + if not msg: + if excinfo.type and excinfo.msg: + msg = f"{excinfo.type.__name__}: {excinfo.msg}" + else: + msg = excinfo.type.__name__ or excinfo.msg + + super().__init__(msg) + self.excinfo = excinfo + + def __str__(self) -> str: + try: + formatted = self.excinfo.errdisplay + except Exception: + return super().__str__() + else: + return dedent( + f""" + {super().__str__()} + + Uncaught in the interpreter: + + {formatted} + """.strip() + ) + + +class BusyResourceError(Exception): + """ + Raised when two tasks are trying to read from or write to the same resource + concurrently. + """ + + def __init__(self, action: str): + super().__init__(f"Another task is already {action} this resource") + + +class ClosedResourceError(Exception): + """Raised when trying to use a resource that has been closed.""" + + +class ConnectionFailed(OSError): + """ + Raised when a connection attempt fails. + + .. note:: This class inherits from :exc:`OSError` for backwards compatibility. + """ + + +def iterate_exceptions( + exception: BaseException, +) -> Generator[BaseException, None, None]: + if isinstance(exception, BaseExceptionGroup): + for exc in exception.exceptions: + yield from iterate_exceptions(exc) + else: + yield exception + + +class DelimiterNotFound(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + maximum number of bytes has been read without the delimiter being found. + """ + + def __init__(self, max_bytes: int) -> None: + super().__init__( + f"The delimiter was not found among the first {max_bytes} bytes" + ) + + +class EndOfStream(Exception): + """ + Raised when trying to read from a stream that has been closed from the other end. + """ + + +class IncompleteRead(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + connection is closed before the requested amount of bytes has been read. + """ + + def __init__(self) -> None: + super().__init__( + "The stream was closed before the read operation could be completed" + ) + + +class TypedAttributeLookupError(LookupError): + """ + Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute + is not found and no default value has been given. + """ + + +class WouldBlock(Exception): + """Raised by ``X_nowait`` functions if ``X()`` would block.""" diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_fileio.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_fileio.py new file mode 100644 index 0000000000000000000000000000000000000000..2eae029e4826c27764d0d8f398ae42bd8f0856fc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_fileio.py @@ -0,0 +1,740 @@ +from __future__ import annotations + +import os +import pathlib +import sys +from collections.abc import ( + AsyncIterator, + Callable, + Iterable, + Iterator, + Sequence, +) +from dataclasses import dataclass +from functools import partial +from os import PathLike +from typing import ( + IO, + TYPE_CHECKING, + Any, + AnyStr, + ClassVar, + Final, + Generic, + overload, +) + +from .. import to_thread +from ..abc import AsyncResource + +if TYPE_CHECKING: + from types import ModuleType + + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer +else: + ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object + + +class AsyncFile(AsyncResource, Generic[AnyStr]): + """ + An asynchronous file object. + + This class wraps a standard file object and provides async friendly versions of the + following blocking methods (where available on the original file object): + + * read + * read1 + * readline + * readlines + * readinto + * readinto1 + * write + * writelines + * truncate + * seek + * tell + * flush + + All other methods are directly passed through. + + This class supports the asynchronous context manager protocol which closes the + underlying file at the end of the context block. + + This class also supports asynchronous iteration:: + + async with await open_file(...) as f: + async for line in f: + print(line) + """ + + def __init__(self, fp: IO[AnyStr]) -> None: + self._fp: Any = fp + + def __getattr__(self, name: str) -> object: + return getattr(self._fp, name) + + @property + def wrapped(self) -> IO[AnyStr]: + """The wrapped file object.""" + return self._fp + + async def __aiter__(self) -> AsyncIterator[AnyStr]: + while True: + line = await self.readline() + if line: + yield line + else: + break + + async def aclose(self) -> None: + return await to_thread.run_sync(self._fp.close) + + async def read(self, size: int = -1) -> AnyStr: + return await to_thread.run_sync(self._fp.read, size) + + async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes: + return await to_thread.run_sync(self._fp.read1, size) + + async def readline(self) -> AnyStr: + return await to_thread.run_sync(self._fp.readline) + + async def readlines(self) -> list[AnyStr]: + return await to_thread.run_sync(self._fp.readlines) + + async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto, b) + + async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto1, b) + + @overload + async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ... + + @overload + async def write(self: AsyncFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + return await to_thread.run_sync(self._fp.write, b) + + @overload + async def writelines( + self: AsyncFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + + @overload + async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ... + + async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None: + return await to_thread.run_sync(self._fp.writelines, lines) + + async def truncate(self, size: int | None = None) -> int: + return await to_thread.run_sync(self._fp.truncate, size) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + return await to_thread.run_sync(self._fp.seek, offset, whence) + + async def tell(self) -> int: + return await to_thread.run_sync(self._fp.tell) + + async def flush(self) -> None: + return await to_thread.run_sync(self._fp.flush) + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[bytes]: ... + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[str]: ... + + +async def open_file( + file: str | PathLike[str] | int, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: Callable[[str, int], int] | None = None, +) -> AsyncFile[Any]: + """ + Open a file asynchronously. + + The arguments are exactly the same as for the builtin :func:`open`. + + :return: an asynchronous file object + + """ + fp = await to_thread.run_sync( + open, file, mode, buffering, encoding, errors, newline, closefd, opener + ) + return AsyncFile(fp) + + +def wrap_file(file: IO[AnyStr]) -> AsyncFile[AnyStr]: + """ + Wrap an existing file as an asynchronous file. + + :param file: an existing file-like object + :return: an asynchronous file object + + """ + return AsyncFile(file) + + +@dataclass(eq=False) +class _PathIterator(AsyncIterator["Path"]): + iterator: Iterator[PathLike[str]] + + async def __anext__(self) -> Path: + nextval = await to_thread.run_sync( + next, self.iterator, None, abandon_on_cancel=True + ) + if nextval is None: + raise StopAsyncIteration from None + + return Path(nextval) + + +class Path: + """ + An asynchronous version of :class:`pathlib.Path`. + + This class cannot be substituted for :class:`pathlib.Path` or + :class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike` + interface. + + It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for + the deprecated :meth:`~pathlib.Path.link_to` method. + + Some methods may be unavailable or have limited functionality, based on the Python + version: + + * :meth:`~pathlib.Path.copy` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.copy_into` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later) + * :meth:`~pathlib.PurePath.full_match` (available on Python 3.13 or later) + * :attr:`~pathlib.Path.info` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later) + * :meth:`~pathlib.PurePath.match` (the ``case_sensitive`` parameter is only + available on Python 3.13 or later) + * :meth:`~pathlib.Path.move` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.move_into` (available on Python 3.14 or later) + * :meth:`~pathlib.PurePath.relative_to` (the ``walk_up`` parameter is only available + on Python 3.12 or later) + * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later) + + Any methods that do disk I/O need to be awaited on. These methods are: + + * :meth:`~pathlib.Path.absolute` + * :meth:`~pathlib.Path.chmod` + * :meth:`~pathlib.Path.cwd` + * :meth:`~pathlib.Path.exists` + * :meth:`~pathlib.Path.expanduser` + * :meth:`~pathlib.Path.group` + * :meth:`~pathlib.Path.hardlink_to` + * :meth:`~pathlib.Path.home` + * :meth:`~pathlib.Path.is_block_device` + * :meth:`~pathlib.Path.is_char_device` + * :meth:`~pathlib.Path.is_dir` + * :meth:`~pathlib.Path.is_fifo` + * :meth:`~pathlib.Path.is_file` + * :meth:`~pathlib.Path.is_junction` + * :meth:`~pathlib.Path.is_mount` + * :meth:`~pathlib.Path.is_socket` + * :meth:`~pathlib.Path.is_symlink` + * :meth:`~pathlib.Path.lchmod` + * :meth:`~pathlib.Path.lstat` + * :meth:`~pathlib.Path.mkdir` + * :meth:`~pathlib.Path.open` + * :meth:`~pathlib.Path.owner` + * :meth:`~pathlib.Path.read_bytes` + * :meth:`~pathlib.Path.read_text` + * :meth:`~pathlib.Path.readlink` + * :meth:`~pathlib.Path.rename` + * :meth:`~pathlib.Path.replace` + * :meth:`~pathlib.Path.resolve` + * :meth:`~pathlib.Path.rmdir` + * :meth:`~pathlib.Path.samefile` + * :meth:`~pathlib.Path.stat` + * :meth:`~pathlib.Path.symlink_to` + * :meth:`~pathlib.Path.touch` + * :meth:`~pathlib.Path.unlink` + * :meth:`~pathlib.Path.walk` + * :meth:`~pathlib.Path.write_bytes` + * :meth:`~pathlib.Path.write_text` + + Additionally, the following methods return an async iterator yielding + :class:`~.Path` objects: + + * :meth:`~pathlib.Path.glob` + * :meth:`~pathlib.Path.iterdir` + * :meth:`~pathlib.Path.rglob` + """ + + __slots__ = "_path", "__weakref__" + + __weakref__: Any + + def __init__(self, *args: str | PathLike[str]) -> None: + self._path: Final[pathlib.Path] = pathlib.Path(*args) + + def __fspath__(self) -> str: + return self._path.__fspath__() + + def __str__(self) -> str: + return self._path.__str__() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.as_posix()!r})" + + def __bytes__(self) -> bytes: + return self._path.__bytes__() + + def __hash__(self) -> int: + return self._path.__hash__() + + def __eq__(self, other: object) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__eq__(target) + + def __lt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__lt__(target) + + def __le__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__le__(target) + + def __gt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__gt__(target) + + def __ge__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__ge__(target) + + def __truediv__(self, other: str | PathLike[str]) -> Path: + return Path(self._path / other) + + def __rtruediv__(self, other: str | PathLike[str]) -> Path: + return Path(other) / self + + @property + def parts(self) -> tuple[str, ...]: + return self._path.parts + + @property + def drive(self) -> str: + return self._path.drive + + @property + def root(self) -> str: + return self._path.root + + @property + def anchor(self) -> str: + return self._path.anchor + + @property + def parents(self) -> Sequence[Path]: + return tuple(Path(p) for p in self._path.parents) + + @property + def parent(self) -> Path: + return Path(self._path.parent) + + @property + def name(self) -> str: + return self._path.name + + @property + def suffix(self) -> str: + return self._path.suffix + + @property + def suffixes(self) -> list[str]: + return self._path.suffixes + + @property + def stem(self) -> str: + return self._path.stem + + async def absolute(self) -> Path: + path = await to_thread.run_sync(self._path.absolute) + return Path(path) + + def as_posix(self) -> str: + return self._path.as_posix() + + def as_uri(self) -> str: + return self._path.as_uri() + + if sys.version_info >= (3, 13): + parser: ClassVar[ModuleType] = pathlib.Path.parser + + @classmethod + def from_uri(cls, uri: str) -> Path: + return Path(pathlib.Path.from_uri(uri)) + + def full_match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.full_match(path_pattern, case_sensitive=case_sensitive) + + def match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.match(path_pattern, case_sensitive=case_sensitive) + else: + + def match(self, path_pattern: str) -> bool: + return self._path.match(path_pattern) + + if sys.version_info >= (3, 14): + + @property + def info(self) -> Any: # TODO: add return type annotation when Typeshed gets it + return self._path.info + + async def copy( + self, + target: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target))) + + async def copy_into( + self, + target_dir: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy_into, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target_dir))) + + async def move(self, target: str | os.PathLike[str]) -> Path: + # Upstream does not handle anyio.Path properly as a PathLike + target = pathlib.Path(target) + return Path(await to_thread.run_sync(self._path.move, target)) + + async def move_into( + self, + target_dir: str | os.PathLike[str], + ) -> Path: + return Path(await to_thread.run_sync(self._path.move_into, target_dir)) + + def is_relative_to(self, other: str | PathLike[str]) -> bool: + try: + self.relative_to(other) + return True + except ValueError: + return False + + async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: + func = partial(os.chmod, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, mode) + + @classmethod + async def cwd(cls) -> Path: + path = await to_thread.run_sync(pathlib.Path.cwd) + return cls(path) + + async def exists(self) -> bool: + return await to_thread.run_sync(self._path.exists, abandon_on_cancel=True) + + async def expanduser(self) -> Path: + return Path( + await to_thread.run_sync(self._path.expanduser, abandon_on_cancel=True) + ) + + def glob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.glob(pattern) + return _PathIterator(gen) + + async def group(self) -> str: + return await to_thread.run_sync(self._path.group, abandon_on_cancel=True) + + async def hardlink_to( + self, target: str | bytes | PathLike[str] | PathLike[bytes] + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(os.link, target, self) + + @classmethod + async def home(cls) -> Path: + home_path = await to_thread.run_sync(pathlib.Path.home) + return cls(home_path) + + def is_absolute(self) -> bool: + return self._path.is_absolute() + + async def is_block_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_block_device, abandon_on_cancel=True + ) + + async def is_char_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_char_device, abandon_on_cancel=True + ) + + async def is_dir(self) -> bool: + return await to_thread.run_sync(self._path.is_dir, abandon_on_cancel=True) + + async def is_fifo(self) -> bool: + return await to_thread.run_sync(self._path.is_fifo, abandon_on_cancel=True) + + async def is_file(self) -> bool: + return await to_thread.run_sync(self._path.is_file, abandon_on_cancel=True) + + if sys.version_info >= (3, 12): + + async def is_junction(self) -> bool: + return await to_thread.run_sync(self._path.is_junction) + + async def is_mount(self) -> bool: + return await to_thread.run_sync( + os.path.ismount, self._path, abandon_on_cancel=True + ) + + def is_reserved(self) -> bool: + return self._path.is_reserved() + + async def is_socket(self) -> bool: + return await to_thread.run_sync(self._path.is_socket, abandon_on_cancel=True) + + async def is_symlink(self) -> bool: + return await to_thread.run_sync(self._path.is_symlink, abandon_on_cancel=True) + + async def iterdir(self) -> AsyncIterator[Path]: + gen = ( + self._path.iterdir() + if sys.version_info < (3, 13) + else await to_thread.run_sync(self._path.iterdir, abandon_on_cancel=True) + ) + async for path in _PathIterator(gen): + yield path + + def joinpath(self, *args: str | PathLike[str]) -> Path: + return Path(self._path.joinpath(*args)) + + async def lchmod(self, mode: int) -> None: + await to_thread.run_sync(self._path.lchmod, mode) + + async def lstat(self) -> os.stat_result: + return await to_thread.run_sync(self._path.lstat, abandon_on_cancel=True) + + async def mkdir( + self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False + ) -> None: + await to_thread.run_sync(self._path.mkdir, mode, parents, exist_ok) + + @overload + async def open( + self, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[bytes]: ... + + @overload + async def open( + self, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[str]: ... + + async def open( + self, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> AsyncFile[Any]: + fp = await to_thread.run_sync( + self._path.open, mode, buffering, encoding, errors, newline + ) + return AsyncFile(fp) + + async def owner(self) -> str: + return await to_thread.run_sync(self._path.owner, abandon_on_cancel=True) + + async def read_bytes(self) -> bytes: + return await to_thread.run_sync(self._path.read_bytes) + + async def read_text( + self, encoding: str | None = None, errors: str | None = None + ) -> str: + return await to_thread.run_sync(self._path.read_text, encoding, errors) + + if sys.version_info >= (3, 12): + + def relative_to( + self, *other: str | PathLike[str], walk_up: bool = False + ) -> Path: + # relative_to() should work with any PathLike but it doesn't + others = [pathlib.Path(other) for other in other] + return Path(self._path.relative_to(*others, walk_up=walk_up)) + + else: + + def relative_to(self, *other: str | PathLike[str]) -> Path: + return Path(self._path.relative_to(*other)) + + async def readlink(self) -> Path: + target = await to_thread.run_sync(os.readlink, self._path) + return Path(target) + + async def rename(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.rename, target) + return Path(target) + + async def replace(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.replace, target) + return Path(target) + + async def resolve(self, strict: bool = False) -> Path: + func = partial(self._path.resolve, strict=strict) + return Path(await to_thread.run_sync(func, abandon_on_cancel=True)) + + def rglob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.rglob(pattern) + return _PathIterator(gen) + + async def rmdir(self) -> None: + await to_thread.run_sync(self._path.rmdir) + + async def samefile(self, other_path: str | PathLike[str]) -> bool: + if isinstance(other_path, Path): + other_path = other_path._path + + return await to_thread.run_sync( + self._path.samefile, other_path, abandon_on_cancel=True + ) + + async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result: + func = partial(os.stat, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, abandon_on_cancel=True) + + async def symlink_to( + self, + target: str | bytes | PathLike[str] | PathLike[bytes], + target_is_directory: bool = False, + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.symlink_to, target, target_is_directory) + + async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: + await to_thread.run_sync(self._path.touch, mode, exist_ok) + + async def unlink(self, missing_ok: bool = False) -> None: + try: + await to_thread.run_sync(self._path.unlink) + except FileNotFoundError: + if not missing_ok: + raise + + if sys.version_info >= (3, 12): + + async def walk( + self, + top_down: bool = True, + on_error: Callable[[OSError], object] | None = None, + follow_symlinks: bool = False, + ) -> AsyncIterator[tuple[Path, list[str], list[str]]]: + def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None: + try: + return next(gen) + except StopIteration: + return None + + gen = self._path.walk(top_down, on_error, follow_symlinks) + while True: + value = await to_thread.run_sync(get_next_value) + if value is None: + return + + root, dirs, paths = value + yield Path(root), dirs, paths + + def with_name(self, name: str) -> Path: + return Path(self._path.with_name(name)) + + def with_stem(self, stem: str) -> Path: + return Path(self._path.with_name(stem + self._path.suffix)) + + def with_suffix(self, suffix: str) -> Path: + return Path(self._path.with_suffix(suffix)) + + def with_segments(self, *pathsegments: str | PathLike[str]) -> Path: + return Path(*pathsegments) + + async def write_bytes(self, data: bytes) -> int: + return await to_thread.run_sync(self._path.write_bytes, data) + + async def write_text( + self, + data: str, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> int: + # Path.write_text() does not support the "newline" parameter before Python 3.10 + def sync_write_text() -> int: + with self._path.open( + "w", encoding=encoding, errors=errors, newline=newline + ) as fp: + return fp.write(data) + + return await to_thread.run_sync(sync_write_text) + + +PathLike.register(Path) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_resources.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a5344aef2962670f9b305a02cd0b11f2087d2f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_resources.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from ..abc import AsyncResource +from ._tasks import CancelScope + + +async def aclose_forcefully(resource: AsyncResource) -> None: + """ + Close an asynchronous resource in a cancelled scope. + + Doing this closes the resource without waiting on anything. + + :param resource: the resource to close + + """ + with CancelScope() as scope: + scope.cancel() + await resource.aclose() diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_signals.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..f3451d302f514a6b2c9b4f96c6b3e17e36d7d050 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_signals.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import AbstractContextManager +from signal import Signals + +from ._eventloop import get_async_backend + + +def open_signal_receiver( + *signals: Signals, +) -> AbstractContextManager[AsyncIterator[Signals]]: + """ + Start receiving operating system signals. + + :param signals: signals to receive (e.g. ``signal.SIGINT``) + :return: an asynchronous context manager for an asynchronous iterator which yields + signal numbers + + .. warning:: Windows does not support signals natively so it is best to avoid + relying on this in cross-platform applications. + + .. warning:: On asyncio, this permanently replaces any previous signal handler for + the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`. + + """ + return get_async_backend().open_signal_receiver(*signals) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_sockets.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..9781c6022be901678e4efc1a5714fc7bcafaf4ac --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_sockets.py @@ -0,0 +1,934 @@ +from __future__ import annotations + +import errno +import os +import socket +import ssl +import stat +import sys +from collections.abc import Awaitable +from dataclasses import dataclass +from ipaddress import IPv4Address, IPv6Address, ip_address +from os import PathLike, chmod +from socket import AddressFamily, SocketKind +from typing import TYPE_CHECKING, Any, Literal, cast, overload + +from .. import ConnectionFailed, to_thread +from ..abc import ( + ByteStreamConnectable, + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPAddressType, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, +) +from ..streams.stapled import MultiListener +from ..streams.tls import TLSConnectable, TLSStream +from ._eventloop import get_async_backend +from ._resources import aclose_forcefully +from ._synchronization import Event +from ._tasks import create_task_group, move_on_after + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike +else: + FileDescriptorLike = object + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +if sys.version_info < (3, 13): + from typing_extensions import deprecated +else: + from warnings import deprecated + +IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515 + +AnyIPAddressFamily = Literal[ + AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6 +] +IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6] + + +# tls_hostname given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str, + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# ssl_context given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext, + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=True +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[True], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=False +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[False], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +# No TLS arguments +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = None, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_standard_compatible: bool = True, + tls_hostname: str | None = None, + happy_eyeballs_delay: float = 0.25, +) -> SocketStream | TLSStream: + """ + Connect to a host using the TCP protocol. + + This function implements the stateless version of the Happy Eyeballs algorithm (RFC + 6555). If ``remote_host`` is a host name that resolves to multiple IP addresses, + each one is tried until one connection attempt succeeds. If the first attempt does + not connected within 250 milliseconds, a second attempt is started using the next + address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if + available) is tried first. + + When the connection has been established, a TLS handshake will be done if either + ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``. + + :param remote_host: the IP address or host name to connect to + :param remote_port: port on the target host to connect to + :param local_host: the interface address or name to bind the socket to before + connecting + :param tls: ``True`` to do a TLS handshake with the connected stream and return a + :class:`~anyio.streams.tls.TLSStream` instead + :param ssl_context: the SSL context object to use (if omitted, a default context is + created) + :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake + before closing the stream and requires that the server does this as well. + Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream. + Some protocols, such as HTTP, require this option to be ``False``. + See :meth:`~ssl.SSLContext.wrap_socket` for details. + :param tls_hostname: host name to check the server certificate against (defaults to + the value of ``remote_host``) + :param happy_eyeballs_delay: delay (in seconds) before starting the next connection + attempt + :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream + :raises ConnectionFailed: if the connection fails + + """ + # Placed here due to https://github.com/python/mypy/issues/7057 + connected_stream: SocketStream | None = None + + async def try_connect(remote_host: str, event: Event) -> None: + nonlocal connected_stream + try: + stream = await asynclib.connect_tcp(remote_host, remote_port, local_address) + except OSError as exc: + oserrors.append(exc) + return + else: + if connected_stream is None: + connected_stream = stream + tg.cancel_scope.cancel() + else: + await stream.aclose() + finally: + event.set() + + asynclib = get_async_backend() + local_address: IPSockAddrType | None = None + family = socket.AF_UNSPEC + if local_host: + gai_res = await getaddrinfo(str(local_host), None) + family, *_, local_address = gai_res[0] + + target_host = str(remote_host) + try: + addr_obj = ip_address(remote_host) + except ValueError: + addr_obj = None + + if addr_obj is not None: + if isinstance(addr_obj, IPv6Address): + target_addrs = [(socket.AF_INET6, addr_obj.compressed)] + else: + target_addrs = [(socket.AF_INET, addr_obj.compressed)] + else: + # getaddrinfo() will raise an exception if name resolution fails + gai_res = await getaddrinfo( + target_host, remote_port, family=family, type=socket.SOCK_STREAM + ) + + # Organize the list so that the first address is an IPv6 address (if available) + # and the second one is an IPv4 addresses. The rest can be in whatever order. + v6_found = v4_found = False + target_addrs = [] + for af, *_, sa in gai_res: + if af == socket.AF_INET6 and not v6_found: + v6_found = True + target_addrs.insert(0, (af, sa[0])) + elif af == socket.AF_INET and not v4_found and v6_found: + v4_found = True + target_addrs.insert(1, (af, sa[0])) + else: + target_addrs.append((af, sa[0])) + + oserrors: list[OSError] = [] + try: + async with create_task_group() as tg: + for _af, addr in target_addrs: + event = Event() + tg.start_soon(try_connect, addr, event) + with move_on_after(happy_eyeballs_delay): + await event.wait() + + if connected_stream is None: + cause = ( + oserrors[0] + if len(oserrors) == 1 + else ExceptionGroup("multiple connection attempts failed", oserrors) + ) + raise OSError("All connection attempts failed") from cause + finally: + oserrors.clear() + + if tls or tls_hostname or ssl_context: + try: + return await TLSStream.wrap( + connected_stream, + server_side=False, + hostname=tls_hostname or str(remote_host), + ssl_context=ssl_context, + standard_compatible=tls_standard_compatible, + ) + except BaseException: + await aclose_forcefully(connected_stream) + raise + + return connected_stream + + +async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream: + """ + Connect to the given UNIX socket. + + Not available on Windows. + + :param path: path to the socket + :return: a socket stream object + :raises ConnectionFailed: if the connection fails + + """ + path = os.fspath(path) + return await get_async_backend().connect_unix(path) + + +async def create_tcp_listener( + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC, + backlog: int = 65536, + reuse_port: bool = False, +) -> MultiListener[SocketStream]: + """ + Create a TCP socket listener. + + :param local_port: port number to listen on + :param local_host: IP address of the interface to listen on. If omitted, listen on + all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address + family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6. + :param family: address family (used if ``local_host`` was omitted) + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a multi-listener object containing one or more socket listeners + + """ + asynclib = get_async_backend() + backlog = min(backlog, 65536) + local_host = str(local_host) if local_host is not None else None + gai_res = await getaddrinfo( + local_host, + local_port, + family=family, + type=socket.SocketKind.SOCK_STREAM if sys.platform == "win32" else 0, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + listeners: list[SocketListener] = [] + try: + # The set() is here to work around a glibc bug: + # https://sourceware.org/bugzilla/show_bug.cgi?id=14969 + sockaddr: tuple[str, int] | tuple[str, int, int, int] + for fam, kind, *_, sockaddr in sorted(set(gai_res)): + # Workaround for an uvloop bug where we don't get the correct scope ID for + # IPv6 link-local addresses when passing type=socket.SOCK_STREAM to + # getaddrinfo(): https://github.com/MagicStack/uvloop/issues/539 + if sys.platform != "win32" and kind is not SocketKind.SOCK_STREAM: + continue + + raw_socket = socket.socket(fam) + raw_socket.setblocking(False) + + # For Windows, enable exclusive address use. For others, enable address + # reuse. + if sys.platform == "win32": + raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + else: + raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + if reuse_port: + raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + # If only IPv6 was requested, disable dual stack operation + if fam == socket.AF_INET6: + raw_socket.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) + + # Workaround for #554 + if "%" in sockaddr[0]: + addr, scope_id = sockaddr[0].split("%", 1) + sockaddr = (addr, sockaddr[1], 0, int(scope_id)) + + raw_socket.bind(sockaddr) + raw_socket.listen(backlog) + listener = asynclib.create_tcp_listener(raw_socket) + listeners.append(listener) + except BaseException: + for listener in listeners: + await listener.aclose() + + raise + + return MultiListener(listeners) + + +async def create_unix_listener( + path: str | bytes | PathLike[Any], + *, + mode: int | None = None, + backlog: int = 65536, +) -> SocketListener: + """ + Create a UNIX socket listener. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :return: a listener object + + .. versionchanged:: 3.0 + If a socket already exists on the file system in the given path, it will be + removed first. + + """ + backlog = min(backlog, 65536) + raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM) + try: + raw_socket.listen(backlog) + return get_async_backend().create_unix_listener(raw_socket) + except BaseException: + raw_socket.close() + raise + + +async def create_udp_socket( + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> UDPSocket: + """ + Create a UDP socket. + + If ``port`` has been given, the socket will be bound to this port on the local + machine, making this socket suitable for providing UDP based services. + + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a UDP socket + + """ + if family is AddressFamily.AF_UNSPEC and not local_host: + raise ValueError('Either "family" or "local_host" must be given') + + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + elif family is AddressFamily.AF_INET6: + local_address = ("::", 0) + else: + local_address = ("0.0.0.0", 0) + + sock = await get_async_backend().create_udp_socket( + family, local_address, None, reuse_port + ) + return cast(UDPSocket, sock) + + +async def create_connected_udp_socket( + remote_host: IPAddressType, + remote_port: int, + *, + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> ConnectedUDPSocket: + """ + Create a connected UDP socket. + + Connected UDP sockets can only communicate with the specified remote host/port, an + any packets sent from other sources are dropped. + + :param remote_host: remote host to set as the default target + :param remote_port: port on the remote host to set as the default target + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` or ``remote_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a connected UDP socket + + """ + local_address = None + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + + gai_res = await getaddrinfo( + str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + remote_address = gai_res[0][-1] + + sock = await get_async_backend().create_udp_socket( + family, local_address, remote_address, reuse_port + ) + return cast(ConnectedUDPSocket, sock) + + +async def create_unix_datagram_socket( + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> UNIXDatagramSocket: + """ + Create a UNIX datagram socket. + + Not available on Windows. + + If ``local_path`` has been given, the socket will be bound to this path, making this + socket suitable for receiving datagrams from other processes. Other processes can + send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a UNIX datagram socket + + """ + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket(raw_socket, None) + + +async def create_connected_unix_datagram_socket( + remote_path: str | bytes | PathLike[Any], + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> ConnectedUNIXDatagramSocket: + """ + Create a connected UNIX datagram socket. + + Connected datagram sockets can only communicate with the specified remote path. + + If ``local_path`` has been given, the socket will be bound to this path, making + this socket suitable for receiving datagrams from other processes. Other processes + can send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param remote_path: the path to set as the default target + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a connected UNIX datagram socket + + """ + remote_path = os.fspath(remote_path) + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket( + raw_socket, remote_path + ) + + +async def getaddrinfo( + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, +) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]: + """ + Look up a numeric IP address given a host name. + + Internationalized domain names are translated according to the (non-transitional) + IDNA 2008 standard. + + .. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of + (host, port), unlike what :func:`socket.getaddrinfo` does. + + :param host: host name + :param port: port number + :param family: socket family (`'AF_INET``, ...) + :param type: socket type (``SOCK_STREAM``, ...) + :param proto: protocol number + :param flags: flags to pass to upstream ``getaddrinfo()`` + :return: list of tuples containing (family, type, proto, canonname, sockaddr) + + .. seealso:: :func:`socket.getaddrinfo` + + """ + # Handle unicode hostnames + if isinstance(host, str): + try: + encoded_host: bytes | None = host.encode("ascii") + except UnicodeEncodeError: + import idna + + encoded_host = idna.encode(host, uts46=True) + else: + encoded_host = host + + gai_res = await get_async_backend().getaddrinfo( + encoded_host, port, family=family, type=type, proto=proto, flags=flags + ) + return [ + (family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr)) + for family, type, proto, canonname, sockaddr in gai_res + # filter out IPv6 results when IPv6 is disabled + if not isinstance(sockaddr[0], int) + ] + + +def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]: + """ + Look up the host name of an IP address. + + :param sockaddr: socket address (e.g. (ipaddress, port) for IPv4) + :param flags: flags to pass to upstream ``getnameinfo()`` + :return: a tuple of (host name, service name) + + .. seealso:: :func:`socket.getnameinfo` + + """ + return get_async_backend().getnameinfo(sockaddr, flags) + + +@deprecated("This function is deprecated; use `wait_readable` instead") +def wait_socket_readable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_readable` instead. + + Wait until the given socket has data to be read. + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become readable + + """ + return get_async_backend().wait_readable(sock.fileno()) + + +@deprecated("This function is deprecated; use `wait_writable` instead") +def wait_socket_writable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_writable` instead. + + Wait until the given socket can be written to. + + This does **NOT** work on Windows when using the asyncio backend with a proactor + event loop (default on py3.8+). + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become writable + + """ + return get_async_backend().wait_writable(sock.fileno()) + + +def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object has data to be read. + + On Unix systems, ``obj`` must either be an integer file descriptor, or else an + object with a ``.fileno()`` method which returns an integer file descriptor. Any + kind of file descriptor can be passed, though the exact semantics will depend on + your kernel. For example, this probably won't do anything useful for on-disk files. + + On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an + object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File + descriptors aren't supported, and neither are handles that refer to anything besides + a ``SOCKET``. + + On backends where this functionality is not natively provided (asyncio + ``ProactorEventLoop`` on Windows), it is provided using a separate selector thread + which is set to shut down when the interpreter shuts down. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become readable + + """ + return get_async_backend().wait_readable(obj) + + +def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object can be written to. + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become writable + + .. seealso:: See the documentation of :func:`wait_readable` for the definition of + ``obj`` and notes on backend compatibility. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + """ + return get_async_backend().wait_writable(obj) + + +def notify_closing(obj: FileDescriptorLike) -> None: + """ + Call this before closing a file descriptor (on Unix) or socket (on + Windows). This will cause any `wait_readable` or `wait_writable` + calls on the given object to immediately wake up and raise + `~anyio.ClosedResourceError`. + + This doesn't actually close the object – you still have to do that + yourself afterwards. Also, you want to be careful to make sure no + new tasks start waiting on the object in between when you call this + and when it's actually closed. So to close something properly, you + usually want to do these steps in order: + + 1. Explicitly mark the object as closed, so that any new attempts + to use it will abort before they start. + 2. Call `notify_closing` to wake up any already-existing users. + 3. Actually close the object. + + It's also possible to do them in a different order if that's more + convenient, *but only if* you make sure not to have any checkpoints in + between the steps. This way they all happen in a single atomic + step, so other tasks won't be able to tell what order they happened + in anyway. + + :param obj: an object with a ``.fileno()`` method or an integer handle + + """ + get_async_backend().notify_closing(obj) + + +# +# Private API +# + + +def convert_ipv6_sockaddr( + sockaddr: tuple[str, int, int, int] | tuple[str, int], +) -> tuple[str, int]: + """ + Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format. + + If the scope ID is nonzero, it is added to the address, separated with ``%``. + Otherwise the flow id and scope id are simply cut off from the tuple. + Any other kinds of socket addresses are returned as-is. + + :param sockaddr: the result of :meth:`~socket.socket.getsockname` + :return: the converted socket address + + """ + # This is more complicated than it should be because of MyPy + if isinstance(sockaddr, tuple) and len(sockaddr) == 4: + host, port, flowinfo, scope_id = sockaddr + if scope_id: + # PyPy (as of v7.3.11) leaves the interface name in the result, so + # we discard it and only get the scope ID from the end + # (https://foss.heptapod.net/pypy/pypy/-/issues/3938) + host = host.split("%")[0] + + # Add scope_id to the address + return f"{host}%{scope_id}", port + else: + return host, port + else: + return sockaddr + + +async def setup_unix_local_socket( + path: None | str | bytes | PathLike[Any], + mode: int | None, + socktype: int, +) -> socket.socket: + """ + Create a UNIX local socket object, deleting the socket at the given path if it + exists. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM + + """ + path_str: str | None + if path is not None: + path_str = os.fsdecode(path) + + # Linux abstract namespace sockets aren't backed by a concrete file so skip stat call + if not path_str.startswith("\0"): + # Copied from pathlib... + try: + stat_result = os.stat(path) + except OSError as e: + if e.errno not in ( + errno.ENOENT, + errno.ENOTDIR, + errno.EBADF, + errno.ELOOP, + ): + raise + else: + if stat.S_ISSOCK(stat_result.st_mode): + os.unlink(path) + else: + path_str = None + + raw_socket = socket.socket(socket.AF_UNIX, socktype) + raw_socket.setblocking(False) + + if path_str is not None: + try: + await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True) + if mode is not None: + await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True) + except BaseException: + raw_socket.close() + raise + + return raw_socket + + +@dataclass +class TCPConnectable(ByteStreamConnectable): + """ + Connects to a TCP server at the given host and port. + + :param host: host name or IP address of the server + :param port: TCP port number of the server + """ + + host: str | IPv4Address | IPv6Address + port: int + + def __post_init__(self) -> None: + if self.port < 1 or self.port > 65535: + raise ValueError("TCP port number out of range") + + @override + async def connect(self) -> SocketStream: + try: + return await connect_tcp(self.host, self.port) + except OSError as exc: + raise ConnectionFailed( + f"error connecting to {self.host}:{self.port}: {exc}" + ) from exc + + +@dataclass +class UNIXConnectable(ByteStreamConnectable): + """ + Connects to a UNIX domain socket at the given path. + + :param path: the file system path of the socket + """ + + path: str | bytes | PathLike[str] | PathLike[bytes] + + @override + async def connect(self) -> UNIXSocketStream: + try: + return await connect_unix(self.path) + except OSError as exc: + raise ConnectionFailed(f"error connecting to {self.path!r}: {exc}") from exc + + +def as_connectable( + remote: ByteStreamConnectable + | tuple[str | IPv4Address | IPv6Address, int] + | str + | bytes + | PathLike[str], + /, + *, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_hostname: str | None = None, + tls_standard_compatible: bool = True, +) -> ByteStreamConnectable: + """ + Return a byte stream connectable from the given object. + + If a bytestream connectable is given, it is returned unchanged. + If a tuple of (host, port) is given, a TCP connectable is returned. + If a string or bytes path is given, a UNIX connectable is returned. + + If ``tls=True``, the connectable will be wrapped in a + :class:`~.streams.tls.TLSConnectable`. + + :param remote: a connectable, a tuple of (host, port) or a path to a UNIX socket + :param tls: if ``True``, wrap the plaintext connectable in a + :class:`~.streams.tls.TLSConnectable`, using the provided TLS settings) + :param ssl_context: if ``tls=True``, the SSLContext object to use (if not provided, + a secure default will be created) + :param tls_hostname: if ``tls=True``, host name of the server to use for checking + the server certificate (defaults to the host portion of the address for TCP + connectables) + :param tls_standard_compatible: if ``False`` and ``tls=True``, makes the TLS stream + skip the closing handshake when closing the connection, so it won't raise an + exception if the server does the same + + """ + connectable: TCPConnectable | UNIXConnectable | TLSConnectable + if isinstance(remote, ByteStreamConnectable): + return remote + elif isinstance(remote, tuple) and len(remote) == 2: + connectable = TCPConnectable(*remote) + elif isinstance(remote, (str, bytes, PathLike)): + connectable = UNIXConnectable(remote) + else: + raise TypeError(f"cannot convert {remote!r} to a connectable") + + if tls: + if not tls_hostname and isinstance(connectable, TCPConnectable): + tls_hostname = str(connectable.host) + + connectable = TLSConnectable( + connectable, + ssl_context=ssl_context, + hostname=tls_hostname, + standard_compatible=tls_standard_compatible, + ) + + return connectable diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_streams.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9814e5a91d64e081ecef323a761ed42d3e64de --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_streams.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import math +from typing import TypeVar +from warnings import warn + +from ..streams.memory import ( + MemoryObjectReceiveStream, + MemoryObjectSendStream, + MemoryObjectStreamState, +) + +T_Item = TypeVar("T_Item") + + +class create_memory_object_stream( + tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]], +): + """ + Create a memory object stream. + + The stream's item type can be annotated like + :func:`create_memory_object_stream[T_Item]`. + + :param max_buffer_size: number of items held in the buffer until ``send()`` starts + blocking + :param item_type: old way of marking the streams with the right generic type for + static typing (does nothing on AnyIO 4) + + .. deprecated:: 4.0 + Use ``create_memory_object_stream[YourItemType](...)`` instead. + :return: a tuple of (send stream, receive stream) + + """ + + def __new__( # type: ignore[misc] + cls, max_buffer_size: float = 0, item_type: object = None + ) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]: + if max_buffer_size != math.inf and not isinstance(max_buffer_size, int): + raise ValueError("max_buffer_size must be either an integer or math.inf") + if max_buffer_size < 0: + raise ValueError("max_buffer_size cannot be negative") + if item_type is not None: + warn( + "The item_type argument has been deprecated in AnyIO 4.0. " + "Use create_memory_object_stream[YourItemType](...) instead.", + DeprecationWarning, + stacklevel=2, + ) + + state = MemoryObjectStreamState[T_Item](max_buffer_size) + return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state)) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_subprocesses.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..36d9b306c992b83a8033c0ee66daa141d23d010c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_subprocesses.py @@ -0,0 +1,202 @@ +from __future__ import annotations + +import sys +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from io import BytesIO +from os import PathLike +from subprocess import PIPE, CalledProcessError, CompletedProcess +from typing import IO, Any, Union, cast + +from ..abc import Process +from ._eventloop import get_async_backend +from ._tasks import create_task_group + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +StrOrBytesPath: TypeAlias = Union[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, + ) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_synchronization.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..caa6efc66fb42e47b8289ff8fbc47a498a59780d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_synchronization.py @@ -0,0 +1,732 @@ +from __future__ import annotations + +import math +from collections import deque +from dataclasses import dataclass +from types import TracebackType + +from sniffio import AsyncLibraryNotFoundError + +from ..lowlevel import checkpoint +from ._eventloop import get_async_backend +from ._exceptions import BusyResourceError +from ._tasks import CancelScope +from ._testing import TaskInfo, get_current_task + + +@dataclass(frozen=True) +class EventStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait` + """ + + tasks_waiting: int + + +@dataclass(frozen=True) +class CapacityLimiterStatistics: + """ + :ivar int borrowed_tokens: number of tokens currently borrowed by tasks + :ivar float total_tokens: total number of available tokens + :ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from + this limiter + :ivar int tasks_waiting: number of tasks waiting on + :meth:`~.CapacityLimiter.acquire` or + :meth:`~.CapacityLimiter.acquire_on_behalf_of` + """ + + borrowed_tokens: int + total_tokens: float + borrowers: tuple[object, ...] + tasks_waiting: int + + +@dataclass(frozen=True) +class LockStatistics: + """ + :ivar bool locked: flag indicating if this lock is locked or not + :ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the + lock is not held by any task) + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire` + """ + + locked: bool + owner: TaskInfo | None + tasks_waiting: int + + +@dataclass(frozen=True) +class ConditionStatistics: + """ + :ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait` + :ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying + :class:`~.Lock` + """ + + tasks_waiting: int + lock_statistics: LockStatistics + + +@dataclass(frozen=True) +class SemaphoreStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire` + + """ + + tasks_waiting: int + + +class Event: + def __new__(cls) -> Event: + try: + return get_async_backend().create_event() + except AsyncLibraryNotFoundError: + return EventAdapter() + + def set(self) -> None: + """Set the flag, notifying all listeners.""" + raise NotImplementedError + + def is_set(self) -> bool: + """Return ``True`` if the flag is set, ``False`` if not.""" + raise NotImplementedError + + async def wait(self) -> None: + """ + Wait until the flag has been set. + + If the flag has already been set when this method is called, it returns + immediately. + + """ + raise NotImplementedError + + def statistics(self) -> EventStatistics: + """Return statistics about the current state of this event.""" + raise NotImplementedError + + +class EventAdapter(Event): + _internal_event: Event | None = None + _is_set: bool = False + + def __new__(cls) -> EventAdapter: + return object.__new__(cls) + + @property + def _event(self) -> Event: + if self._internal_event is None: + self._internal_event = get_async_backend().create_event() + if self._is_set: + self._internal_event.set() + + return self._internal_event + + def set(self) -> None: + if self._internal_event is None: + self._is_set = True + else: + self._event.set() + + def is_set(self) -> bool: + if self._internal_event is None: + return self._is_set + + return self._internal_event.is_set() + + async def wait(self) -> None: + await self._event.wait() + + def statistics(self) -> EventStatistics: + if self._internal_event is None: + return EventStatistics(tasks_waiting=0) + + return self._internal_event.statistics() + + +class Lock: + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + try: + return get_async_backend().create_lock(fast_acquire=fast_acquire) + except AsyncLibraryNotFoundError: + return LockAdapter(fast_acquire=fast_acquire) + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Release the lock.""" + raise NotImplementedError + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + raise NotImplementedError + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class LockAdapter(Lock): + _internal_lock: Lock | None = None + + def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False): + self._fast_acquire = fast_acquire + + @property + def _lock(self) -> Lock: + if self._internal_lock is None: + self._internal_lock = get_async_backend().create_lock( + fast_acquire=self._fast_acquire + ) + + return self._internal_lock + + async def __aenter__(self) -> None: + await self._lock.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self._internal_lock is not None: + self._internal_lock.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + await self._lock.acquire() + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + + def release(self) -> None: + """Release the lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + return self._lock.locked() + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + + """ + if self._internal_lock is None: + return LockStatistics(False, None, 0) + + return self._internal_lock.statistics() + + +class Condition: + _owner_task: TaskInfo | None = None + + def __init__(self, lock: Lock | None = None): + self._lock = lock or Lock() + self._waiters: deque[Event] = deque() + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + def _check_acquired(self) -> None: + if self._owner_task != get_current_task(): + raise RuntimeError("The current task is not holding the underlying lock") + + async def acquire(self) -> None: + """Acquire the underlying lock.""" + await self._lock.acquire() + self._owner_task = get_current_task() + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + self._owner_task = get_current_task() + + def release(self) -> None: + """Release the underlying lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is set.""" + return self._lock.locked() + + def notify(self, n: int = 1) -> None: + """Notify exactly n listeners.""" + self._check_acquired() + for _ in range(n): + try: + event = self._waiters.popleft() + except IndexError: + break + + event.set() + + def notify_all(self) -> None: + """Notify all the listeners.""" + self._check_acquired() + for event in self._waiters: + event.set() + + self._waiters.clear() + + async def wait(self) -> None: + """Wait for a notification.""" + await checkpoint() + event = Event() + self._waiters.append(event) + self.release() + try: + await event.wait() + except BaseException: + if not event.is_set(): + self._waiters.remove(event) + + raise + finally: + with CancelScope(shield=True): + await self.acquire() + + def statistics(self) -> ConditionStatistics: + """ + Return statistics about the current state of this condition. + + .. versionadded:: 3.0 + """ + return ConditionStatistics(len(self._waiters), self._lock.statistics()) + + +class Semaphore: + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + try: + return get_async_backend().create_semaphore( + initial_value, max_value=max_value, fast_acquire=fast_acquire + ) + except AsyncLibraryNotFoundError: + return SemaphoreAdapter(initial_value, max_value=max_value) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ): + if not isinstance(initial_value, int): + raise TypeError("initial_value must be an integer") + if initial_value < 0: + raise ValueError("initial_value must be >= 0") + if max_value is not None: + if not isinstance(max_value, int): + raise TypeError("max_value must be an integer or None") + if max_value < initial_value: + raise ValueError( + "max_value must be equal to or higher than initial_value" + ) + + self._fast_acquire = fast_acquire + + async def __aenter__(self) -> Semaphore: + await self.acquire() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Decrement the semaphore value, blocking if necessary.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Increment the semaphore value.""" + raise NotImplementedError + + @property + def value(self) -> int: + """The current value of the semaphore.""" + raise NotImplementedError + + @property + def max_value(self) -> int | None: + """The maximum value of the semaphore.""" + raise NotImplementedError + + def statistics(self) -> SemaphoreStatistics: + """ + Return statistics about the current state of this semaphore. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class SemaphoreAdapter(Semaphore): + _internal_semaphore: Semaphore | None = None + + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> SemaphoreAdapter: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> None: + super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) + self._initial_value = initial_value + self._max_value = max_value + + @property + def _semaphore(self) -> Semaphore: + if self._internal_semaphore is None: + self._internal_semaphore = get_async_backend().create_semaphore( + self._initial_value, max_value=self._max_value + ) + + return self._internal_semaphore + + async def acquire(self) -> None: + await self._semaphore.acquire() + + def acquire_nowait(self) -> None: + self._semaphore.acquire_nowait() + + def release(self) -> None: + self._semaphore.release() + + @property + def value(self) -> int: + if self._internal_semaphore is None: + return self._initial_value + + return self._semaphore.value + + @property + def max_value(self) -> int | None: + return self._max_value + + def statistics(self) -> SemaphoreStatistics: + if self._internal_semaphore is None: + return SemaphoreStatistics(tasks_waiting=0) + + return self._semaphore.statistics() + + +class CapacityLimiter: + def __new__(cls, total_tokens: float) -> CapacityLimiter: + try: + return get_async_backend().create_capacity_limiter(total_tokens) + except AsyncLibraryNotFoundError: + return CapacityLimiterAdapter(total_tokens) + + async def __aenter__(self) -> None: + raise NotImplementedError + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + raise NotImplementedError + + @property + def total_tokens(self) -> float: + """ + The total number of tokens available for borrowing. + + This is a read-write property. If the total number of tokens is increased, the + proportionate number of tasks waiting on this limiter will be granted their + tokens. + + .. versionchanged:: 3.0 + The property is now writable. + + """ + raise NotImplementedError + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + raise NotImplementedError + + @property + def borrowed_tokens(self) -> int: + """The number of tokens that have currently been borrowed.""" + raise NotImplementedError + + @property + def available_tokens(self) -> float: + """The number of tokens currently available to be borrowed""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire a token for the current task without waiting for one to become + available. + + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + """ + Acquire a token without waiting for one to become available. + + :param borrower: the entity borrowing a token + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + async def acquire(self) -> None: + """ + Acquire a token for the current task, waiting if necessary for one to become + available. + + """ + raise NotImplementedError + + async def acquire_on_behalf_of(self, borrower: object) -> None: + """ + Acquire a token, waiting if necessary for one to become available. + + :param borrower: the entity borrowing a token + + """ + raise NotImplementedError + + def release(self) -> None: + """ + Release the token held by the current task. + + :raises RuntimeError: if the current task has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def release_on_behalf_of(self, borrower: object) -> None: + """ + Release the token held by the given borrower. + + :raises RuntimeError: if the borrower has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def statistics(self) -> CapacityLimiterStatistics: + """ + Return statistics about the current state of this limiter. + + .. versionadded:: 3.0 + + """ + raise NotImplementedError + + +class CapacityLimiterAdapter(CapacityLimiter): + _internal_limiter: CapacityLimiter | None = None + + def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter: + return object.__new__(cls) + + def __init__(self, total_tokens: float) -> None: + self.total_tokens = total_tokens + + @property + def _limiter(self) -> CapacityLimiter: + if self._internal_limiter is None: + self._internal_limiter = get_async_backend().create_capacity_limiter( + self._total_tokens + ) + + return self._internal_limiter + + async def __aenter__(self) -> None: + await self._limiter.__aenter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + return await self._limiter.__aexit__(exc_type, exc_val, exc_tb) + + @property + def total_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + if not isinstance(value, int) and value is not math.inf: + raise TypeError("total_tokens must be an int or math.inf") + elif value < 1: + raise ValueError("total_tokens must be >= 1") + + if self._internal_limiter is None: + self._total_tokens = value + return + + self._limiter.total_tokens = value + + @property + def borrowed_tokens(self) -> int: + if self._internal_limiter is None: + return 0 + + return self._internal_limiter.borrowed_tokens + + @property + def available_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.available_tokens + + def acquire_nowait(self) -> None: + self._limiter.acquire_nowait() + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + self._limiter.acquire_on_behalf_of_nowait(borrower) + + async def acquire(self) -> None: + await self._limiter.acquire() + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await self._limiter.acquire_on_behalf_of(borrower) + + def release(self) -> None: + self._limiter.release() + + def release_on_behalf_of(self, borrower: object) -> None: + self._limiter.release_on_behalf_of(borrower) + + def statistics(self) -> CapacityLimiterStatistics: + if self._internal_limiter is None: + return CapacityLimiterStatistics( + borrowed_tokens=0, + total_tokens=self.total_tokens, + borrowers=(), + tasks_waiting=0, + ) + + return self._internal_limiter.statistics() + + +class ResourceGuard: + """ + A context manager for ensuring that a resource is only used by a single task at a + time. + + Entering this context manager while the previous has not exited it yet will trigger + :exc:`BusyResourceError`. + + :param action: the action to guard against (visible in the :exc:`BusyResourceError` + when triggered, e.g. "Another task is already {action} this resource") + + .. versionadded:: 4.1 + """ + + __slots__ = "action", "_guarded" + + def __init__(self, action: str = "using"): + self.action: str = action + self._guarded = False + + def __enter__(self) -> None: + if self._guarded: + raise BusyResourceError(self.action) + + self._guarded = True + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._guarded = False diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_tasks.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..fe49015102b3c8d6c964dc1d85e1da2b42279112 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_tasks.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import math +from collections.abc import Generator +from contextlib import contextmanager +from types import TracebackType + +from ..abc._tasks import TaskGroup, TaskStatus +from ._eventloop import get_async_backend + + +class _IgnoredTaskStatus(TaskStatus[object]): + def started(self, value: object = None) -> None: + pass + + +TASK_STATUS_IGNORED = _IgnoredTaskStatus() + + +class CancelScope: + """ + Wraps a unit of work that can be made separately cancellable. + + :param deadline: The time (clock value) when this scope is cancelled automatically + :param shield: ``True`` to shield the cancel scope from external cancellation + """ + + def __new__( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline) + + def cancel(self) -> None: + """Cancel this scope immediately.""" + raise NotImplementedError + + @property + def deadline(self) -> float: + """ + The time (clock value) when this scope is cancelled automatically. + + Will be ``float('inf')`` if no timeout has been set. + + """ + raise NotImplementedError + + @deadline.setter + def deadline(self, value: float) -> None: + raise NotImplementedError + + @property + def cancel_called(self) -> bool: + """``True`` if :meth:`cancel` has been called.""" + raise NotImplementedError + + @property + def cancelled_caught(self) -> bool: + """ + ``True`` if this scope suppressed a cancellation exception it itself raised. + + This is typically used to check if any work was interrupted, or to see if the + scope was cancelled due to its deadline being reached. The value will, however, + only be ``True`` if the cancellation was triggered by the scope itself (and not + an outer scope). + + """ + raise NotImplementedError + + @property + def shield(self) -> bool: + """ + ``True`` if this scope is shielded from external cancellation. + + While a scope is shielded, it will not receive cancellations from outside. + + """ + raise NotImplementedError + + @shield.setter + def shield(self, value: bool) -> None: + raise NotImplementedError + + def __enter__(self) -> CancelScope: + raise NotImplementedError + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + raise NotImplementedError + + +@contextmanager +def fail_after( + delay: float | None, shield: bool = False +) -> Generator[CancelScope, None, None]: + """ + Create a context manager which raises a :class:`TimeoutError` if does not finish in + time. + + :param delay: maximum allowed time (in seconds) before raising the exception, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a context manager that yields a cancel scope + :rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\] + + """ + current_time = get_async_backend().current_time + deadline = (current_time() + delay) if delay is not None else math.inf + with get_async_backend().create_cancel_scope( + deadline=deadline, shield=shield + ) as cancel_scope: + yield cancel_scope + + if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline: + raise TimeoutError + + +def move_on_after(delay: float | None, shield: bool = False) -> CancelScope: + """ + Create a cancel scope with a deadline that expires after the given delay. + + :param delay: maximum allowed time (in seconds) before exiting the context block, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a cancel scope + + """ + deadline = ( + (get_async_backend().current_time() + delay) if delay is not None else math.inf + ) + return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield) + + +def current_effective_deadline() -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the current + task. + + :return: a clock value from the event loop's internal clock (or ``float('inf')`` if + there is no deadline in effect, or ``float('-inf')`` if the current scope has + been cancelled) + :rtype: float + + """ + return get_async_backend().current_effective_deadline() + + +def create_task_group() -> TaskGroup: + """ + Create a task group. + + :return: a task group + + """ + return get_async_backend().create_task_group() diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_tempfile.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_tempfile.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb6b14a9a8eae9dcaa66eb68ac36d2084617877 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_tempfile.py @@ -0,0 +1,616 @@ +from __future__ import annotations + +import os +import sys +import tempfile +from collections.abc import Iterable +from io import BytesIO, TextIOWrapper +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Generic, + overload, +) + +from .. import to_thread +from .._core._fileio import AsyncFile +from ..lowlevel import checkpoint_if_cancelled + +if TYPE_CHECKING: + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer + + +class TemporaryFile(Generic[AnyStr]): + """ + An asynchronous temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager interface to a temporary file. + The file is created using Python's standard `tempfile.TemporaryFile` function in a + background thread, and is wrapped as an asynchronous file using `AsyncFile`. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: TemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: TemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + mode: OpenTextMode | OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self.mode = mode + self.buffering = buffering + self.encoding = encoding + self.newline = newline + self.suffix: str | None = suffix + self.prefix: str | None = prefix + self.dir: str | None = dir + self.errors = errors + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile( + self.mode, + self.buffering, + self.encoding, + self.newline, + self.suffix, + self.prefix, + self.dir, + errors=self.errors, + ) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class NamedTemporaryFile(Generic[AnyStr]): + """ + An asynchronous named temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager for a temporary file with a + visible name in the file system. It uses Python's standard + :func:`~tempfile.NamedTemporaryFile` function and wraps the file object with + :class:`AsyncFile` for asynchronous operations. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param delete: Whether to delete the file when it is closed. + :param errors: The error handling scheme used for encoding/decoding errors. + :param delete_on_close: (Python 3.12+) Whether to delete the file on close. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: NamedTemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + @overload + def __init__( + self: NamedTemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + + def __init__( + self, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + delete: bool = True, + *, + errors: str | None = None, + delete_on_close: bool = True, + ) -> None: + self._params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "delete": delete, + "errors": errors, + } + if sys.version_info >= (3, 12): + self._params["delete_on_close"] = delete_on_close + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.NamedTemporaryFile(**self._params) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class SpooledTemporaryFile(AsyncFile[AnyStr]): + """ + An asynchronous spooled temporary file that starts in memory and is spooled to disk. + + This class provides an asynchronous interface to a spooled temporary file, much like + Python's standard :class:`~tempfile.SpooledTemporaryFile`. It supports asynchronous + write operations and provides a method to force a rollover to disk. + + :param max_size: Maximum size in bytes before the file is rolled over to disk. + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file (text mode only). + :param newline: Controls how universal newlines mode works (text mode only). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _rolled: bool = False + + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = ..., + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = ..., + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + max_size: int = 0, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self._tempfile_params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "errors": errors, + } + self._max_size = max_size + if "b" in mode: + super().__init__(BytesIO()) # type: ignore[arg-type] + else: + super().__init__( + TextIOWrapper( # type: ignore[arg-type] + BytesIO(), + encoding=encoding, + errors=errors, + newline=newline, + write_through=True, + ) + ) + + async def aclose(self) -> None: + if not self._rolled: + self._fp.close() + return + + await super().aclose() + + async def _check(self) -> None: + if self._rolled or self._fp.tell() <= self._max_size: + return + + await self.rollover() + + async def rollover(self) -> None: + if self._rolled: + return + + self._rolled = True + buffer = self._fp + buffer.seek(0) + self._fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile(**self._tempfile_params) + ) + await self.write(buffer.read()) + buffer.close() + + @property + def closed(self) -> bool: + return self._fp.closed + + async def read(self, size: int = -1) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read(size) + + return await super().read(size) # type: ignore[return-value] + + async def read1(self: SpooledTemporaryFile[bytes], size: int = -1) -> bytes: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read1(size) + + return await super().read1(size) + + async def readline(self) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readline() + + return await super().readline() # type: ignore[return-value] + + async def readlines(self) -> list[AnyStr]: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readlines() + + return await super().readlines() # type: ignore[return-value] + + async def readinto(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto(b) + + async def readinto1(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto1(b) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.seek(offset, whence) + + return await super().seek(offset, whence) + + async def tell(self) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.tell() + + return await super().tell() + + async def truncate(self, size: int | None = None) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.truncate(size) + + return await super().truncate(size) + + @overload + async def write(self: SpooledTemporaryFile[bytes], b: ReadableBuffer) -> int: ... + @overload + async def write(self: SpooledTemporaryFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + """ + Asynchronously write data to the spooled temporary file. + + If the file has not yet been rolled over, the data is written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param s: The data to write. + :return: The number of bytes written. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.write(b) + await self._check() + return result + + return await super().write(b) # type: ignore[misc] + + @overload + async def writelines( + self: SpooledTemporaryFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + @overload + async def writelines( + self: SpooledTemporaryFile[str], lines: Iterable[str] + ) -> None: ... + + async def writelines(self, lines: Iterable[str] | Iterable[ReadableBuffer]) -> None: + """ + Asynchronously write a list of lines to the spooled temporary file. + + If the file has not yet been rolled over, the lines are written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param lines: An iterable of lines to write. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.writelines(lines) + await self._check() + return result + + return await super().writelines(lines) # type: ignore[misc] + + +class TemporaryDirectory(Generic[AnyStr]): + """ + An asynchronous temporary directory that is created and cleaned up automatically. + + This class provides an asynchronous context manager for creating a temporary + directory. It wraps Python's standard :class:`~tempfile.TemporaryDirectory` to + perform directory creation and cleanup operations in a background thread. + + :param suffix: Suffix to be added to the temporary directory name. + :param prefix: Prefix to be added to the temporary directory name. + :param dir: The parent directory where the temporary directory is created. + :param ignore_cleanup_errors: Whether to ignore errors during cleanup + (Python 3.10+). + :param delete: Whether to delete the directory upon closing (Python 3.12+). + """ + + def __init__( + self, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + *, + ignore_cleanup_errors: bool = False, + delete: bool = True, + ) -> None: + self.suffix: AnyStr | None = suffix + self.prefix: AnyStr | None = prefix + self.dir: AnyStr | None = dir + self.ignore_cleanup_errors = ignore_cleanup_errors + self.delete = delete + + self._tempdir: tempfile.TemporaryDirectory | None = None + + async def __aenter__(self) -> str: + params: dict[str, Any] = { + "suffix": self.suffix, + "prefix": self.prefix, + "dir": self.dir, + } + if sys.version_info >= (3, 10): + params["ignore_cleanup_errors"] = self.ignore_cleanup_errors + + if sys.version_info >= (3, 12): + params["delete"] = self.delete + + self._tempdir = await to_thread.run_sync( + lambda: tempfile.TemporaryDirectory(**params) + ) + return await to_thread.run_sync(self._tempdir.__enter__) + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if self._tempdir is not None: + await to_thread.run_sync( + self._tempdir.__exit__, exc_type, exc_value, traceback + ) + + async def cleanup(self) -> None: + if self._tempdir is not None: + await to_thread.run_sync(self._tempdir.cleanup) + + +@overload +async def mkstemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + text: bool = False, +) -> tuple[int, str]: ... + + +@overload +async def mkstemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, + text: bool = False, +) -> tuple[int, bytes]: ... + + +async def mkstemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + text: bool = False, +) -> tuple[int, str | bytes]: + """ + Asynchronously create a temporary file and return an OS-level handle and the file + name. + + This function wraps `tempfile.mkstemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the file name. + :param prefix: Prefix to be added to the file name. + :param dir: Directory in which the temporary file is created. + :param text: Whether the file is opened in text mode. + :return: A tuple containing the file descriptor and the file name. + + """ + return await to_thread.run_sync(tempfile.mkstemp, suffix, prefix, dir, text) + + +@overload +async def mkdtemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, +) -> str: ... + + +@overload +async def mkdtemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, +) -> bytes: ... + + +async def mkdtemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, +) -> str | bytes: + """ + Asynchronously create a temporary directory and return its path. + + This function wraps `tempfile.mkdtemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the directory name. + :param prefix: Prefix to be added to the directory name. + :param dir: Parent directory where the temporary directory is created. + :return: The path of the created temporary directory. + + """ + return await to_thread.run_sync(tempfile.mkdtemp, suffix, prefix, dir) + + +async def gettempdir() -> str: + """ + Asynchronously return the name of the directory used for temporary files. + + This function wraps `tempfile.gettempdir` and executes it in a background thread. + + :return: The path of the temporary directory as a string. + + """ + return await to_thread.run_sync(tempfile.gettempdir) + + +async def gettempdirb() -> bytes: + """ + Asynchronously return the name of the directory used for temporary files in bytes. + + This function wraps `tempfile.gettempdirb` and executes it in a background thread. + + :return: The path of the temporary directory as bytes. + + """ + return await to_thread.run_sync(tempfile.gettempdirb) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_testing.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..9e28b22766d8a4bd0af8949445f3f1aa2f684c6a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_testing.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +from collections.abc import Awaitable, Generator +from typing import Any, cast + +from ._eventloop import get_async_backend + + +class TaskInfo: + """ + Represents an asynchronous task. + + :ivar int id: the unique identifier of the task + :ivar parent_id: the identifier of the parent task, if any + :vartype parent_id: Optional[int] + :ivar str name: the description of the task (if any) + :ivar ~collections.abc.Coroutine coro: the coroutine object of the task + """ + + __slots__ = "_name", "id", "parent_id", "name", "coro" + + def __init__( + self, + id: int, + parent_id: int | None, + name: str | None, + coro: Generator[Any, Any, Any] | Awaitable[Any], + ): + func = get_current_task + self._name = f"{func.__module__}.{func.__qualname__}" + self.id: int = id + self.parent_id: int | None = parent_id + self.name: str | None = name + self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro + + def __eq__(self, other: object) -> bool: + if isinstance(other, TaskInfo): + return self.id == other.id + + return NotImplemented + + def __hash__(self) -> int: + return hash(self.id) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})" + + def has_pending_cancellation(self) -> bool: + """ + Return ``True`` if the task has a cancellation pending, ``False`` otherwise. + + """ + return False + + +def get_current_task() -> TaskInfo: + """ + Return the current task. + + :return: a representation of the current task + + """ + return get_async_backend().get_current_task() + + +def get_running_tasks() -> list[TaskInfo]: + """ + Return a list of running tasks in the current event loop. + + :return: a list of task info objects + + """ + return cast("list[TaskInfo]", get_async_backend().get_running_tasks()) + + +async def wait_all_tasks_blocked() -> None: + """Wait until all other tasks are waiting for something.""" + await get_async_backend().wait_all_tasks_blocked() diff --git a/miniconda3/lib/python3.13/site-packages/anyio/_core/_typedattr.py b/miniconda3/lib/python3.13/site-packages/anyio/_core/_typedattr.py new file mode 100644 index 0000000000000000000000000000000000000000..f358a448cb12739fd4eda4f4859d3a24ddd1de63 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/_core/_typedattr.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import Any, TypeVar, final, overload + +from ._exceptions import TypedAttributeLookupError + +T_Attr = TypeVar("T_Attr") +T_Default = TypeVar("T_Default") +undefined = object() + + +def typed_attribute() -> Any: + """Return a unique object, used to mark typed attributes.""" + return object() + + +class TypedAttributeSet: + """ + Superclass for typed attribute collections. + + Checks that every public attribute of every subclass has a type annotation. + """ + + def __init_subclass__(cls) -> None: + annotations: dict[str, Any] = getattr(cls, "__annotations__", {}) + for attrname in dir(cls): + if not attrname.startswith("_") and attrname not in annotations: + raise TypeError( + f"Attribute {attrname!r} is missing its type annotation" + ) + + super().__init_subclass__() + + +class TypedAttributeProvider: + """Base class for classes that wish to provide typed extra attributes.""" + + @property + def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]: + """ + A mapping of the extra attributes to callables that return the corresponding + values. + + If the provider wraps another provider, the attributes from that wrapper should + also be included in the returned mapping (but the wrapper may override the + callables from the wrapped instance). + + """ + return {} + + @overload + def extra(self, attribute: T_Attr) -> T_Attr: ... + + @overload + def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ... + + @final + def extra(self, attribute: Any, default: object = undefined) -> object: + """ + extra(attribute, default=undefined) + + Return the value of the given typed extra attribute. + + :param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to + look for + :param default: the value that should be returned if no value is found for the + attribute + :raises ~anyio.TypedAttributeLookupError: if the search failed and no default + value was given + + """ + try: + getter = self.extra_attributes[attribute] + except KeyError: + if default is undefined: + raise TypedAttributeLookupError("Attribute not found") from None + else: + return default + + return getter() diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/__init__.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d560ce3f1fa45a7ee4a3bc8958aa59702caa9d0c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/__init__.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from ._eventloop import AsyncBackend as AsyncBackend +from ._resources import AsyncResource as AsyncResource +from ._sockets import ConnectedUDPSocket as ConnectedUDPSocket +from ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocket +from ._sockets import IPAddressType as IPAddressType +from ._sockets import IPSockAddrType as IPSockAddrType +from ._sockets import SocketAttribute as SocketAttribute +from ._sockets import SocketListener as SocketListener +from ._sockets import SocketStream as SocketStream +from ._sockets import UDPPacketType as UDPPacketType +from ._sockets import UDPSocket as UDPSocket +from ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketType +from ._sockets import UNIXDatagramSocket as UNIXDatagramSocket +from ._sockets import UNIXSocketStream as UNIXSocketStream +from ._streams import AnyByteReceiveStream as AnyByteReceiveStream +from ._streams import AnyByteSendStream as AnyByteSendStream +from ._streams import AnyByteStream as AnyByteStream +from ._streams import AnyByteStreamConnectable as AnyByteStreamConnectable +from ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStream +from ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStream +from ._streams import AnyUnreliableByteStream as AnyUnreliableByteStream +from ._streams import ByteReceiveStream as ByteReceiveStream +from ._streams import ByteSendStream as ByteSendStream +from ._streams import ByteStream as ByteStream +from ._streams import ByteStreamConnectable as ByteStreamConnectable +from ._streams import Listener as Listener +from ._streams import ObjectReceiveStream as ObjectReceiveStream +from ._streams import ObjectSendStream as ObjectSendStream +from ._streams import ObjectStream as ObjectStream +from ._streams import ObjectStreamConnectable as ObjectStreamConnectable +from ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStream +from ._streams import UnreliableObjectSendStream as UnreliableObjectSendStream +from ._streams import UnreliableObjectStream as UnreliableObjectStream +from ._subprocesses import Process as Process +from ._tasks import TaskGroup as TaskGroup +from ._tasks import TaskStatus as TaskStatus +from ._testing import TestRunner as TestRunner + +# Re-exported here, for backwards compatibility +# isort: off +from .._core._synchronization import ( + CapacityLimiter as CapacityLimiter, + Condition as Condition, + Event as Event, + Lock as Lock, + Semaphore as Semaphore, +) +from .._core._tasks import CancelScope as CancelScope +from ..from_thread import BlockingPortal as BlockingPortal + +# Re-export imports so they look like they live directly in this package +for __value in list(locals().values()): + if getattr(__value, "__module__", "").startswith("anyio.abc."): + __value.__module__ = __name__ + +del __value diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/_eventloop.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd9e08855e359542fe001b1165a0caf47a126dd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/_eventloop.py @@ -0,0 +1,418 @@ +from __future__ import annotations + +import math +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncIterator, Awaitable, Callable, Sequence +from contextlib import AbstractContextManager +from os import PathLike +from signal import Signals +from socket import AddressFamily, SocketKind, socket +from typing import ( + IO, + TYPE_CHECKING, + Any, + TypeVar, + Union, + overload, +) + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + + from .._core._synchronization import CapacityLimiter, Event, Lock, Semaphore + from .._core._tasks import CancelScope + from .._core._testing import TaskInfo + from ..from_thread import BlockingPortal + from ._sockets import ( + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, + ) + from ._subprocesses import Process + from ._tasks import TaskGroup + from ._testing import TestRunner + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +StrOrBytesPath: TypeAlias = Union[str, bytes, "PathLike[str]", "PathLike[bytes]"] + + +class AsyncBackend(metaclass=ABCMeta): + @classmethod + @abstractmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param kwargs: positional arguments to ``func`` + :param options: keyword arguments to call the backend ``run()`` implementation + with + :return: the return value of the coroutine function + """ + + @classmethod + @abstractmethod + def current_token(cls) -> object: + """ + + :return: + """ + + @classmethod + @abstractmethod + def current_time(cls) -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + """ + + @classmethod + @abstractmethod + def cancelled_exception_class(cls) -> type[BaseException]: + """Return the exception class that is raised in a task if it's cancelled.""" + + @classmethod + @abstractmethod + async def checkpoint(cls) -> None: + """ + Check if the task has been cancelled, and allow rescheduling of other tasks. + + This is effectively the same as running :meth:`checkpoint_if_cancelled` and then + :meth:`cancel_shielded_checkpoint`. + """ + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + """ + Check if the current task group has been cancelled. + + This will check if the task has been cancelled, but will not allow other tasks + to be scheduled if not. + + """ + if cls.current_effective_deadline() == -math.inf: + await cls.checkpoint() + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + """ + Allow the rescheduling of other tasks. + + This will give other tasks the opportunity to run, but without checking if the + current task group has been cancelled, unlike with :meth:`checkpoint`. + + """ + with cls.create_cancel_scope(shield=True): + await cls.sleep(0) + + @classmethod + @abstractmethod + async def sleep(cls, delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + """ + + @classmethod + @abstractmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + pass + + @classmethod + @abstractmethod + def current_effective_deadline(cls) -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the + current task. + + :return: + - a clock value from the event loop's internal clock + - ``inf`` if there is no deadline in effect + - ``-inf`` if the current scope has been cancelled + :rtype: float + """ + + @classmethod + @abstractmethod + def create_task_group(cls) -> TaskGroup: + pass + + @classmethod + @abstractmethod + def create_event(cls) -> Event: + pass + + @classmethod + @abstractmethod + def create_lock(cls, *, fast_acquire: bool) -> Lock: + pass + + @classmethod + @abstractmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + pass + + @classmethod + @abstractmethod + def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + async def run_sync_in_worker_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: CapacityLimiter | None = None, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def check_cancelled(cls) -> None: + pass + + @classmethod + @abstractmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def create_blocking_portal(cls) -> BlockingPortal: + pass + + @classmethod + @abstractmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + pass + + @classmethod + @abstractmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[Process]) -> None: + pass + + @classmethod + @abstractmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def connect_unix(cls, path: str | bytes) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + def create_tcp_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + def create_unix_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def create_udp_socket( + cls, + family: AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + pass + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: None + ) -> UNIXDatagramSocket: ... + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes + ) -> ConnectedUNIXDatagramSocket: ... + + @classmethod + @abstractmethod + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes | None + ) -> UNIXDatagramSocket | ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + pass + + @classmethod + @abstractmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + pass + + @classmethod + @abstractmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wrap_listener_socket(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def wrap_stream_socket(cls, sock: socket) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_unix_stream_socket(cls, sock: socket) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_udp_socket(cls, sock: socket) -> UDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_udp_socket(cls, sock: socket) -> ConnectedUDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_unix_datagram_socket(cls, sock: socket) -> UNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket + ) -> ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + pass + + @classmethod + @abstractmethod + def get_current_task(cls) -> TaskInfo: + pass + + @classmethod + @abstractmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + pass + + @classmethod + @abstractmethod + async def wait_all_tasks_blocked(cls) -> None: + pass + + @classmethod + @abstractmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + pass diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/_resources.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..10df115a7b9f975493476da763cc1e26dbd822e5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/_resources.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from types import TracebackType +from 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.""" diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/_sockets.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff60d4d9dfc3c15d416c9fc4a6b3b7f79a9fdb1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/_sockets.py @@ -0,0 +1,405 @@ +from __future__ import annotations + +import errno +import socket +import sys +from abc import abstractmethod +from collections.abc import Callable, Collection, Mapping +from contextlib import AsyncExitStack +from io import IOBase +from ipaddress import IPv4Address, IPv6Address +from socket import AddressFamily +from typing import Any, TypeVar, Union + +from .._core._eventloop import get_async_backend +from .._core._typedattr import ( + TypedAttributeProvider, + TypedAttributeSet, + typed_attribute, +) +from ._streams import ByteStream, Listener, UnreliableObjectStream +from ._tasks import TaskGroup + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +IPAddressType: TypeAlias = Union[str, IPv4Address, IPv6Address] +IPSockAddrType: TypeAlias = tuple[str, int] +SockAddrType: TypeAlias = Union[IPSockAddrType, str] +UDPPacketType: TypeAlias = tuple[bytes, IPSockAddrType] +UNIXDatagramPacketType: TypeAlias = tuple[bytes, str] +T_Retval = TypeVar("T_Retval") + + +def _validate_socket( + sock_or_fd: socket.socket | int, + sock_type: socket.SocketKind, + addr_family: socket.AddressFamily = socket.AF_UNSPEC, + *, + require_connected: bool = False, + require_bound: bool = False, +) -> socket.socket: + if isinstance(sock_or_fd, int): + try: + sock = socket.socket(fileno=sock_or_fd) + except OSError as exc: + if exc.errno == errno.ENOTSOCK: + raise ValueError( + "the file descriptor does not refer to a socket" + ) from exc + elif require_connected: + raise ValueError("the socket must be connected") from exc + elif require_bound: + raise ValueError("the socket must be bound to a local address") from exc + else: + raise + elif isinstance(sock_or_fd, socket.socket): + sock = sock_or_fd + else: + raise TypeError( + f"expected an int or socket, got {type(sock_or_fd).__qualname__} instead" + ) + + try: + if require_connected: + try: + sock.getpeername() + except OSError as exc: + raise ValueError("the socket must be connected") from exc + + if require_bound: + try: + if sock.family in (socket.AF_INET, socket.AF_INET6): + bound_addr = sock.getsockname()[1] + else: + bound_addr = sock.getsockname() + except OSError: + bound_addr = None + + if not bound_addr: + raise ValueError("the socket must be bound to a local address") + + if addr_family != socket.AF_UNSPEC and sock.family != addr_family: + raise ValueError( + f"address family mismatch: expected {addr_family.name}, got " + f"{sock.family.name}" + ) + + if sock.type != sock_type: + raise ValueError( + f"socket type mismatch: expected {sock_type.name}, got {sock.type.name}" + ) + except BaseException: + # Avoid ResourceWarning from the locally constructed socket object + if isinstance(sock_or_fd, int): + sock.detach() + + raise + + sock.setblocking(False) + return sock + + +class SocketAttribute(TypedAttributeSet): + """ + .. attribute:: family + :type: socket.AddressFamily + + the address family of the underlying socket + + .. attribute:: local_address + :type: tuple[str, int] | str + + the local address the underlying socket is connected to + + .. attribute:: local_port + :type: int + + for IP based sockets, the local port the underlying socket is bound to + + .. attribute:: raw_socket + :type: socket.socket + + the underlying stdlib socket object + + .. attribute:: remote_address + :type: tuple[str, int] | str + + the remote address the underlying socket is connected to + + .. attribute:: remote_port + :type: int + + for IP based sockets, the remote port the underlying socket is connected to + """ + + family: AddressFamily = typed_attribute() + local_address: SockAddrType = typed_attribute() + local_port: int = typed_attribute() + raw_socket: socket.socket = typed_attribute() + remote_address: SockAddrType = typed_attribute() + remote_port: int = typed_attribute() + + +class _SocketProvider(TypedAttributeProvider): + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + from .._core._sockets import convert_ipv6_sockaddr as convert + + attributes: dict[Any, Callable[[], Any]] = { + SocketAttribute.family: lambda: self._raw_socket.family, + SocketAttribute.local_address: lambda: convert( + self._raw_socket.getsockname() + ), + SocketAttribute.raw_socket: lambda: self._raw_socket, + } + try: + peername: tuple[str, int] | None = convert(self._raw_socket.getpeername()) + except OSError: + peername = None + + # Provide the remote address for connected sockets + if peername is not None: + attributes[SocketAttribute.remote_address] = lambda: peername + + # Provide local and remote ports for IP based sockets + if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6): + attributes[SocketAttribute.local_port] = ( + lambda: self._raw_socket.getsockname()[1] + ) + if peername is not None: + remote_port = peername[1] + attributes[SocketAttribute.remote_port] = lambda: remote_port + + return attributes + + @property + @abstractmethod + def _raw_socket(self) -> socket.socket: + pass + + +class SocketStream(ByteStream, _SocketProvider): + """ + Transports bytes over a socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> SocketStream: + """ + Wrap an existing socket object or file descriptor as a socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket stream + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_connected=True) + return await get_async_backend().wrap_stream_socket(sock) + + +class UNIXSocketStream(SocketStream): + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UNIXSocketStream: + """ + Wrap an existing socket object or file descriptor as a UNIX socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX socket stream + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_STREAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_unix_stream_socket(sock) + + @abstractmethod + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + """ + Send file descriptors along with a message to the peer. + + :param message: a non-empty bytestring + :param fds: a collection of files (either numeric file descriptors or open file + or socket objects) + """ + + @abstractmethod + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + """ + Receive file descriptors along with a message from the peer. + + :param msglen: length of the message to expect from the peer + :param maxfds: maximum number of file descriptors to expect from the peer + :return: a tuple of (message, file descriptors) + """ + + +class SocketListener(Listener[SocketStream], _SocketProvider): + """ + Listens to incoming socket connections. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> SocketListener: + """ + Wrap an existing socket object or file descriptor as a socket listener. + + The newly created listener takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket listener + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_bound=True) + return await get_async_backend().wrap_listener_socket(sock) + + @abstractmethod + async def accept(self) -> SocketStream: + """Accept an incoming connection.""" + + async def serve( + self, + handler: Callable[[SocketStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + from .. import create_task_group + + async with AsyncExitStack() as stack: + if task_group is None: + task_group = await stack.enter_async_context(create_task_group()) + + while True: + stream = await self.accept() + task_group.start_soon(handler, stream) + + +class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider): + """ + Represents an unconnected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UDPSocket: + """ + Wrap an existing socket object or file descriptor as a UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must be bound to a local address. + + :param sock_or_fd: a socket object or file descriptor + :return: a UDP socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, require_bound=True) + return await get_async_backend().wrap_udp_socket(sock) + + async def sendto(self, data: bytes, host: str, port: int) -> None: + """ + Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))). + + """ + return await self.send((data, (host, port))) + + +class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents an connected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> ConnectedUDPSocket: + """ + Wrap an existing socket object or file descriptor as a connected UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UDP socket + + """ + sock = _validate_socket( + sock_or_fd, + socket.SOCK_DGRAM, + require_connected=True, + ) + return await get_async_backend().wrap_connected_udp_socket(sock) + + +class UNIXDatagramSocket( + UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider +): + """ + Represents an unconnected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> UNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX datagram socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX) + return await get_async_backend().wrap_unix_datagram_socket(sock) + + async def sendto(self, data: bytes, path: str) -> None: + """Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path)).""" + return await self.send((data, path)) + + +class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents a connected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> ConnectedUNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a connected UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UNIX datagram socket + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_connected_unix_datagram_socket(sock) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/_streams.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..369df3f36cda74aa0d0893cd98bd4b29d3786faa --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/_streams.py @@ -0,0 +1,239 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Callable +from typing import Any, Generic, TypeVar, Union + +from .._core._exceptions import EndOfStream +from .._core._typedattr import TypedAttributeProvider +from ._resources import AsyncResource +from ._tasks import TaskGroup + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class UnreliableObjectReceiveStream( + Generic[T_co], AsyncResource, TypedAttributeProvider +): + """ + An interface for receiving objects. + + This interface makes no guarantees that the received messages arrive in the order in + which they were sent, or that no messages are missed. + + Asynchronously iterating over objects of this type will yield objects matching the + given type parameter. + """ + + def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]: + return self + + async def __anext__(self) -> T_co: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self) -> T_co: + """ + Receive the next item. + + :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly + closed + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectSendStream( + Generic[T_contra], AsyncResource, TypedAttributeProvider +): + """ + An interface for sending objects. + + This interface makes no guarantees that the messages sent will reach the + recipient(s) in the same order in which they were sent, or at all. + """ + + @abstractmethod + async def send(self, item: T_contra) -> None: + """ + Send an item to the peer(s). + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if the send stream has been explicitly + closed + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectStream( + UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item] +): + """ + A bidirectional message stream which does not guarantee the order or reliability of + message delivery. + """ + + +class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]): + """ + A receive message stream which guarantees that messages are received in the same + order in which they were sent, and that no messages are missed. + """ + + +class ObjectSendStream(UnreliableObjectSendStream[T_contra]): + """ + A send message stream which guarantees that messages are delivered in the same order + in which they were sent, without missing any messages in the middle. + """ + + +class ObjectStream( + ObjectReceiveStream[T_Item], + ObjectSendStream[T_Item], + UnreliableObjectStream[T_Item], +): + """ + A bidirectional message stream which guarantees the order and reliability of message + delivery. + """ + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +class ByteReceiveStream(AsyncResource, TypedAttributeProvider): + """ + An interface for receiving bytes from a single peer. + + Iterating this byte stream will yield a byte string of arbitrary length, but no more + than 65536 bytes. + """ + + def __aiter__(self) -> ByteReceiveStream: + return self + + async def __anext__(self) -> bytes: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self, max_bytes: int = 65536) -> bytes: + """ + Receive at most ``max_bytes`` bytes from the peer. + + .. note:: Implementers of this interface should not return an empty + :class:`bytes` object, and users should ignore them. + + :param max_bytes: maximum number of bytes to receive + :return: the received bytes + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + """ + + +class ByteSendStream(AsyncResource, TypedAttributeProvider): + """An interface for sending bytes to a single peer.""" + + @abstractmethod + async def send(self, item: bytes) -> None: + """ + Send the given bytes to the peer. + + :param item: the bytes to send + """ + + +class ByteStream(ByteReceiveStream, ByteSendStream): + """A bidirectional byte stream.""" + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +#: Type alias for all unreliable bytes-oriented receive streams. +AnyUnreliableByteReceiveStream: TypeAlias = Union[ + UnreliableObjectReceiveStream[bytes], ByteReceiveStream +] +#: Type alias for all unreliable bytes-oriented send streams. +AnyUnreliableByteSendStream: TypeAlias = Union[ + UnreliableObjectSendStream[bytes], ByteSendStream +] +#: Type alias for all unreliable bytes-oriented streams. +AnyUnreliableByteStream: TypeAlias = Union[UnreliableObjectStream[bytes], ByteStream] +#: Type alias for all bytes-oriented receive streams. +AnyByteReceiveStream: TypeAlias = Union[ObjectReceiveStream[bytes], ByteReceiveStream] +#: Type alias for all bytes-oriented send streams. +AnyByteSendStream: TypeAlias = Union[ObjectSendStream[bytes], ByteSendStream] +#: Type alias for all bytes-oriented streams. +AnyByteStream: TypeAlias = Union[ObjectStream[bytes], ByteStream] + + +class Listener(Generic[T_co], AsyncResource, TypedAttributeProvider): + """An interface for objects that let you accept incoming connections.""" + + @abstractmethod + async def serve( + self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None + ) -> None: + """ + Accept incoming connections as they come in and start tasks to handle them. + + :param handler: a callable that will be used to handle each accepted connection + :param task_group: the task group that will be used to start tasks for handling + each accepted connection (if omitted, an ad-hoc task group will be created) + """ + + +class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ObjectStream[T_co]: + """ + Connect to the remote endpoint. + + :return: an object stream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +class ByteStreamConnectable(metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ByteStream: + """ + Connect to the remote endpoint. + + :return: a bytestream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +#: Type alias for all connectables returning bytestreams or bytes-oriented object streams +AnyByteStreamConnectable: TypeAlias = Union[ + ObjectStreamConnectable[bytes], ByteStreamConnectable +] diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/_subprocesses.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0564ceac8aac425675b5c8f7f7205d08061fd3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/_subprocesses.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from abc import abstractmethod +from signal import Signals + +from ._resources import AsyncResource +from ._streams import ByteReceiveStream, ByteSendStream + + +class Process(AsyncResource): + """An asynchronous version of :class:`subprocess.Popen`.""" + + @abstractmethod + async def wait(self) -> int: + """ + Wait until the process exits. + + :return: the exit code of the process + """ + + @abstractmethod + def terminate(self) -> None: + """ + Terminates the process, gracefully if possible. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGTERM`` to the process. + + .. seealso:: :meth:`subprocess.Popen.terminate` + """ + + @abstractmethod + def kill(self) -> None: + """ + Kills the process. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGKILL`` to the process. + + .. seealso:: :meth:`subprocess.Popen.kill` + """ + + @abstractmethod + def send_signal(self, signal: Signals) -> None: + """ + Send a signal to the subprocess. + + .. seealso:: :meth:`subprocess.Popen.send_signal` + + :param signal: the signal number (e.g. :data:`signal.SIGHUP`) + """ + + @property + @abstractmethod + def pid(self) -> int: + """The process ID of the process.""" + + @property + @abstractmethod + def returncode(self) -> int | None: + """ + The return code of the process. If the process has not yet terminated, this will + be ``None``. + """ + + @property + @abstractmethod + def stdin(self) -> ByteSendStream | None: + """The stream for the standard input of the process.""" + + @property + @abstractmethod + def stdout(self) -> ByteReceiveStream | None: + """The stream for the standard output of the process.""" + + @property + @abstractmethod + def stderr(self) -> ByteReceiveStream | None: + """The stream for the standard error output of the process.""" diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/_tasks.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..b4ebff9edfeaabf26396fa944752407f6ddefd7e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/_tasks.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Awaitable, Callable +from types import TracebackType +from typing import TYPE_CHECKING, Any, Protocol, TypeVar, overload + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from .._core._tasks import CancelScope + +T_Retval = TypeVar("T_Retval") +T_contra = TypeVar("T_contra", contravariant=True) +PosArgsT = TypeVarTuple("PosArgsT") + + +class TaskStatus(Protocol[T_contra]): + @overload + def started(self: TaskStatus[None]) -> None: ... + + @overload + def started(self, value: T_contra) -> None: ... + + def started(self, value: T_contra | None = None) -> None: + """ + Signal that the task has started. + + :param value: object passed back to the starter of the task + """ + + +class TaskGroup(metaclass=ABCMeta): + """ + Groups several asynchronous tasks together. + + :ivar cancel_scope: the cancel scope inherited by all child tasks + :vartype cancel_scope: CancelScope + + .. note:: On asyncio, support for eager task factories is considered to be + **experimental**. In particular, they don't follow the usual semantics of new + tasks being scheduled on the next iteration of the event loop, and may thus + cause unexpected behavior in code that wasn't written with such semantics in + mind. + """ + + cancel_scope: CancelScope + + @abstractmethod + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + """ + Start a new task in this task group. + + :param func: a coroutine function + :param args: positional arguments to call the function with + :param name: name of the task, for the purposes of introspection and debugging + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def start( + self, + func: Callable[..., Awaitable[Any]], + *args: object, + name: object = None, + ) -> Any: + """ + Start a new task and wait until it signals for readiness. + + The target callable must accept a keyword argument ``task_status`` (of type + :class:`TaskStatus`). Awaiting on this method will return whatever was passed to + ``task_status.started()`` (``None`` by default). + + .. note:: The :class:`TaskStatus` class is generic, and the type argument should + indicate the type of the value that will be passed to + ``task_status.started()``. + + :param func: a coroutine function that accepts the ``task_status`` keyword + argument + :param args: positional arguments to call the function with + :param name: an optional name for the task, for introspection and debugging + :return: the value passed to ``task_status.started()`` + :raises RuntimeError: if the task finishes without calling + ``task_status.started()`` + + .. seealso:: :ref:`start_initialize` + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def __aenter__(self) -> TaskGroup: + """Enter the task group context and allow starting new tasks.""" + + @abstractmethod + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + """Exit the task group context waiting for all tasks to finish.""" diff --git a/miniconda3/lib/python3.13/site-packages/anyio/abc/_testing.py b/miniconda3/lib/python3.13/site-packages/anyio/abc/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..7c50ed76dc4d8df41262973a0122295523e2a935 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/abc/_testing.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import types +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable +from 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 + """ diff --git a/miniconda3/lib/python3.13/site-packages/anyio/streams/__init__.py b/miniconda3/lib/python3.13/site-packages/anyio/streams/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/anyio/streams/buffered.py b/miniconda3/lib/python3.13/site-packages/anyio/streams/buffered.py new file mode 100644 index 0000000000000000000000000000000000000000..ca40eae84822e805adf075cbc231f2f056ea9808 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/streams/buffered.py @@ -0,0 +1,182 @@ +from __future__ import annotations + +import sys +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from typing import Any, SupportsIndex + +from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead +from ..abc import ( + AnyByteReceiveStream, + AnyByteStream, + AnyByteStreamConnectable, + ByteReceiveStream, + ByteStream, + ByteStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class BufferedByteReceiveStream(ByteReceiveStream): + """ + Wraps any bytes-based receive stream and uses a buffer to provide sophisticated + receiving capabilities in the form of a byte stream. + """ + + receive_stream: AnyByteReceiveStream + _buffer: bytearray = field(init=False, default_factory=bytearray) + _closed: bool = field(init=False, default=False) + + async def aclose(self) -> None: + await self.receive_stream.aclose() + self._closed = True + + @property + def buffer(self) -> bytes: + """The bytes currently in the buffer.""" + return bytes(self._buffer) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.receive_stream.extra_attributes + + def feed_data(self, data: Iterable[SupportsIndex], /) -> None: + """ + Append data directly into the buffer. + + Any data in the buffer will be consumed by receive operations before receiving + anything from the wrapped stream. + + :param data: the data to append to the buffer (can be bytes or anything else + that supports ``__index__()``) + + """ + self._buffer.extend(data) + + async def receive(self, max_bytes: int = 65536) -> bytes: + if self._closed: + raise ClosedResourceError + + if self._buffer: + chunk = bytes(self._buffer[:max_bytes]) + del self._buffer[:max_bytes] + return chunk + elif isinstance(self.receive_stream, ByteReceiveStream): + return await self.receive_stream.receive(max_bytes) + else: + # With a bytes-oriented object stream, we need to handle any surplus bytes + # we get from the receive() call + chunk = await self.receive_stream.receive() + if len(chunk) > max_bytes: + # Save the surplus bytes in the buffer + self._buffer.extend(chunk[max_bytes:]) + return chunk[:max_bytes] + else: + return chunk + + async def receive_exactly(self, nbytes: int) -> bytes: + """ + Read exactly the given amount of bytes from the stream. + + :param nbytes: the number of bytes to read + :return: the bytes read + :raises ~anyio.IncompleteRead: if the stream was closed before the requested + amount of bytes could be read from the stream + + """ + while True: + remaining = nbytes - len(self._buffer) + if remaining <= 0: + retval = self._buffer[:nbytes] + del self._buffer[:nbytes] + return bytes(retval) + + try: + if isinstance(self.receive_stream, ByteReceiveStream): + chunk = await self.receive_stream.receive(remaining) + else: + chunk = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + self._buffer.extend(chunk) + + async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes: + """ + Read from the stream until the delimiter is found or max_bytes have been read. + + :param delimiter: the marker to look for in the stream + :param max_bytes: maximum number of bytes that will be read before raising + :exc:`~anyio.DelimiterNotFound` + :return: the bytes read (not including the delimiter) + :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter + was found + :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the + bytes read up to the maximum allowed + + """ + delimiter_size = len(delimiter) + offset = 0 + while True: + # Check if the delimiter can be found in the current buffer + index = self._buffer.find(delimiter, offset) + if index >= 0: + found = self._buffer[:index] + del self._buffer[: index + len(delimiter) :] + return bytes(found) + + # Check if the buffer is already at or over the limit + if len(self._buffer) >= max_bytes: + raise DelimiterNotFound(max_bytes) + + # Read more data into the buffer from the socket + try: + data = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + # Move the offset forward and add the new data to the buffer + offset = max(len(self._buffer) - delimiter_size + 1, 0) + self._buffer.extend(data) + + +class BufferedByteStream(BufferedByteReceiveStream, ByteStream): + """ + A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed + through to the wrapped stream as-is. + """ + + def __init__(self, stream: AnyByteStream): + """ + :param stream: the stream to be wrapped + + """ + super().__init__(stream) + self._stream = stream + + @override + async def send_eof(self) -> None: + await self._stream.send_eof() + + @override + async def send(self, item: bytes) -> None: + await self._stream.send(item) + + +class BufferedConnectable(ByteStreamConnectable): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the connectable to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> BufferedByteStream: + stream = await self.connectable.connect() + return BufferedByteStream(stream) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/streams/file.py b/miniconda3/lib/python3.13/site-packages/anyio/streams/file.py new file mode 100644 index 0000000000000000000000000000000000000000..f492464267ac54b57ee9953a4aad128f06a2110a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/streams/file.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from io import SEEK_SET, UnsupportedOperation +from os import PathLike +from pathlib import Path +from typing import Any, BinaryIO, cast + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + TypedAttributeSet, + to_thread, + typed_attribute, +) +from ..abc import ByteReceiveStream, ByteSendStream + + +class FileStreamAttribute(TypedAttributeSet): + #: the open file descriptor + file: BinaryIO = typed_attribute() + #: the path of the file on the file system, if available (file must be a real file) + path: Path = typed_attribute() + #: the file number, if available (file must be a real file or a TTY) + fileno: int = typed_attribute() + + +class _BaseFileStream: + def __init__(self, file: BinaryIO): + self._file = file + + async def aclose(self) -> None: + await to_thread.run_sync(self._file.close) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict[Any, Callable[[], Any]] = { + FileStreamAttribute.file: lambda: self._file, + } + + if hasattr(self._file, "name"): + attributes[FileStreamAttribute.path] = lambda: Path(self._file.name) + + try: + self._file.fileno() + except UnsupportedOperation: + pass + else: + attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno() + + return attributes + + +class FileReadStream(_BaseFileStream, ByteReceiveStream): + """ + A byte stream that reads from a file in the file system. + + :param file: a file that has been opened for reading in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path(cls, path: str | PathLike[str]) -> FileReadStream: + """ + Create a file read stream by opening the given file. + + :param path: path of the file to read from + + """ + file = await to_thread.run_sync(Path(path).open, "rb") + return cls(cast(BinaryIO, file)) + + async def receive(self, max_bytes: int = 65536) -> bytes: + try: + data = await to_thread.run_sync(self._file.read, max_bytes) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc + + if data: + return data + else: + raise EndOfStream + + async def seek(self, position: int, whence: int = SEEK_SET) -> int: + """ + Seek the file to the given position. + + .. seealso:: :meth:`io.IOBase.seek` + + .. note:: Not all file descriptors are seekable. + + :param position: position to seek the file to + :param whence: controls how ``position`` is interpreted + :return: the new absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.seek, position, whence) + + async def tell(self) -> int: + """ + Return the current stream position. + + .. note:: Not all file descriptors are seekable. + + :return: the current absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.tell) + + +class FileWriteStream(_BaseFileStream, ByteSendStream): + """ + A byte stream that writes to a file in the file system. + + :param file: a file that has been opened for writing in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path( + cls, path: str | PathLike[str], append: bool = False + ) -> FileWriteStream: + """ + Create a file write stream by opening the given file for writing. + + :param path: path of the file to write to + :param append: if ``True``, open the file for appending; if ``False``, any + existing file at the given path will be truncated + + """ + mode = "ab" if append else "wb" + file = await to_thread.run_sync(Path(path).open, mode) + return cls(cast(BinaryIO, file)) + + async def send(self, item: bytes) -> None: + try: + await to_thread.run_sync(self._file.write, item) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc diff --git a/miniconda3/lib/python3.13/site-packages/anyio/streams/memory.py b/miniconda3/lib/python3.13/site-packages/anyio/streams/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3bac474b5eba460033240b5b8c45effd7bb334 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/streams/memory.py @@ -0,0 +1,319 @@ +from __future__ import annotations + +import warnings +from collections import OrderedDict, deque +from dataclasses import dataclass, field +from types import TracebackType +from typing import Generic, NamedTuple, TypeVar + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + WouldBlock, +) +from .._core._testing import TaskInfo, get_current_task +from ..abc import Event, ObjectReceiveStream, ObjectSendStream +from ..lowlevel import checkpoint + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class MemoryObjectStreamStatistics(NamedTuple): + current_buffer_used: int #: number of items stored in the buffer + #: maximum number of items that can be stored on this stream (or :data:`math.inf`) + max_buffer_size: float + open_send_streams: int #: number of unclosed clones of the send stream + open_receive_streams: int #: number of unclosed clones of the receive stream + #: number of tasks blocked on :meth:`MemoryObjectSendStream.send` + tasks_waiting_send: int + #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive` + tasks_waiting_receive: int + + +@dataclass(eq=False) +class MemoryObjectItemReceiver(Generic[T_Item]): + task_info: TaskInfo = field(init=False, default_factory=get_current_task) + item: T_Item = field(init=False) + + def __repr__(self) -> str: + # When item is not defined, we get following error with default __repr__: + # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item' + item = getattr(self, "item", None) + return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})" + + +@dataclass(eq=False) +class MemoryObjectStreamState(Generic[T_Item]): + max_buffer_size: float = field() + buffer: deque[T_Item] = field(init=False, default_factory=deque) + open_send_channels: int = field(init=False, default=0) + open_receive_channels: int = field(init=False, default=0) + waiting_receivers: OrderedDict[Event, MemoryObjectItemReceiver[T_Item]] = field( + init=False, default_factory=OrderedDict + ) + waiting_senders: OrderedDict[Event, T_Item] = field( + init=False, default_factory=OrderedDict + ) + + def statistics(self) -> MemoryObjectStreamStatistics: + return MemoryObjectStreamStatistics( + len(self.buffer), + self.max_buffer_size, + self.open_send_channels, + self.open_receive_channels, + len(self.waiting_senders), + len(self.waiting_receivers), + ) + + +@dataclass(eq=False) +class MemoryObjectReceiveStream(Generic[T_co], ObjectReceiveStream[T_co]): + _state: MemoryObjectStreamState[T_co] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_receive_channels += 1 + + def receive_nowait(self) -> T_co: + """ + Receive the next item if it can be done without waiting. + + :return: the received item + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been + closed from the sending end + :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks + waiting to send + + """ + if self._closed: + raise ClosedResourceError + + if self._state.waiting_senders: + # Get the item from the next sender + send_event, item = self._state.waiting_senders.popitem(last=False) + self._state.buffer.append(item) + send_event.set() + + if self._state.buffer: + return self._state.buffer.popleft() + elif not self._state.open_send_channels: + raise EndOfStream + + raise WouldBlock + + async def receive(self) -> T_co: + await checkpoint() + try: + return self.receive_nowait() + except WouldBlock: + # Add ourselves in the queue + receive_event = Event() + receiver = MemoryObjectItemReceiver[T_co]() + self._state.waiting_receivers[receive_event] = receiver + + try: + await receive_event.wait() + finally: + self._state.waiting_receivers.pop(receive_event, None) + + try: + return receiver.item + except AttributeError: + raise EndOfStream from None + + def clone(self) -> MemoryObjectReceiveStream[T_co]: + """ + Create a clone of this receive stream. + + Each clone can be closed separately. Only when all clones have been closed will + the receiving end of the memory stream be considered closed by the sending ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectReceiveStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_receive_channels -= 1 + if self._state.open_receive_channels == 0: + send_events = list(self._state.waiting_senders.keys()) + for event in send_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectReceiveStream[T_co]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) + + +@dataclass(eq=False) +class MemoryObjectSendStream(Generic[T_contra], ObjectSendStream[T_contra]): + _state: MemoryObjectStreamState[T_contra] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_send_channels += 1 + + def send_nowait(self, item: T_contra) -> None: + """ + Send an item immediately if it can be done without waiting. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting + to receive + + """ + if self._closed: + raise ClosedResourceError + if not self._state.open_receive_channels: + raise BrokenResourceError + + while self._state.waiting_receivers: + receive_event, receiver = self._state.waiting_receivers.popitem(last=False) + if not receiver.task_info.has_pending_cancellation(): + receiver.item = item + receive_event.set() + return + + if len(self._state.buffer) < self._state.max_buffer_size: + self._state.buffer.append(item) + else: + raise WouldBlock + + async def send(self, item: T_contra) -> None: + """ + Send an item to the stream. + + If the buffer is full, this method blocks until there is again room in the + buffer or the item can be sent directly to a receiver. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + + """ + await checkpoint() + try: + self.send_nowait(item) + except WouldBlock: + # Wait until there's someone on the receiving end + send_event = Event() + self._state.waiting_senders[send_event] = item + try: + await send_event.wait() + except BaseException: + self._state.waiting_senders.pop(send_event, None) + raise + + if send_event in self._state.waiting_senders: + del self._state.waiting_senders[send_event] + raise BrokenResourceError from None + + def clone(self) -> MemoryObjectSendStream[T_contra]: + """ + Create a clone of this send stream. + + Each clone can be closed separately. Only when all clones have been closed will + the sending end of the memory stream be considered closed by the receiving ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectSendStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_send_channels -= 1 + if self._state.open_send_channels == 0: + receive_events = list(self._state.waiting_receivers.keys()) + self._state.waiting_receivers.clear() + for event in receive_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectSendStream[T_contra]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/streams/stapled.py b/miniconda3/lib/python3.13/site-packages/anyio/streams/stapled.py new file mode 100644 index 0000000000000000000000000000000000000000..80f64a2e8e5763ae327c5c213ec12e24f023b4d3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/streams/stapled.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +from ..abc import ( + ByteReceiveStream, + ByteSendStream, + ByteStream, + Listener, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + TaskGroup, +) + +T_Item = TypeVar("T_Item") +T_Stream = TypeVar("T_Stream") + + +@dataclass(eq=False) +class StapledByteStream(ByteStream): + """ + Combines two byte streams into a single, bidirectional byte stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ByteSendStream send_stream: the sending byte stream + :param ByteReceiveStream receive_stream: the receiving byte stream + """ + + send_stream: ByteSendStream + receive_stream: ByteReceiveStream + + async def receive(self, max_bytes: int = 65536) -> bytes: + return await self.receive_stream.receive(max_bytes) + + async def send(self, item: bytes) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class StapledObjectStream(Generic[T_Item], ObjectStream[T_Item]): + """ + Combines two object streams into a single, bidirectional object stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ObjectSendStream send_stream: the sending object stream + :param ObjectReceiveStream receive_stream: the receiving object stream + """ + + send_stream: ObjectSendStream[T_Item] + receive_stream: ObjectReceiveStream[T_Item] + + async def receive(self) -> T_Item: + return await self.receive_stream.receive() + + async def send(self, item: T_Item) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class MultiListener(Generic[T_Stream], Listener[T_Stream]): + """ + Combines multiple listeners into one, serving connections from all of them at once. + + Any MultiListeners in the given collection of listeners will have their listeners + moved into this one. + + Extra attributes are provided from each listener, with each successive listener + overriding any conflicting attributes from the previous one. + + :param listeners: listeners to serve + :type listeners: Sequence[Listener[T_Stream]] + """ + + listeners: Sequence[Listener[T_Stream]] + + def __post_init__(self) -> None: + listeners: list[Listener[T_Stream]] = [] + for listener in self.listeners: + if isinstance(listener, MultiListener): + listeners.extend(listener.listeners) + del listener.listeners[:] # type: ignore[attr-defined] + else: + listeners.append(listener) + + self.listeners = listeners + + async def serve( + self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None + ) -> None: + from .. import create_task_group + + async with create_task_group() as tg: + for listener in self.listeners: + tg.start_soon(listener.serve, handler, task_group) + + async def aclose(self) -> None: + for listener in self.listeners: + await listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict = {} + for listener in self.listeners: + attributes.update(listener.extra_attributes) + + return attributes diff --git a/miniconda3/lib/python3.13/site-packages/anyio/streams/text.py b/miniconda3/lib/python3.13/site-packages/anyio/streams/text.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd8e7a2550a7e217ec280a7147826c2bc3bad96 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/streams/text.py @@ -0,0 +1,169 @@ +from __future__ import annotations + +import codecs +import sys +from collections.abc import Callable, Mapping +from dataclasses import InitVar, dataclass, field +from typing import Any + +from ..abc import ( + AnyByteReceiveStream, + AnyByteSendStream, + AnyByteStream, + AnyByteStreamConnectable, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + ObjectStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class TextReceiveStream(ObjectReceiveStream[str]): + """ + Stream wrapper that decodes bytes to strings using the given encoding. + + Decoding is done using :class:`~codecs.IncrementalDecoder` which returns any + completely received unicode characters as soon as they come in. + + :param transport_stream: any bytes-based receive stream + :param encoding: character encoding to use for decoding bytes to strings (defaults + to ``utf-8``) + :param errors: handling scheme for decoding errors (defaults to ``strict``; see the + `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteReceiveStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _decoder: codecs.IncrementalDecoder = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + decoder_class = codecs.getincrementaldecoder(encoding) + self._decoder = decoder_class(errors=errors) + + async def receive(self) -> str: + while True: + chunk = await self.transport_stream.receive() + decoded = self._decoder.decode(chunk) + if decoded: + return decoded + + async def aclose(self) -> None: + await self.transport_stream.aclose() + self._decoder.reset() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextSendStream(ObjectSendStream[str]): + """ + Sends strings to the wrapped stream as bytes using the given encoding. + + :param AnyByteSendStream transport_stream: any bytes-based send stream + :param str encoding: character encoding to use for encoding strings to bytes + (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteSendStream + encoding: InitVar[str] = "utf-8" + errors: str = "strict" + _encoder: Callable[..., tuple[bytes, int]] = field(init=False) + + def __post_init__(self, encoding: str) -> None: + self._encoder = codecs.getencoder(encoding) + + async def send(self, item: str) -> None: + encoded = self._encoder(item, self.errors)[0] + await self.transport_stream.send(encoded) + + async def aclose(self) -> None: + await self.transport_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextStream(ObjectStream[str]): + """ + A bidirectional stream that decodes bytes to strings on receive and encodes strings + to bytes on send. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param AnyByteStream transport_stream: any bytes-based stream + :param str encoding: character encoding to use for encoding/decoding strings to/from + bytes (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _receive_stream: TextReceiveStream = field(init=False) + _send_stream: TextSendStream = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + self._receive_stream = TextReceiveStream( + self.transport_stream, encoding=encoding, errors=errors + ) + self._send_stream = TextSendStream( + self.transport_stream, encoding=encoding, errors=errors + ) + + async def receive(self) -> str: + return await self._receive_stream.receive() + + async def send(self, item: str) -> None: + await self._send_stream.send(item) + + async def send_eof(self) -> None: + await self.transport_stream.send_eof() + + async def aclose(self) -> None: + await self._send_stream.aclose() + await self._receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self._send_stream.extra_attributes, + **self._receive_stream.extra_attributes, + } + + +class TextConnectable(ObjectStreamConnectable[str]): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the bytestream endpoint to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> TextStream: + stream = await self.connectable.connect() + return TextStream(stream) diff --git a/miniconda3/lib/python3.13/site-packages/anyio/streams/tls.py b/miniconda3/lib/python3.13/site-packages/anyio/streams/tls.py new file mode 100644 index 0000000000000000000000000000000000000000..17fa200e61c77edc80a52601eb9f6edc89620023 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/anyio/streams/tls.py @@ -0,0 +1,417 @@ +from __future__ import annotations + +import logging +import re +import ssl +import sys +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from functools import wraps +from ssl import SSLContext +from typing import Any, TypeVar + +from .. import ( + BrokenResourceError, + EndOfStream, + aclose_forcefully, + get_cancelled_exc_class, + to_thread, +) +from .._core._typedattr import TypedAttributeSet, typed_attribute +from ..abc import ( + AnyByteStream, + AnyByteStreamConnectable, + ByteStream, + ByteStreamConnectable, + Listener, + TaskGroup, +) + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] + + +class TLSAttribute(TypedAttributeSet): + """Contains Transport Layer Security related attributes.""" + + #: the selected ALPN protocol + alpn_protocol: str | None = typed_attribute() + #: the channel binding for type ``tls-unique`` + channel_binding_tls_unique: bytes = typed_attribute() + #: the selected cipher + cipher: tuple[str, str, int] = typed_attribute() + #: the peer certificate in dictionary form (see :meth:`ssl.SSLSocket.getpeercert` + # for more information) + peer_certificate: None | (dict[str, str | _PCTRTTT | _PCTRTT]) = typed_attribute() + #: the peer certificate in binary form + peer_certificate_binary: bytes | None = typed_attribute() + #: ``True`` if this is the server side of the connection + server_side: bool = typed_attribute() + #: ciphers shared by the client during the TLS handshake (``None`` if this is the + #: client side) + shared_ciphers: list[tuple[str, str, int]] | None = typed_attribute() + #: the :class:`~ssl.SSLObject` used for encryption + ssl_object: ssl.SSLObject = typed_attribute() + #: ``True`` if this stream does (and expects) a closing TLS handshake when the + #: stream is being closed + standard_compatible: bool = typed_attribute() + #: the TLS protocol version (e.g. ``TLSv1.2``) + tls_version: str = typed_attribute() + + +@dataclass(eq=False) +class TLSStream(ByteStream): + """ + A stream wrapper that encrypts all sent data and decrypts received data. + + This class has no public initializer; use :meth:`wrap` instead. + All extra attributes from :class:`~TLSAttribute` are supported. + + :var AnyByteStream transport_stream: the wrapped stream + + """ + + transport_stream: AnyByteStream + standard_compatible: bool + _ssl_object: ssl.SSLObject + _read_bio: ssl.MemoryBIO + _write_bio: ssl.MemoryBIO + + @classmethod + async def wrap( + cls, + transport_stream: AnyByteStream, + *, + server_side: bool | None = None, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> TLSStream: + """ + Wrap an existing stream with Transport Layer Security. + + This performs a TLS handshake with the peer. + + :param transport_stream: a bytes-transporting stream to wrap + :param server_side: ``True`` if this is the server side of the connection, + ``False`` if this is the client side (if omitted, will be set to ``False`` + if ``hostname`` has been provided, ``False`` otherwise). Used only to create + a default context when an explicit context has not been provided. + :param hostname: host name of the peer (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure + default will be created) + :param standard_compatible: if ``False``, skip the closing handshake when + closing the connection, and don't raise an exception if the peer does the + same + :raises ~ssl.SSLError: if the TLS handshake fails + + """ + if server_side is None: + server_side = not hostname + + if not ssl_context: + purpose = ( + ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH + ) + ssl_context = ssl.create_default_context(purpose) + + # Re-enable detection of unexpected EOFs if it was disabled by Python + if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): + ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF + + bio_in = ssl.MemoryBIO() + bio_out = ssl.MemoryBIO() + + # External SSLContext implementations may do blocking I/O in wrap_bio(), + # but the standard library implementation won't + if type(ssl_context) is ssl.SSLContext: + ssl_object = ssl_context.wrap_bio( + bio_in, bio_out, server_side=server_side, server_hostname=hostname + ) + else: + ssl_object = await to_thread.run_sync( + ssl_context.wrap_bio, + bio_in, + bio_out, + server_side, + hostname, + None, + ) + + wrapper = cls( + transport_stream=transport_stream, + standard_compatible=standard_compatible, + _ssl_object=ssl_object, + _read_bio=bio_in, + _write_bio=bio_out, + ) + await wrapper._call_sslobject_method(ssl_object.do_handshake) + return wrapper + + async def _call_sslobject_method( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: + while True: + try: + result = func(*args) + except ssl.SSLWantReadError: + try: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + data = await self.transport_stream.receive() + except EndOfStream: + self._read_bio.write_eof() + except OSError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + else: + self._read_bio.write(data) + except ssl.SSLWantWriteError: + await self.transport_stream.send(self._write_bio.read()) + except ssl.SSLSyscallError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + except ssl.SSLError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + if isinstance(exc, ssl.SSLEOFError) or ( + exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror + ): + if self.standard_compatible: + raise BrokenResourceError from exc + else: + raise EndOfStream from None + + raise + else: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + return result + + async def unwrap(self) -> tuple[AnyByteStream, bytes]: + """ + Does the TLS closing handshake. + + :return: a tuple of (wrapped byte stream, bytes left in the read buffer) + + """ + await self._call_sslobject_method(self._ssl_object.unwrap) + self._read_bio.write_eof() + self._write_bio.write_eof() + return self.transport_stream, self._read_bio.read() + + async def aclose(self) -> None: + if self.standard_compatible: + try: + await self.unwrap() + except BaseException: + await aclose_forcefully(self.transport_stream) + raise + + await self.transport_stream.aclose() + + async def receive(self, max_bytes: int = 65536) -> bytes: + data = await self._call_sslobject_method(self._ssl_object.read, max_bytes) + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + await self._call_sslobject_method(self._ssl_object.write, item) + + async def send_eof(self) -> None: + tls_version = self.extra(TLSAttribute.tls_version) + match = re.match(r"TLSv(\d+)(?:\.(\d+))?", tls_version) + if match: + major, minor = int(match.group(1)), int(match.group(2) or 0) + if (major, minor) < (1, 3): + raise NotImplementedError( + f"send_eof() requires at least TLSv1.3; current " + f"session uses {tls_version}" + ) + + raise NotImplementedError( + "send_eof() has not yet been implemented for TLS streams" + ) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.transport_stream.extra_attributes, + TLSAttribute.alpn_protocol: self._ssl_object.selected_alpn_protocol, + TLSAttribute.channel_binding_tls_unique: ( + self._ssl_object.get_channel_binding + ), + TLSAttribute.cipher: self._ssl_object.cipher, + TLSAttribute.peer_certificate: lambda: self._ssl_object.getpeercert(False), + TLSAttribute.peer_certificate_binary: lambda: self._ssl_object.getpeercert( + True + ), + TLSAttribute.server_side: lambda: self._ssl_object.server_side, + TLSAttribute.shared_ciphers: lambda: self._ssl_object.shared_ciphers() + if self._ssl_object.server_side + else None, + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + TLSAttribute.ssl_object: lambda: self._ssl_object, + TLSAttribute.tls_version: self._ssl_object.version, + } + + +@dataclass(eq=False) +class TLSListener(Listener[TLSStream]): + """ + A convenience listener that wraps another listener and auto-negotiates a TLS session + on every accepted connection. + + If the TLS handshake times out or raises an exception, + :meth:`handle_handshake_error` is called to do whatever post-mortem processing is + deemed necessary. + + Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute. + + :param Listener listener: the listener to wrap + :param ssl_context: the SSL context object + :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap` + :param handshake_timeout: time limit for the TLS handshake + (passed to :func:`~anyio.fail_after`) + """ + + listener: Listener[Any] + ssl_context: ssl.SSLContext + standard_compatible: bool = True + handshake_timeout: float = 30 + + @staticmethod + async def handle_handshake_error(exc: BaseException, stream: AnyByteStream) -> None: + """ + Handle an exception raised during the TLS handshake. + + This method does 3 things: + + #. Forcefully closes the original stream + #. Logs the exception (unless it was a cancellation exception) using the + ``anyio.streams.tls`` logger + #. Reraises the exception if it was a base exception or a cancellation exception + + :param exc: the exception + :param stream: the original stream + + """ + await aclose_forcefully(stream) + + # Log all except cancellation exceptions + if not isinstance(exc, get_cancelled_exc_class()): + # CPython (as of 3.11.5) returns incorrect `sys.exc_info()` here when using + # any asyncio implementation, so we explicitly pass the exception to log + # (https://github.com/python/cpython/issues/108668). Trio does not have this + # issue because it works around the CPython bug. + logging.getLogger(__name__).exception( + "Error during TLS handshake", exc_info=exc + ) + + # Only reraise base exceptions and cancellation exceptions + if not isinstance(exc, Exception) or isinstance(exc, get_cancelled_exc_class()): + raise + + async def serve( + self, + handler: Callable[[TLSStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + @wraps(handler) + async def handler_wrapper(stream: AnyByteStream) -> None: + from .. import fail_after + + try: + with fail_after(self.handshake_timeout): + wrapped_stream = await TLSStream.wrap( + stream, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException as exc: + await self.handle_handshake_error(exc, stream) + else: + await handler(wrapped_stream) + + await self.listener.serve(handler_wrapper, task_group) + + async def aclose(self) -> None: + await self.listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + } + + +class TLSConnectable(ByteStreamConnectable): + """ + Wraps another connectable and does TLS negotiation after a successful connection. + + :param connectable: the connectable to wrap + :param hostname: host name of the server (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure default + will be created) + :param standard_compatible: if ``False``, skip the closing handshake when closing + the connection, and don't raise an exception if the server does the same + """ + + def __init__( + self, + connectable: AnyByteStreamConnectable, + *, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> None: + self.connectable = connectable + self.ssl_context: SSLContext = ssl_context or ssl.create_default_context( + ssl.Purpose.SERVER_AUTH + ) + if not isinstance(self.ssl_context, ssl.SSLContext): + raise TypeError( + "ssl_context must be an instance of ssl.SSLContext, not " + f"{type(self.ssl_context).__name__}" + ) + self.hostname = hostname + self.standard_compatible = standard_compatible + + @override + async def connect(self) -> TLSStream: + stream = await self.connectable.connect() + try: + return await TLSStream.wrap( + stream, + hostname=self.hostname, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException: + await aclose_forcefully(stream) + raise diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..499927d778be66a399ff512b866409c4ba7a7c8c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/METADATA @@ -0,0 +1,123 @@ +Metadata-Version: 2.4 +Name: archspec +Version: 0.2.5 +Summary: A library to query system architecture +License: Apache-2.0 OR MIT +License-File: LICENSE-APACHE +License-File: LICENSE-MIT +License-File: NOTICE +Author: archspec developers +Author-email: maintainers@spack.io +Maintainer: Greg Becker +Maintainer-email: maintainers@spack.io +Requires-Python: >=3.6, !=2.7.*, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.* +Classifier: Development Status :: 3 - Alpha +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Operating System :: MacOS +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Project-URL: Documentation, https://archspec.readthedocs.io +Project-URL: Homepage, https://github.com/archspec/archspec +Project-URL: Repository, https://github.com/archspec/archspec.git +Description-Content-Type: text/markdown + +# Archspec (Python bindings) + +[![CI](https://github.com/archspec/archspec/workflows/Unit%20tests/badge.svg)](https://github.com/archspec/archspec/actions) +[![CodeCov](https://codecov.io/gh/archspec/archspec/branch/master/graph/badge.svg)](https://codecov.io/gh/archspec/archspec) +[![Documentation Status](https://readthedocs.org/projects/archspec/badge/?version=latest)](https://archspec.readthedocs.io/en/latest/?badge=latest) + +Archspec aims at providing a standard set of human-understandable labels for +various aspects of a system architecture like CPU, network fabrics, etc. and +APIs to detect, query and compare them. + +This project grew out of [Spack](https://spack.io/) and is currently under +active development. At present it supports APIs to detect and model +compatibility relationships among different CPU microarchitectures. + +## Getting started with development + +The `archspec` Python package needs [poetry](https://python-poetry.org/) to +be installed from VCS sources. The preferred method to install it is via +its custom installer outside of any virtual environment: + +```console +curl -sSL https://install.python-poetry.org | python3 - +``` + +You can refer to [Poetry's documentation](https://python-poetry.org/docs/#installation) +for further details or for other methods to install this tool. You'll also need `tox` +to run unit test: + +```console +pip install --user tox +``` + +Finally, you'll need to clone the repository: + +```console +git clone --recursive https://github.com/archspec/archspec.git +``` + +### Running unit tests + +Once you have your environment ready you can run `archspec` unit tests +using ``tox`` from the root of the repository: + +```console +$ tox + [ ... ] + py27: commands succeeded + py35: commands succeeded + py36: commands succeeded + py37: commands succeeded + py38: commands succeeded + pylint: commands succeeded + flake8: commands succeeded + black: commands succeeded + congratulations :) +``` + +## Citing Archspec + +If you are referencing `archspec` in a publication, please cite the following +paper: + +* Massimiliano Culpo, Gregory Becker, Carlos Eduardo Arango Gutierrez, Kenneth + Hoste, and Todd Gamblin. + [**`archspec`: A library for detecting, labeling, and reasoning about + microarchitectures**](https://tgamblin.github.io/pubs/archspec-canopie-hpc-2020.pdf). + In *2nd International Workshop on Containers and New Orchestration Paradigms + for Isolated Environments in HPC (CANOPIE-HPC'20)*, Online Event, November + 12, 2020. + +## License + +Archspec is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). Users may choose either license, at their +option. + +All new contributions must be made under both the MIT and Apache-2.0 +licenses. + +See [LICENSE-MIT](https://github.com/archspec/archspec/blob/master/LICENSE-MIT), +[LICENSE-APACHE](https://github.com/archspec/archspec/blob/master/LICENSE-APACHE), +[COPYRIGHT](https://github.com/archspec/archspec/blob/master/COPYRIGHT), and +[NOTICE](https://github.com/archspec/archspec/blob/master/NOTICE) for details. + +SPDX-License-Identifier: (Apache-2.0 OR MIT) + +LLNL-CODE-811653 + diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f75096c401fa947de902b18930f9f2b5ca819262 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/RECORD @@ -0,0 +1,88 @@ +../../../bin/archspec,sha256=GF-Fy76-9whVsvLe1qu63xMH8EWOcvd65f29nRJUgZc,467 +archspec-0.2.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +archspec-0.2.5.dist-info/METADATA,sha256=Rsa-lHKler8MX_jhHwyafwQu95u8tA0gqBBneIocKJ4,4565 +archspec-0.2.5.dist-info/RECORD,, +archspec-0.2.5.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +archspec-0.2.5.dist-info/WHEEL,sha256=M5asmiAlL6HEcOq52Yi5mmk9KmTVjY2RDPtO4p9DMrc,88 +archspec-0.2.5.dist-info/direct_url.json,sha256=tEankn611kBkC1j5rz91rAIMmzz4mcUiVeCbDiiHDmw,98 +archspec-0.2.5.dist-info/entry_points.txt,sha256=v6umiu5eQSD6088Viyvkjlc1WVSHKK0LADMa7rMpNm4,46 +archspec-0.2.5.dist-info/licenses/LICENSE-APACHE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +archspec-0.2.5.dist-info/licenses/LICENSE-MIT,sha256=kAGtmaZiB1oOWmqaU5_HUEDYBjw_clHWg5ykC1I0BU4,1171 +archspec-0.2.5.dist-info/licenses/NOTICE,sha256=9CR93geVKl_4ZrJORbXN0fzkEM2y4DglWhY1hn9ZwQw,1167 +archspec/__init__.py,sha256=l_vGH4wKXB5bmg7ZqNh-xA8EVUkpJpAS5l7V07ic0kE,67 +archspec/__main__.py,sha256=lZu3C2P9FbOlE5GBeoSTqgdPycvcQcL7N8ihsdZGXYM,97 +archspec/__pycache__/__init__.cpython-313.pyc,, +archspec/__pycache__/__main__.cpython-313.pyc,, +archspec/__pycache__/cli.cpython-313.pyc,, +archspec/cli.py,sha256=qgqXH-9b1bbssm00LOQmeiZkTuZJIgymXwAbtCDVk9Y,1691 +archspec/cpu/__init__.py,sha256=OEkFUxPe0veRJL2bd4kYwzE8fJ8_V9UAtMB2bEyAVsM,727 +archspec/cpu/__pycache__/__init__.cpython-313.pyc,, +archspec/cpu/__pycache__/alias.cpython-313.pyc,, +archspec/cpu/__pycache__/detect.cpython-313.pyc,, +archspec/cpu/__pycache__/microarchitecture.cpython-313.pyc,, +archspec/cpu/__pycache__/schema.cpython-313.pyc,, +archspec/cpu/alias.py,sha256=GrJPaWX6-FtoepF3z2G8RwikaB-_slHVT54yFQtOLU0,2506 +archspec/cpu/detect.py,sha256=zId1RmKtEk3658M3SVD1_xED_9UsKRIWMTsOS5Ei5hw,16302 +archspec/cpu/microarchitecture.py,sha256=I_XqoIumN4lnMb61x_PQEsIVEIndsvET4md5sI7jEJE,15210 +archspec/cpu/schema.py,sha256=8CnUUDGzXaaGqbhSOQCTYT3wfoFLj4qFvFeedBtE5bM,3687 +archspec/json/COPYRIGHT,sha256=nXDFqDfvpi337jffHHDd_8C7OOON8p3f3PoBRiQHzfs,805 +archspec/json/LICENSE-APACHE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +archspec/json/LICENSE-MIT,sha256=kAGtmaZiB1oOWmqaU5_HUEDYBjw_clHWg5ykC1I0BU4,1171 +archspec/json/NOTICE,sha256=9CR93geVKl_4ZrJORbXN0fzkEM2y4DglWhY1hn9ZwQw,1167 +archspec/json/README.md,sha256=izG7TOmPb760cBmVawnPszxUtBlyyvHmKoxFrf3fK-g,1531 +archspec/json/cpu/cpuid.json,sha256=gAWR57GoganHupdZX57v2CwXLVohSkx2hxkFL_r0-O0,20572 +archspec/json/cpu/cpuid_schema.json,sha256=wIHbIUMywtjeBnZHGwL2g62sbagp6wrONj2x9y36pzg,3129 +archspec/json/cpu/microarchitectures.json,sha256=upWYxLbsThV_YJQ5GPXXAL6d0VD6ytPW-WVqBIKU2YM,85601 +archspec/json/cpu/microarchitectures_schema.json,sha256=EkHYbWfHs2k765QYU2gsoExocV_k9xt-_3LqAsGqhpU,3025 +archspec/json/tests/targets/bgq-rhel6-power7,sha256=78gpbVDtmaehxm-I53_JD9_tYr8mkDJfUD9dA95akFg,116 +archspec/json/tests/targets/darwin-bigsur-m1,sha256=ccXDP4oGNbOtTA16Zl9ntuh5R5JqnBlvZQT6m3U44Tw,534 +archspec/json/tests/targets/darwin-mojave-haswell,sha256=x2dqKo4PYyQjA4O29lmGSuJuvbPwsT4LHYt60Pt0_sM,553 +archspec/json/tests/targets/darwin-mojave-ivybridge,sha256=YEUVaxRSZmNa2Np5DpjAWdFwFG-o82njVKmwQDKVldw,2356 +archspec/json/tests/targets/darwin-mojave-skylake,sha256=Hemmh6M0BvHs04nu2NELy20COML_94G1zH4bAumU_dg,598 +archspec/json/tests/targets/darwin-monterey-m1,sha256=WSG9O446Q_SSD9vHuYj1SaI2zA6DhGtF3UU20xbnZ9s,3307 +archspec/json/tests/targets/darwin-monterey-m2,sha256=ExCs3mYsAb3Lt6ZXDLI1pam9WrEfDNVhodphfVA7K6w,3307 +archspec/json/tests/targets/linux-amazon-cortex_a72,sha256=P7YAipvudlo2U1PvUa01dDR2HKQURPeB2PHNu7kHRes,221 +archspec/json/tests/targets/linux-amazon-neoverse_n1,sha256=zvHJOqLzHf4cTscllomBX2iSZNK45MiZ0z2jJ9AeDqk,276 +archspec/json/tests/targets/linux-amazon-neoverse_v1,sha256=2RsWvKEIyHxVQunBRg_X71rdvq2dhPKRhKcsYdWb824,361 +archspec/json/tests/targets/linux-amazon2-sapphirerapids,sha256=aRgatOvQJqJKnI62YC6FCuHxiMWtnwmba20_Ko0XI-k,1519 +archspec/json/tests/targets/linux-asahi-m1,sha256=hKEOlbpmkV41_18D-XMig8TZV2FiZJLnBjYwZtpNrIQ,363 +archspec/json/tests/targets/linux-asahi-m2,sha256=SKEtv3AhM-Zzzyr94GFirrF5UJKJTOOZqK33KulaBiI,381 +archspec/json/tests/targets/linux-centos7-cascadelake,sha256=YYdo8G0bP85bn4dGdWePNDthEtAhhjKVRSXs3M7Yjg8,1408 +archspec/json/tests/targets/linux-centos7-power8le,sha256=KgkGSkHLpk2vP4j0W3m7iHe559f-pxa2riWtAkIMRxo,111 +archspec/json/tests/targets/linux-centos7-thunderx2,sha256=K8xsnq3W7EC-PXv5j3MsGrauowOARGOKj3_7-oOsNJI,238 +archspec/json/tests/targets/linux-rhel6-piledriver,sha256=3YnQpTBgBi7FZtSCrJjAgx9DjFe92-sYoVJAprMBK_o,1411 +archspec/json/tests/targets/linux-rhel7-broadwell,sha256=HBWEiyE2uKDYRS3C0rKspIb_5QypY5fs94NHEDSaPL0,1187 +archspec/json/tests/targets/linux-rhel7-haswell,sha256=kq2qku54qPic_q-CnOw-RUj1nXTG6sZHBUDMhMyZz9g,1095 +archspec/json/tests/targets/linux-rhel7-ivybridge,sha256=PC1NLw9ATBrCN7zHQszxbvHVvMHL1xUFpV1on94UM6Q,1009 +archspec/json/tests/targets/linux-rhel7-skylake_avx512,sha256=3FI8aT-6OwBWE15FKoRDzTiz5BXqXYR5nFNTBg7Y9Qw,1286 +archspec/json/tests/targets/linux-rhel7-x86_64_v3,sha256=D6iKhk9KQlb9qYetPdUBmDVNAVr-hGV297vDHLwe2FM,1172 +archspec/json/tests/targets/linux-rhel7-zen,sha256=icybZCA-bXuasnJHS_qnU0tBpQgjy6-jDRitSC20J1E,1319 +archspec/json/tests/targets/linux-rhel8-neoverse_v1,sha256=gtC-6MNgpPThX_HYYYHEivhqtirB32IlPscVI7kX3D0,351 +archspec/json/tests/targets/linux-rhel8-power9,sha256=Ly0l0wku80CMdizv1UCKEx2Sip9S_0Bd0PTCfQPYHLc,135 +archspec/json/tests/targets/linux-rhel9-neoverse_n2,sha256=tpQ9eG72iCemwazMMW_fGemCgTaSvn3JIUfJW74wyJw,429 +archspec/json/tests/targets/linux-rhel9-neoverse_v2,sha256=XDV98FvAo7RdmI-RpS_ah8pdMWAcmO_sniJ5j1iVIHA,444 +archspec/json/tests/targets/linux-rocky8-a64fx,sha256=rVo-uqYEJnlgPXAhbt-La1W25CR_xfb03rh0t520_1M,256 +archspec/json/tests/targets/linux-rocky8.5-zen4,sha256=y4UDQdOxsg0Hl461XlBD_tPb_TX8EcXV7bwiHQn6zFM,1750 +archspec/json/tests/targets/linux-rocky9-zen5,sha256=_HcNkfT5QjYOl2_55xJA-gd2DFvmhCHOZxK3q63rF5o,1882 +archspec/json/tests/targets/linux-scientific7-k10,sha256=xEhQCc5CIqBWOoe28rvrW-BnjZSkOEBv0gXLQM5yAnE,1111 +archspec/json/tests/targets/linux-scientific7-piledriver,sha256=kKCspg6gamWgMe9h9Mx5hP5O1DXgXOI6iH2B2BfwjDg,1149 +archspec/json/tests/targets/linux-scientificfermi6-bulldozer,sha256=ZmboNqzZEsWWwOwBV_vmrNIi6x1E3E76Uz4Ej15Fu2s,1201 +archspec/json/tests/targets/linux-scientificfermi6-piledriver,sha256=5pVZpVPXtKmqKK1Ps2LmYagCWhWTbjI5co_1QjYjZxI,1099 +archspec/json/tests/targets/linux-sifive-u74mc,sha256=NGnvrcK3VP4qmWk7eZNIAgNED6yvyfcEBasMTmsHgck,124 +archspec/json/tests/targets/linux-ubuntu18.04-broadwell,sha256=Azb3xc9WvgxBvQRNC5m83SJpqr73iLrGSJVJ5s4_zNI,1190 +archspec/json/tests/targets/linux-ubuntu20.04-zen3,sha256=Y7Cws4kwzBlNupQhGl_2woA_1_SWxRqwgzn9NaT3_kg,1531 +archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2,sha256=TR6C4HX2QRciUAwzaJSfTxL7K427NnC_SlfnUTqxFe4,396 +archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2,sha256=FrkEGxnf-indDzUhuyxoMLiURAuC-2Wdk5-FYf0pOSg,458 +archspec/json/tests/targets/linux-unknown-neoverse_v2,sha256=hQfDm2tcyRf3-kwhMTUow2aZujxqbVlnzUEjNaxQC3g,447 +archspec/json/tests/targets/linux-unknown-power10,sha256=7ntCWmXGCTJkfZMMB0mIAk7fe2J7NlO11j0kjKkaSUM,83 +archspec/json/tests/targets/linux-unknown-sapphirerapids,sha256=8AAkJoXaLkNhmcMqUp725T_MIWeyxkarU4poi_Zb0YE,2187 +archspec/json/tests/targets/windows-cpuid-broadwell,sha256=ph0TRQor1s33j9IVjtbE6ZD4-wq7iilty2vnVb4UHDk,395 +archspec/json/tests/targets/windows-cpuid-icelake,sha256=b2JlmnPiUF5JBl3jHCmkRPvon9vCE7_s5NjPph5EGrI,432 +archspec/vendor/cpuid/.git,sha256=hrvgEKtXq8SEhWOQXV_vXrt0dSbrahQy_qNQ1j4aswo,52 +archspec/vendor/cpuid/.gitignore,sha256=JRpFSUVfuHv5eFgg3iaMvtq0hO-MNrYKq1pVwlrXp9M,12 +archspec/vendor/cpuid/LICENSE,sha256=DfgRNgMm2fRV3fECBVNI_aDAMYxc06vKr-Kq0rttsu4,1079 +archspec/vendor/cpuid/README.md,sha256=UPKqGnVjslsiGR2GgXJv-twnYdnFnmCF3_t5CLXmY0Q,2400 +archspec/vendor/cpuid/__pycache__/cpuid.cpython-313.pyc,, +archspec/vendor/cpuid/__pycache__/example.cpython-313.pyc,, +archspec/vendor/cpuid/cpuid.py,sha256=hywlKGTKtPXySyJy67d4OLpaQLfwfsPgUvSPdaxanRQ,6037 +archspec/vendor/cpuid/example.py,sha256=g3EUANGuzhu61l6Z-5iLedPEe_vfObKxys-R5qnI6MY,1855 diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9f0d68ff7fc3c1ff6da960ed2ffd70dd8ea16896 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: poetry-core 2.2.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..a6165286c803f9d8801a84db325aa9a341ebc9d5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_175812491784513/conda-bld/archspec_1758124989039/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f3dc153b53f4ca570f5707b5e12f0401d98ec7d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +archspec=archspec.cli:main + diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-APACHE b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-APACHE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-MIT b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-MIT new file mode 100644 index 0000000000000000000000000000000000000000..03be635ad5df4567a85180c7a03a54ee96e1ee98 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-MIT @@ -0,0 +1,20 @@ +Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +Archspec Project Developers. See the top-level COPYRIGHT file for details. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/NOTICE b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..3737d5a86ddc20bfd04ce225fff2d34407df06f9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec-0.2.5.dist-info/licenses/NOTICE @@ -0,0 +1,21 @@ +This work was produced under the auspices of the U.S. Department of +Energy by Lawrence Livermore National Laboratory under Contract +DE-AC52-07NA27344. + +This work was prepared as an account of work sponsored by an agency of +the United States Government. Neither the United States Government nor +Lawrence Livermore National Security, LLC, nor any of their employees +makes any warranty, expressed or implied, or assumes any legal liability +or responsibility for the accuracy, completeness, or usefulness of any +information, apparatus, product, or process disclosed, or represents that +its use would not infringe privately owned rights. + +Reference herein to any specific commercial product, process, or service +by trade name, trademark, manufacturer, or otherwise does not necessarily +constitute or imply its endorsement, recommendation, or favoring by the +United States Government or Lawrence Livermore National Security, LLC. + +The views and opinions of authors expressed herein do not necessarily +state or reflect those of the United States Government or Lawrence +Livermore National Security, LLC, and shall not be used for advertising +or product endorsement purposes. diff --git a/miniconda3/lib/python3.13/site-packages/archspec/__init__.py b/miniconda3/lib/python3.13/site-packages/archspec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2425354e623ab3e58c65ab9aa67e4c7d884053b4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/__init__.py @@ -0,0 +1,3 @@ +"""Init file to avoid namespace packages""" + +__version__ = "0.2.5" diff --git a/miniconda3/lib/python3.13/site-packages/archspec/__main__.py b/miniconda3/lib/python3.13/site-packages/archspec/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..45fbe12704517a629bf56fa10fbb6e32672c9d74 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/__main__.py @@ -0,0 +1,9 @@ +""" +Run the `archspec` CLI as a module. +""" + +import sys + +from .cli import main + +sys.exit(main()) diff --git a/miniconda3/lib/python3.13/site-packages/archspec/cli.py b/miniconda3/lib/python3.13/site-packages/archspec/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..eaddaf5d77bef895fc6a6104c0f4b6b16ff83735 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/cli.py @@ -0,0 +1,70 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +""" +archspec command line interface +""" + +import argparse +import typing + +import archspec +import archspec.cpu + + +def _make_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + "archspec", + description="archspec command line interface", + add_help=False, + ) + parser.add_argument( + "--version", + "-V", + help="Show the version and exit.", + action="version", + version=f"archspec, version {archspec.__version__}", + ) + parser.add_argument("--help", "-h", help="Show the help and exit.", action="help") + + subcommands = parser.add_subparsers( + title="command", + metavar="COMMAND", + dest="command", + ) + + cpu_command = subcommands.add_parser( + "cpu", + help="archspec command line interface for CPU", + description="archspec command line interface for CPU", + ) + cpu_command.set_defaults(run=cpu) + + return parser + + +def cpu() -> int: + """Run the `archspec cpu` subcommand.""" + try: + print(archspec.cpu.host()) + except FileNotFoundError as exc: + print(exc) + return 1 + return 0 + + +def main(argv: typing.Optional[typing.List[str]] = None) -> int: + """Run the `archspec` command line interface.""" + parser = _make_parser() + + try: + args = parser.parse_args(argv) + except SystemExit as err: + return err.code + + if args.command is None: + parser.print_help() + return 0 + + return args.run() diff --git a/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.py b/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbb43b785db83b1639f8cb9c0b228ab10741eeb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""The "cpu" package permits to query and compare different +CPU microarchitectures. +""" +from .detect import brand_string, host +from .microarchitecture import ( + TARGETS, + InvalidCompilerVersion, + Microarchitecture, + UnsupportedMicroarchitecture, + generic_microarchitecture, + version_components, +) + +__all__ = [ + "brand_string", + "host", + "TARGETS", + "InvalidCompilerVersion", + "Microarchitecture", + "UnsupportedMicroarchitecture", + "generic_microarchitecture", + "version_components", +] diff --git a/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.py b/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.py new file mode 100644 index 0000000000000000000000000000000000000000..783a67d3ea9563f05f23ab6cba45ffc7b261aff1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.py @@ -0,0 +1,87 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Aliases for microarchitecture features.""" +from .schema import TARGETS_JSON, LazyDictionary + +_FEATURE_ALIAS_PREDICATE = {} + + +class FeatureAliasTest: + """A test that must be passed for a feature alias to succeed. + + Args: + rules (dict): dictionary of rules to be met. Each key must be a + valid alias predicate + """ + + # pylint: disable=too-few-public-methods + def __init__(self, rules): + self.rules = rules + self.predicates = [] + for name, args in rules.items(): + self.predicates.append(_FEATURE_ALIAS_PREDICATE[name](args)) + + def __call__(self, microarchitecture): + return all(feature_test(microarchitecture) for feature_test in self.predicates) + + +def _feature_aliases(): + """Returns the dictionary of all defined feature aliases.""" + json_data = TARGETS_JSON["feature_aliases"] + aliases = {} + for alias, rules in json_data.items(): + aliases[alias] = FeatureAliasTest(rules) + return aliases + + +FEATURE_ALIASES = LazyDictionary(_feature_aliases) + + +def alias_predicate(func): + """Decorator to register a predicate that can be used to evaluate + feature aliases. + """ + name = func.__name__ + + # Check we didn't register anything else with the same name + if name in _FEATURE_ALIAS_PREDICATE: + msg = f'the alias predicate "{name}" already exists' + raise KeyError(msg) + + _FEATURE_ALIAS_PREDICATE[name] = func + + return func + + +@alias_predicate +def reason(_): + """This predicate returns always True and it's there to allow writing + a documentation string in the JSON file to explain why an alias is needed. + """ + return lambda x: True + + +@alias_predicate +def any_of(list_of_features): + """Returns a predicate that is True if any of the feature in the + list is in the microarchitecture being tested, False otherwise. + """ + + def _impl(microarchitecture): + return any(x in microarchitecture for x in list_of_features) + + return _impl + + +@alias_predicate +def families(list_of_families): + """Returns a predicate that is True if the architecture family of + the microarchitecture being tested is in the list, False otherwise. + """ + + def _impl(microarchitecture): + return str(microarchitecture.family) in list_of_families + + return _impl diff --git a/miniconda3/lib/python3.13/site-packages/archspec/cpu/detect.py b/miniconda3/lib/python3.13/site-packages/archspec/cpu/detect.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f095f78a6c05fb42dbe21b0e2515e76fdcd5a7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/cpu/detect.py @@ -0,0 +1,459 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Detection of CPU microarchitectures""" +import collections +import os +import platform +import re +import struct +import subprocess +import warnings +from typing import Dict, List, Optional, Set, Tuple, Union + +from ..vendor.cpuid.cpuid import CPUID +from .microarchitecture import TARGETS, Microarchitecture, generic_microarchitecture +from .schema import CPUID_JSON, TARGETS_JSON + +#: Mapping from operating systems to chain of commands +#: to obtain a dictionary of raw info on the current cpu +INFO_FACTORY = collections.defaultdict(list) + +#: Mapping from micro-architecture families (x86_64, ppc64le, etc.) to +#: functions checking the compatibility of the host with a given target +COMPATIBILITY_CHECKS = {} + +# Constants for commonly used architectures +X86_64 = "x86_64" +AARCH64 = "aarch64" +PPC64LE = "ppc64le" +PPC64 = "ppc64" +RISCV64 = "riscv64" + + +def detection(operating_system: str): + """Decorator to mark functions that are meant to return partial information on the current cpu. + + Args: + operating_system: operating system where this function can be used. + """ + + def decorator(factory): + INFO_FACTORY[operating_system].append(factory) + return factory + + return decorator + + +def partial_uarch( + name: str = "", + vendor: str = "", + features: Optional[Set[str]] = None, + generation: int = 0, + cpu_part: str = "", +) -> Microarchitecture: + """Construct a partial microarchitecture, from information gathered during system scan.""" + return Microarchitecture( + name=name, + parents=[], + vendor=vendor, + features=features or set(), + compilers={}, + generation=generation, + cpu_part=cpu_part, + ) + + +@detection(operating_system="Linux") +def proc_cpuinfo() -> Microarchitecture: + """Returns a partial Microarchitecture, obtained from scanning ``/proc/cpuinfo``""" + data = {} + with open("/proc/cpuinfo") as file: # pylint: disable=unspecified-encoding + for line in file: + key, separator, value = line.partition(":") + + # If there's no separator and info was already populated + # according to what's written here: + # + # http://www.linfo.org/proc_cpuinfo.html + # + # we are on a blank line separating two cpus. Exit early as + # we want to read just the first entry in /proc/cpuinfo + if separator != ":" and data: + break + + data[key.strip()] = value.strip() + + architecture = _machine() + if architecture == X86_64: + return partial_uarch( + vendor=data.get("vendor_id", "generic"), features=_feature_set(data, key="flags") + ) + + if architecture == AARCH64: + return partial_uarch( + vendor=_canonicalize_aarch64_vendor(data), + features=_feature_set(data, key="Features"), + cpu_part=data.get("CPU part", ""), + ) + + if architecture in (PPC64LE, PPC64): + generation_match = re.search(r"POWER(\d+)", data.get("cpu", "")) + try: + generation = int(generation_match.group(1)) + except AttributeError: + # There might be no match under emulated environments. For instance + # emulating a ppc64le with QEMU and Docker still reports the host + # /proc/cpuinfo and not a Power + generation = 0 + return partial_uarch(generation=generation) + + if architecture == RISCV64: + if data.get("uarch") == "sifive,u74-mc": + data["uarch"] = "u74mc" + return partial_uarch(name=data.get("uarch", RISCV64)) + + return generic_microarchitecture(architecture) + + +class CpuidInfoCollector: + """Collects the information we need on the host CPU from cpuid""" + + # pylint: disable=too-few-public-methods + def __init__(self): + self.cpuid = CPUID() + + registers = self.cpuid.registers_for(**CPUID_JSON["vendor"]["input"]) + self.highest_basic_support = registers.eax + self.vendor = struct.pack("III", registers.ebx, registers.edx, registers.ecx).decode( + "utf-8" + ) + + registers = self.cpuid.registers_for(**CPUID_JSON["highest_extension_support"]["input"]) + self.highest_extension_support = registers.eax + + self.features = self._features() + + def _features(self): + result = set() + + def check_features(data): + registers = self.cpuid.registers_for(**data["input"]) + for feature_check in data["bits"]: + current = getattr(registers, feature_check["register"]) + if self._is_bit_set(current, feature_check["bit"]): + result.add(feature_check["name"]) + + for call_data in CPUID_JSON["flags"]: + if call_data["input"]["eax"] > self.highest_basic_support: + continue + check_features(call_data) + + for call_data in CPUID_JSON["extension-flags"]: + if call_data["input"]["eax"] > self.highest_extension_support: + continue + check_features(call_data) + + return result + + def _is_bit_set(self, register: int, bit: int) -> bool: + mask = 1 << bit + return register & mask > 0 + + def brand_string(self) -> Optional[str]: + """Returns the brand string, if available.""" + if self.highest_extension_support < 0x80000004: + return None + + r1 = self.cpuid.registers_for(eax=0x80000002, ecx=0) + r2 = self.cpuid.registers_for(eax=0x80000003, ecx=0) + r3 = self.cpuid.registers_for(eax=0x80000004, ecx=0) + result = struct.pack( + "IIIIIIIIIIII", + r1.eax, + r1.ebx, + r1.ecx, + r1.edx, + r2.eax, + r2.ebx, + r2.ecx, + r2.edx, + r3.eax, + r3.ebx, + r3.ecx, + r3.edx, + ).decode("utf-8") + return result.strip("\x00") + + +@detection(operating_system="Windows") +def cpuid_info(): + """Returns a partial Microarchitecture, obtained from running the cpuid instruction""" + architecture = _machine() + if architecture == X86_64: + data = CpuidInfoCollector() + return partial_uarch(vendor=data.vendor, features=data.features) + + return generic_microarchitecture(architecture) + + +def _check_output(args, env): + with subprocess.Popen(args, stdout=subprocess.PIPE, env=env) as proc: + output = proc.communicate()[0] + return str(output.decode("utf-8")) + + +WINDOWS_MAPPING = { + "AMD64": X86_64, + "ARM64": AARCH64, +} + + +def _machine(): + """Return the machine architecture we are on""" + operating_system = platform.system() + + # If we are not on Darwin or Windows, trust what Python tells us + if operating_system not in ("Darwin", "Windows"): + return platform.machine() + + # Normalize windows specific names + if operating_system == "Windows": + platform_machine = platform.machine() + return WINDOWS_MAPPING.get(platform_machine, platform_machine) + + # On Darwin it might happen that we are on M1, but using an interpreter + # built for x86_64. In that case "platform.machine() == 'x86_64'", so we + # need to fix that. + # + # See: https://bugs.python.org/issue42704 + output = _check_output( + ["sysctl", "-n", "machdep.cpu.brand_string"], env=_ensure_bin_usrbin_in_path() + ).strip() + + if "Apple" in output: + # Note that a native Python interpreter on Apple M1 would return + # "arm64" instead of "aarch64". Here we normalize to the latter. + return AARCH64 + + return X86_64 + + +@detection(operating_system="Darwin") +def sysctl_info() -> Microarchitecture: + """Returns a raw info dictionary parsing the output of sysctl.""" + child_environment = _ensure_bin_usrbin_in_path() + + def sysctl(*args: str) -> str: + return _check_output(["sysctl"] + list(args), env=child_environment).strip() + + if _machine() == X86_64: + features = ( + f'{sysctl("-n", "machdep.cpu.features").lower()} ' + f'{sysctl("-n", "machdep.cpu.leaf7_features").lower()}' + ) + features = set(features.split()) + + # Flags detected on Darwin turned to their linux counterpart + for darwin_flag, linux_flag in TARGETS_JSON["conversions"]["darwin_flags"].items(): + if darwin_flag in features: + features.update(linux_flag.split()) + + return partial_uarch(vendor=sysctl("-n", "machdep.cpu.vendor"), features=features) + + model = "unknown" + model_str = sysctl("-n", "machdep.cpu.brand_string").lower() + if "m2" in model_str: + model = "m2" + elif "m1" in model_str: + model = "m1" + elif "apple" in model_str: + model = "m1" + + return partial_uarch(name=model, vendor="Apple") + + +def _ensure_bin_usrbin_in_path(): + # Make sure that /sbin and /usr/sbin are in PATH as sysctl is usually found there + child_environment = dict(os.environ.items()) + search_paths = child_environment.get("PATH", "").split(os.pathsep) + for additional_path in ("/sbin", "/usr/sbin"): + if additional_path not in search_paths: + search_paths.append(additional_path) + child_environment["PATH"] = os.pathsep.join(search_paths) + return child_environment + + +def _canonicalize_aarch64_vendor(data: Dict[str, str]) -> str: + """Adjust the vendor field to make it human-readable""" + if "CPU implementer" not in data: + return "generic" + + # Mapping numeric codes to vendor (ARM). This list is a merge from + # different sources: + # + # https://github.com/karelzak/util-linux/blob/master/sys-utils/lscpu-arm.c + # https://developer.arm.com/docs/ddi0487/latest/arm-architecture-reference-manual-armv8-for-armv8-a-architecture-profile + # https://github.com/gcc-mirror/gcc/blob/master/gcc/config/aarch64/aarch64-cores.def + # https://patchwork.kernel.org/patch/10524949/ + arm_vendors = TARGETS_JSON["conversions"]["arm_vendors"] + arm_code = data["CPU implementer"] + return arm_vendors.get(arm_code, arm_code) + + +def _feature_set(data: Dict[str, str], key: str) -> Set[str]: + return set(data.get(key, "").split()) + + +def detected_info() -> Microarchitecture: + """Returns a partial Microarchitecture with information on the CPU of the current host. + + This function calls all the viable factories one after the other until there's one that is + able to produce the requested information. Falls-back to a generic microarchitecture, if none + of the calls succeed. + """ + # pylint: disable=broad-except + for factory in INFO_FACTORY[platform.system()]: + try: + return factory() + except Exception as exc: + warnings.warn(str(exc)) + + return generic_microarchitecture(_machine()) + + +def compatible_microarchitectures(info: Microarchitecture) -> List[Microarchitecture]: + """Returns an unordered list of known micro-architectures that are compatible with the + partial Microarchitecture passed as input. + """ + architecture_family = _machine() + # If a tester is not registered, assume no known target is compatible with the host + tester = COMPATIBILITY_CHECKS.get(architecture_family, lambda x, y: False) + return [x for x in TARGETS.values() if tester(info, x)] or [ + generic_microarchitecture(architecture_family) + ] + + +def host(): + """Detects the host micro-architecture and returns it.""" + # Retrieve information on the host's cpu + info = detected_info() + + # Get a list of possible candidates for this micro-architecture + candidates = compatible_microarchitectures(info) + + # Sorting criteria for candidates + def sorting_fn(item): + return len(item.ancestors), len(item.features) + + # Get the best generic micro-architecture + generic_candidates = [c for c in candidates if c.vendor == "generic"] + best_generic = max(generic_candidates, key=sorting_fn) + + # Relevant for AArch64. Filter on "cpu_part" if we have any match + if info.cpu_part != "" and any(c for c in candidates if info.cpu_part == c.cpu_part): + candidates = [c for c in candidates if info.cpu_part == c.cpu_part] + + # Filter the candidates to be descendant of the best generic candidate. + # This is to avoid that the lack of a niche feature that can be disabled + # from e.g. BIOS prevents detection of a reasonably performant architecture + candidates = [c for c in candidates if c > best_generic] + + # If we don't have candidates, return the best generic micro-architecture + if not candidates: + return best_generic + + # Reverse sort of the depth for the inheritance tree among only targets we + # can use. This gets the newest target we satisfy. + return max(candidates, key=sorting_fn) + + +def compatibility_check(architecture_family: Union[str, Tuple[str, ...]]): + """Decorator to register a function as a proper compatibility check. + + A compatibility check function takes a partial Microarchitecture object as a first argument, + and an arbitrary target Microarchitecture as the second argument. It returns True if the + target is compatible with first argument, False otherwise. + + Args: + architecture_family: architecture family for which this test can be used + """ + # Turn the argument into something iterable + if isinstance(architecture_family, str): + architecture_family = (architecture_family,) + + def decorator(func): + COMPATIBILITY_CHECKS.update({family: func for family in architecture_family}) + return func + + return decorator + + +@compatibility_check(architecture_family=(PPC64LE, PPC64)) +def compatibility_check_for_power(info, target): + """Compatibility check for PPC64 and PPC64LE architectures.""" + # We can use a target if it descends from our machine type and our + # generation (9 for POWER9, etc) is at least its generation. + arch_root = TARGETS[_machine()] + return ( + target == arch_root or arch_root in target.ancestors + ) and target.generation <= info.generation + + +@compatibility_check(architecture_family=X86_64) +def compatibility_check_for_x86_64(info, target): + """Compatibility check for x86_64 architectures.""" + # We can use a target if it descends from our machine type, is from our + # vendor, and we have all of its features + arch_root = TARGETS[X86_64] + return ( + (target == arch_root or arch_root in target.ancestors) + and target.vendor in (info.vendor, "generic") + and target.features.issubset(info.features) + ) + + +@compatibility_check(architecture_family=AARCH64) +def compatibility_check_for_aarch64(info, target): + """Compatibility check for AARCH64 architectures.""" + # At the moment, it's not clear how to detect compatibility with + # a specific version of the architecture + if target.vendor == "generic" and target.name != AARCH64: + return False + + arch_root = TARGETS[AARCH64] + arch_root_and_vendor = arch_root == target.family and target.vendor in ( + info.vendor, + "generic", + ) + + # On macOS it seems impossible to get all the CPU features + # with syctl info, but for ARM we can get the exact model + if platform.system() == "Darwin": + model = TARGETS[info.name] + return arch_root_and_vendor and (target == model or target in model.ancestors) + + return arch_root_and_vendor and target.features.issubset(info.features) + + +@compatibility_check(architecture_family=RISCV64) +def compatibility_check_for_riscv64(info, target): + """Compatibility check for riscv64 architectures.""" + arch_root = TARGETS[RISCV64] + return (target == arch_root or arch_root in target.ancestors) and ( + target.name == info.name or target.vendor == "generic" + ) + + +def brand_string() -> Optional[str]: + """Returns the brand string of the host, if detected, or None.""" + if platform.system() == "Darwin": + return _check_output( + ["sysctl", "-n", "machdep.cpu.brand_string"], env=_ensure_bin_usrbin_in_path() + ).strip() + + if host().family == X86_64: + return CpuidInfoCollector().brand_string() + + return None diff --git a/miniconda3/lib/python3.13/site-packages/archspec/cpu/microarchitecture.py b/miniconda3/lib/python3.13/site-packages/archspec/cpu/microarchitecture.py new file mode 100644 index 0000000000000000000000000000000000000000..bb85b9f37c0966b3a7eb30b0a811d4db83a74eed --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/cpu/microarchitecture.py @@ -0,0 +1,416 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Types and functions to manage information on CPU microarchitectures.""" +import functools +import platform +import re +import warnings + +import archspec +import archspec.cpu.alias +import archspec.cpu.schema + +from .alias import FEATURE_ALIASES +from .schema import LazyDictionary + + +def coerce_target_names(func): + """Decorator that automatically converts a known target name to a proper + Microarchitecture object. + """ + + @functools.wraps(func) + def _impl(self, other): + if isinstance(other, str): + if other not in TARGETS: + msg = '"{0}" is not a valid target name' + raise ValueError(msg.format(other)) + other = TARGETS[other] + + return func(self, other) + + return _impl + + +class Microarchitecture: + """Represents a specific CPU micro-architecture. + + Args: + name (str): name of the micro-architecture (e.g. skylake). + parents (list): list of parents micro-architectures, if any. + Parenthood is considered by cpu features and not + chronologically. As such each micro-architecture is + compatible with its ancestors. For example "skylake", + which has "broadwell" as a parent, supports running binaries + optimized for "broadwell". + vendor (str): vendor of the micro-architecture + features (set of str): supported CPU flags. Note that the semantic + of the flags in this field might vary among architectures, if + at all present. For instance x86_64 processors will list all + the flags supported by a given CPU while Arm processors will + list instead only the flags that have been added on top of the + base model for the current micro-architecture. + compilers (dict): compiler support to generate tuned code for this + micro-architecture. This dictionary has as keys names of + supported compilers, while values are list of dictionaries + with fields: + + * name: name of the micro-architecture according to the + compiler. This is the name passed to the ``-march`` option + or similar. Not needed if the name is the same as that + passed in as argument above. + * versions: versions that support this micro-architecture. + + generation (int): generation of the micro-architecture, if relevant. + cpu_part (str): cpu part of the architecture, if relevant. + """ + + # pylint: disable=too-many-arguments,too-many-instance-attributes + #: Aliases for micro-architecture's features + feature_aliases = FEATURE_ALIASES + + def __init__(self, name, parents, vendor, features, compilers, generation=0, cpu_part=""): + self.name = name + self.parents = parents + self.vendor = vendor + self.features = features + self.compilers = compilers + # Only relevant for PowerPC + self.generation = generation + # Only relevant for AArch64 + self.cpu_part = cpu_part + + # Cache the "ancestor" computation + self._ancestors = None + # Cache the "generic" computation + self._generic = None + # Cache the "family" computation + self._family = None + + @property + def ancestors(self): + """All the ancestors of this microarchitecture.""" + if self._ancestors is None: + value = self.parents[:] + for parent in self.parents: + value.extend(a for a in parent.ancestors if a not in value) + self._ancestors = value + return self._ancestors + + def _to_set(self): + """Returns a set of the nodes in this microarchitecture DAG.""" + # This function is used to implement subset semantics with + # comparison operators + return set([str(self)] + [str(x) for x in self.ancestors]) + + @coerce_target_names + def __eq__(self, other): + if not isinstance(other, Microarchitecture): + return NotImplemented + + return ( + self.name == other.name + and self.vendor == other.vendor + and self.features == other.features + and self.parents == other.parents # avoid ancestors here + and self.compilers == other.compilers + and self.generation == other.generation + and self.cpu_part == other.cpu_part + ) + + def __hash__(self): + return hash(self.name) + + @coerce_target_names + def __ne__(self, other): + return not self == other + + @coerce_target_names + def __lt__(self, other): + if not isinstance(other, Microarchitecture): + return NotImplemented + + return self._to_set() < other._to_set() + + @coerce_target_names + def __le__(self, other): + return (self == other) or (self < other) + + @coerce_target_names + def __gt__(self, other): + if not isinstance(other, Microarchitecture): + return NotImplemented + + return self._to_set() > other._to_set() + + @coerce_target_names + def __ge__(self, other): + return (self == other) or (self > other) + + def __repr__(self): + cls_name = self.__class__.__name__ + fmt = ( + cls_name + "({0.name!r}, {0.parents!r}, {0.vendor!r}, " + "{0.features!r}, {0.compilers!r}, generation={0.generation!r}, " + "cpu_part={0.cpu_part!r})" + ) + return fmt.format(self) + + def __str__(self): + return self.name + + def __contains__(self, feature): + # Feature must be of a string type, so be defensive about that + if not isinstance(feature, str): + msg = "only objects of string types are accepted [got {0}]" + raise TypeError(msg.format(str(type(feature)))) + + # Here we look first in the raw features, and fall-back to + # feature aliases if not match was found + if feature in self.features: + return True + + # Check if the alias is defined, if not it will return False + match_alias = Microarchitecture.feature_aliases.get(feature, lambda x: False) + return match_alias(self) + + @property + def family(self): + """Returns the architecture family a given target belongs to""" + if self._family is None: + roots = [x for x in [self] + self.ancestors if not x.ancestors] + msg = "a target is expected to belong to just one architecture family" + msg += f"[found {', '.join(str(x) for x in roots)}]" + assert len(roots) == 1, msg + self._family = roots.pop() + + return self._family + + @property + def generic(self): + """Returns the best generic architecture that is compatible with self""" + if self._generic is None: + generics = [x for x in [self] + self.ancestors if x.vendor == "generic"] + self._generic = max(generics, key=lambda x: len(x.ancestors)) + return self._generic + + def to_dict(self): + """Returns a dictionary representation of this object.""" + return { + "name": str(self.name), + "vendor": str(self.vendor), + "features": sorted(str(x) for x in self.features), + "generation": self.generation, + "parents": [str(x) for x in self.parents], + "compilers": self.compilers, + "cpupart": self.cpu_part, + } + + @staticmethod + def from_dict(data) -> "Microarchitecture": + """Construct a microarchitecture from a dictionary representation.""" + return Microarchitecture( + name=data["name"], + parents=[TARGETS[x] for x in data["parents"]], + vendor=data["vendor"], + features=set(data["features"]), + compilers=data.get("compilers", {}), + generation=data.get("generation", 0), + cpu_part=data.get("cpupart", ""), + ) + + def optimization_flags(self, compiler, version): + """Returns a string containing the optimization flags that needs + to be used to produce code optimized for this micro-architecture. + + The version is expected to be a string of dot separated digits. + + If there is no information on the compiler passed as argument the + function returns an empty string. If it is known that the compiler + version we want to use does not support this architecture the function + raises an exception. + + Args: + compiler (str): name of the compiler to be used + version (str): version of the compiler to be used + + Raises: + UnsupportedMicroarchitecture: if the requested compiler does not support + this micro-architecture. + ValueError: if the version doesn't match the expected format + """ + # If we don't have information on compiler at all return an empty string + if compiler not in self.family.compilers: + return "" + + # If we have information but it stops before this + # microarchitecture, fall back to the best known target + if compiler not in self.compilers: + best_target = [x for x in self.ancestors if compiler in x.compilers][0] + msg = ( + "'{0}' compiler is known to optimize up to the '{1}'" + " microarchitecture in the '{2}' architecture family" + ) + msg = msg.format(compiler, best_target, best_target.family) + raise UnsupportedMicroarchitecture(msg) + + # Check that the version matches the expected format + if not re.match(r"^(?:\d+\.)*\d+$", version): + msg = ( + "invalid format for the compiler version argument. " + "Only dot separated digits are allowed." + ) + raise InvalidCompilerVersion(msg) + + # If we have information on this compiler we need to check the + # version being used + compiler_info = self.compilers[compiler] + + def satisfies_constraint(entry, version): + min_version, max_version = entry["versions"].split(":") + + # Check version suffixes + min_version, _ = version_components(min_version) + max_version, _ = version_components(max_version) + version, _ = version_components(version) + + # Assume compiler versions fit into semver + def tuplify(ver): + return tuple(int(y) for y in ver.split(".")) + + version = tuplify(version) + if min_version: + min_version = tuplify(min_version) + if min_version > version: + return False + + if max_version: + max_version = tuplify(max_version) + if max_version < version: + return False + + return True + + for compiler_entry in compiler_info: + if satisfies_constraint(compiler_entry, version): + flags_fmt = compiler_entry["flags"] + # If there's no field name, use the name of the + # micro-architecture + compiler_entry.setdefault("name", self.name) + + # Check if we need to emit a warning + warning_message = compiler_entry.get("warnings", None) + if warning_message: + warnings.warn(warning_message) + + flags = flags_fmt.format(**compiler_entry) + return flags + + msg = "cannot produce optimized binary for micro-architecture '{0}' with {1}@{2}" + if compiler_info: + versions = [x["versions"] for x in compiler_info] + msg += f' [supported compiler versions are {", ".join(versions)}]' + else: + msg += " [no supported compiler versions]" + msg = msg.format(self.name, compiler, version) + raise UnsupportedMicroarchitecture(msg) + + +def generic_microarchitecture(name): + """Returns a generic micro-architecture with no vendor and no features. + + Args: + name (str): name of the micro-architecture + """ + return Microarchitecture(name, parents=[], vendor="generic", features=set(), compilers={}) + + +def version_components(version): + """Decomposes the version passed as input in version number and + suffix and returns them. + + If the version number or the suffix are not present, an empty + string is returned. + + Args: + version (str): version to be decomposed into its components + """ + match = re.match(r"([\d.]*)(-?)(.*)", str(version)) + if not match: + return "", "" + + version_number = match.group(1) + suffix = match.group(3) + + return version_number, suffix + + +def _known_microarchitectures(): + """Returns a dictionary of the known micro-architectures. If the + current host platform is unknown adds it too as a generic target. + """ + + def fill_target_from_dict(name, data, targets): + """Recursively fills targets by adding the micro-architecture + passed as argument and all its ancestors. + + Args: + name (str): micro-architecture to be added to targets. + data (dict): raw data loaded from JSON. + targets (dict): dictionary that maps micro-architecture names + to ``Microarchitecture`` objects + """ + values = data[name] + + # Get direct parents of target + parent_names = values["from"] + for parent in parent_names: + # Recursively fill parents so they exist before we add them + if parent in targets: + continue + fill_target_from_dict(parent, data, targets) + parents = [targets.get(parent) for parent in parent_names] + + vendor = values["vendor"] + features = set(values["features"]) + compilers = values.get("compilers", {}) + generation = values.get("generation", 0) + cpu_part = values.get("cpupart", "") + + targets[name] = Microarchitecture( + name, parents, vendor, features, compilers, generation=generation, cpu_part=cpu_part + ) + + known_targets = {} + data = archspec.cpu.schema.TARGETS_JSON["microarchitectures"] + for name in data: + if name in known_targets: + # name was already brought in as ancestor to a target + continue + fill_target_from_dict(name, data, known_targets) + + # Add the host platform if not present + host_platform = platform.machine() + known_targets.setdefault(host_platform, generic_microarchitecture(host_platform)) + + return known_targets + + +#: Dictionary of known micro-architectures +TARGETS = LazyDictionary(_known_microarchitectures) + + +class ArchspecError(Exception): + """Base class for errors within archspec""" + + +class UnsupportedMicroarchitecture(ArchspecError, ValueError): + """Raised if a compiler version does not support optimization for a given + micro-architecture. + """ + + +class InvalidCompilerVersion(ArchspecError, ValueError): + """Raised when an invalid format is used for compiler versions in archspec.""" diff --git a/miniconda3/lib/python3.13/site-packages/archspec/cpu/schema.py b/miniconda3/lib/python3.13/site-packages/archspec/cpu/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffc2231650b6952d3b9ad2fe6674632100d6607 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/cpu/schema.py @@ -0,0 +1,112 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Global objects with the content of the microarchitecture +JSON file and its schema +""" +import collections.abc +import json +import os +import pathlib +from typing import Tuple + + +class LazyDictionary(collections.abc.MutableMapping): + """Lazy dictionary that gets constructed on first access to any object key + + Args: + factory (callable): factory function to construct the dictionary + """ + + def __init__(self, factory, *args, **kwargs): + self.factory = factory + self.args = args + self.kwargs = kwargs + self._data = None + + @property + def data(self): + """Returns the lazily constructed dictionary""" + if self._data is None: + self._data = self.factory(*self.args, **self.kwargs) + return self._data + + def __getitem__(self, key): + return self.data[key] + + def __setitem__(self, key, value): + self.data[key] = value + + def __delitem__(self, key): + del self.data[key] + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + + +#: Environment variable that might point to a directory with a user defined JSON file +DIR_FROM_ENVIRONMENT = "ARCHSPEC_CPU_DIR" + +#: Environment variable that might point to a directory with extensions to JSON files +EXTENSION_DIR_FROM_ENVIRONMENT = "ARCHSPEC_EXTENSION_CPU_DIR" + + +def _json_file(filename: str, allow_custom: bool = False) -> Tuple[pathlib.Path, pathlib.Path]: + """Given a filename, returns the absolute path for the main JSON file, and an + optional absolute path for an extension JSON file. + + Args: + filename: filename for the JSON file + allow_custom: if True, allows overriding the location where the file resides + """ + json_dir = pathlib.Path(__file__).parent / ".." / "json" / "cpu" + if allow_custom and DIR_FROM_ENVIRONMENT in os.environ: + json_dir = pathlib.Path(os.environ[DIR_FROM_ENVIRONMENT]) + json_dir = json_dir.absolute() + json_file = json_dir / filename + + extension_file = None + if allow_custom and EXTENSION_DIR_FROM_ENVIRONMENT in os.environ: + extension_dir = pathlib.Path(os.environ[EXTENSION_DIR_FROM_ENVIRONMENT]) + extension_dir.absolute() + extension_file = extension_dir / filename + + return json_file, extension_file + + +def _load(json_file: pathlib.Path, extension_file: pathlib.Path): + with open(json_file, "r", encoding="utf-8") as file: + data = json.load(file) + + if not extension_file or not extension_file.exists(): + return data + + with open(extension_file, "r", encoding="utf-8") as file: + extension_data = json.load(file) + + top_level_sections = list(data.keys()) + for key in top_level_sections: + if key not in extension_data: + continue + + data[key].update(extension_data[key]) + + return data + + +#: In memory representation of the data in microarchitectures.json, +#: loaded on first access +TARGETS_JSON = LazyDictionary(_load, *_json_file("microarchitectures.json", allow_custom=True)) + +#: JSON schema for microarchitectures.json, loaded on first access +TARGETS_JSON_SCHEMA = LazyDictionary(_load, *_json_file("microarchitectures_schema.json")) + +#: Information on how to call 'cpuid' to get information on the HOST CPU +CPUID_JSON = LazyDictionary(_load, *_json_file("cpuid.json", allow_custom=True)) + +#: JSON schema for cpuid.json, loaded on first access +CPUID_JSON_SCHEMA = LazyDictionary(_load, *_json_file("cpuid_schema.json")) diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/COPYRIGHT b/miniconda3/lib/python3.13/site-packages/archspec/json/COPYRIGHT new file mode 100644 index 0000000000000000000000000000000000000000..4164e98de77169c98f258c4ac8eff4daf9f78f4e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/COPYRIGHT @@ -0,0 +1,22 @@ +Intellectual Property Notice +------------------------------ + +Archspec is licensed under the Apache License, Version 2.0 (LICENSE-APACHE +or http://www.apache.org/licenses/LICENSE-2.0) or the MIT license, +(LICENSE-MIT or http://opensource.org/licenses/MIT), at your option. + +Copyrights and patents in the Archspec project are retained by contributors. +No copyright assignment is required to contribute to Archspec. + + +SPDX usage +------------ + +Individual files contain SPDX tags instead of the full license text. +This enables machine processing of license information based on the SPDX +License Identifiers that are available here: https://spdx.org/licenses/ + +Files that are dual-licensed as Apache-2.0 OR MIT contain the following +text in the license header: + + SPDX-License-Identifier: (Apache-2.0 OR MIT) diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-APACHE b/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-APACHE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-MIT b/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-MIT new file mode 100644 index 0000000000000000000000000000000000000000..03be635ad5df4567a85180c7a03a54ee96e1ee98 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-MIT @@ -0,0 +1,20 @@ +Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +Archspec Project Developers. See the top-level COPYRIGHT file for details. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/NOTICE b/miniconda3/lib/python3.13/site-packages/archspec/json/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..3737d5a86ddc20bfd04ce225fff2d34407df06f9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/NOTICE @@ -0,0 +1,21 @@ +This work was produced under the auspices of the U.S. Department of +Energy by Lawrence Livermore National Laboratory under Contract +DE-AC52-07NA27344. + +This work was prepared as an account of work sponsored by an agency of +the United States Government. Neither the United States Government nor +Lawrence Livermore National Security, LLC, nor any of their employees +makes any warranty, expressed or implied, or assumes any legal liability +or responsibility for the accuracy, completeness, or usefulness of any +information, apparatus, product, or process disclosed, or represents that +its use would not infringe privately owned rights. + +Reference herein to any specific commercial product, process, or service +by trade name, trademark, manufacturer, or otherwise does not necessarily +constitute or imply its endorsement, recommendation, or favoring by the +United States Government or Lawrence Livermore National Security, LLC. + +The views and opinions of authors expressed herein do not necessarily +state or reflect those of the United States Government or Lawrence +Livermore National Security, LLC, and shall not be used for advertising +or product endorsement purposes. diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/README.md b/miniconda3/lib/python3.13/site-packages/archspec/json/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78c424a86fa348b1b48001b649df8530fa3da2ac --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/README.md @@ -0,0 +1,36 @@ +[![](https://github.com/archspec/archspec-json/workflows/JSON%20Validation/badge.svg)](https://github.com/archspec/archspec-json/actions) + +# Archspec-json + +The [archspec-json](https://github.com/archspec/archspec-json) repository is part of the +[Archspec](https://github.com/archspec) project. It contains data on various architectural +aspects of a platform stored in JSON format and is meant to be used as a base to develop +language specific APIs. + +Currently the repository contains the following JSON files: +```console +cpu/ +├── cpuid.json # Contains information on CPUID calls to retrieve vendor and features on x86_64 +├── cpuid_schema.json # Schema for the file above +├── microarchitectures.json # Contains information on CPU microarchitectures +└── microarchitectures_schema.json # Schema for the file above + ``` + + +## License + +Archspec is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). Users may choose either license, at their +option. + +All new contributions must be made under both the MIT and Apache-2.0 +licenses. + +See [LICENSE-MIT](https://github.com/archspec/archspec-json/blob/master/LICENSE-MIT), +[LICENSE-APACHE](https://github.com/archspec/archspec-json/blob/master/LICENSE-APACHE), +[COPYRIGHT](https://github.com/archspec/archspec-json/blob/master/COPYRIGHT), and +[NOTICE](https://github.com/archspec/archspec-json/blob/master/NOTICE) for details. + +SPDX-License-Identifier: (Apache-2.0 OR MIT) + +LLNL-CODE-811653 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid.json b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid.json new file mode 100644 index 0000000000000000000000000000000000000000..594e435383ad50c0cd6f71f965b27b54343f502a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid.json @@ -0,0 +1,1050 @@ +{ + "vendor": { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=0:_Highest_Function_Parameter_and_Manufacturer_ID", + "input": { + "eax": 0, + "ecx": 0 + } + }, + "highest_extension_support": { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=80000000h:_Get_Highest_Extended_Function_Implemented", + "input": { + "eax": 2147483648, + "ecx": 0 + } + }, + "flags": [ + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=1:_Processor_Info_and_Feature_Bits", + "input": { + "eax": 1, + "ecx": 0 + }, + "bits": [ + { + "name": "fpu", + "register": "edx", + "bit": 0 + }, + { + "name": "vme", + "register": "edx", + "bit": 1 + }, + { + "name": "de", + "register": "edx", + "bit": 2 + }, + { + "name": "pse", + "register": "edx", + "bit": 3 + }, + { + "name": "tsc", + "register": "edx", + "bit": 4 + }, + { + "name": "msr", + "register": "edx", + "bit": 5 + }, + { + "name": "pae", + "register": "edx", + "bit": 6 + }, + { + "name": "mce", + "register": "edx", + "bit": 7 + }, + { + "name": "cx8", + "register": "edx", + "bit": 8 + }, + { + "name": "apic", + "register": "edx", + "bit": 9 + }, + { + "name": "sep", + "register": "edx", + "bit": 11 + }, + { + "name": "mtrr", + "register": "edx", + "bit": 12 + }, + { + "name": "pge", + "register": "edx", + "bit": 13 + }, + { + "name": "mca", + "register": "edx", + "bit": 14 + }, + { + "name": "cmov", + "register": "edx", + "bit": 15 + }, + { + "name": "pat", + "register": "edx", + "bit": 16 + }, + { + "name": "pse36", + "register": "edx", + "bit": 17 + }, + { + "name": "pn", + "register": "edx", + "bit": 18 + }, + { + "name": "clflush", + "register": "edx", + "bit": 19 + }, + { + "name": "dts", + "register": "edx", + "bit": 21 + }, + { + "name": "acpi", + "register": "edx", + "bit": 22 + }, + { + "name": "mmx", + "register": "edx", + "bit": 23 + }, + { + "name": "fxsr", + "register": "edx", + "bit": 24 + }, + { + "name": "sse", + "register": "edx", + "bit": 25 + }, + { + "name": "sse2", + "register": "edx", + "bit": 26 + }, + { + "name": "ss", + "register": "edx", + "bit": 27 + }, + { + "name": "ht", + "register": "edx", + "bit": 28 + }, + { + "name": "tm", + "register": "edx", + "bit": 29 + }, + { + "name": "ia64", + "register": "edx", + "bit": 30 + }, + { + "name": "pbe", + "register": "edx", + "bit": 31 + }, + { + "name": "pni", + "register": "ecx", + "bit": 0 + }, + { + "name": "pclmulqdq", + "register": "ecx", + "bit": 1 + }, + { + "name": "dtes64", + "register": "ecx", + "bit": 2 + }, + { + "name": "monitor", + "register": "ecx", + "bit": 3 + }, + { + "name": "ds_cpl", + "register": "ecx", + "bit": 4 + }, + { + "name": "vmx", + "register": "ecx", + "bit": 5 + }, + { + "name": "smx", + "register": "ecx", + "bit": 6 + }, + { + "name": "est", + "register": "ecx", + "bit": 7 + }, + { + "name": "tm2", + "register": "ecx", + "bit": 8 + }, + { + "name": "ssse3", + "register": "ecx", + "bit": 9 + }, + { + "name": "cid", + "register": "ecx", + "bit": 10 + }, + { + "name": "fma", + "register": "ecx", + "bit": 12 + }, + { + "name": "cx16", + "register": "ecx", + "bit": 13 + }, + { + "name": "xtpr", + "register": "ecx", + "bit": 14 + }, + { + "name": "pdcm", + "register": "ecx", + "bit": 15 + }, + { + "name": "pcid", + "register": "ecx", + "bit": 17 + }, + { + "name": "dca", + "register": "ecx", + "bit": 18 + }, + { + "name": "sse4_1", + "register": "ecx", + "bit": 19 + }, + { + "name": "sse4_2", + "register": "ecx", + "bit": 20 + }, + { + "name": "x2apic", + "register": "ecx", + "bit": 21 + }, + { + "name": "movbe", + "register": "ecx", + "bit": 22 + }, + { + "name": "popcnt", + "register": "ecx", + "bit": 23 + }, + { + "name": "tscdeadline", + "register": "ecx", + "bit": 24 + }, + { + "name": "aes", + "register": "ecx", + "bit": 25 + }, + { + "name": "xsave", + "register": "ecx", + "bit": 26 + }, + { + "name": "osxsave", + "register": "ecx", + "bit": 27 + }, + { + "name": "avx", + "register": "ecx", + "bit": 28 + }, + { + "name": "f16c", + "register": "ecx", + "bit": 29 + }, + { + "name": "rdrand", + "register": "ecx", + "bit": 30 + }, + { + "name": "hypervisor", + "register": "ecx", + "bit": 31 + } + ] + }, + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features", + "input": { + "eax": 7, + "ecx": 0 + }, + "bits": [ + { + "name": "fsgsbase", + "register": "ebx", + "bit": 0 + }, + { + "name": "sgx", + "register": "ebx", + "bit": 2 + }, + { + "name": "bmi1", + "register": "ebx", + "bit": 3 + }, + { + "name": "hle", + "register": "ebx", + "bit": 4 + }, + { + "name": "avx2", + "register": "ebx", + "bit": 5 + }, + { + "name": "fdp-excptn-only", + "register": "ebx", + "bit": 6 + }, + { + "name": "smep", + "register": "ebx", + "bit": 7 + }, + { + "name": "bmi2", + "register": "ebx", + "bit": 8 + }, + { + "name": "erms", + "register": "ebx", + "bit": 9 + }, + { + "name": "invpcid", + "register": "ebx", + "bit": 10 + }, + { + "name": "rtm", + "register": "ebx", + "bit": 11 + }, + { + "name": "pqm", + "register": "ebx", + "bit": 12 + }, + { + "name": "mpx", + "register": "ebx", + "bit": 14 + }, + { + "name": "pqe", + "register": "ebx", + "bit": 15 + }, + { + "name": "avx512f", + "register": "ebx", + "bit": 16 + }, + { + "name": "avx512dq", + "register": "ebx", + "bit": 17 + }, + { + "name": "rdseed", + "register": "ebx", + "bit": 18 + }, + { + "name": "adx", + "register": "ebx", + "bit": 19 + }, + { + "name": "smap", + "register": "ebx", + "bit": 20 + }, + { + "name": "avx512ifma", + "register": "ebx", + "bit": 21 + }, + { + "name": "pcommit", + "register": "ebx", + "bit": 22 + }, + { + "name": "clflushopt", + "register": "ebx", + "bit": 23 + }, + { + "name": "clwb", + "register": "ebx", + "bit": 24 + }, + { + "name": "intel_pt", + "register": "ebx", + "bit": 25 + }, + { + "name": "avx512pf", + "register": "ebx", + "bit": 26 + }, + { + "name": "avx512er", + "register": "ebx", + "bit": 27 + }, + { + "name": "avx512cd", + "register": "ebx", + "bit": 28 + }, + { + "name": "sha_ni", + "register": "ebx", + "bit": 29 + }, + { + "name": "avx512bw", + "register": "ebx", + "bit": 30 + }, + { + "name": "avx512vl", + "register": "ebx", + "bit": 31 + }, + { + "name": "prefetchwt1", + "register": "ecx", + "bit": 0 + }, + { + "name": "avx512vbmi", + "register": "ecx", + "bit": 1 + }, + { + "name": "umip", + "register": "ecx", + "bit": 2 + }, + { + "name": "pku", + "register": "ecx", + "bit": 3 + }, + { + "name": "ospke", + "register": "ecx", + "bit": 4 + }, + { + "name": "waitpkg", + "register": "ecx", + "bit": 5 + }, + { + "name": "avx512_vbmi2", + "register": "ecx", + "bit": 6 + }, + { + "name": "cet_ss", + "register": "ecx", + "bit": 7 + }, + { + "name": "gfni", + "register": "ecx", + "bit": 8 + }, + { + "name": "vaes", + "register": "ecx", + "bit": 9 + }, + { + "name": "vpclmulqdq", + "register": "ecx", + "bit": 10 + }, + { + "name": "avx512_vnni", + "register": "ecx", + "bit": 11 + }, + { + "name": "avx512_bitalg", + "register": "ecx", + "bit": 12 + }, + { + "name": "tme", + "register": "ecx", + "bit": 13 + }, + { + "name": "avx512_vpopcntdq", + "register": "ecx", + "bit": 14 + }, + { + "name": "rdpid", + "register": "ecx", + "bit": 22 + }, + { + "name": "cldemote", + "register": "ecx", + "bit": 25 + }, + { + "name": "movdiri", + "register": "ecx", + "bit": 27 + }, + { + "name": "movdir64b", + "register": "ecx", + "bit": 28 + }, + { + "name": "enqcmd", + "register": "ecx", + "bit": 29 + }, + { + "name": "sgx_lc", + "register": "ecx", + "bit": 30 + }, + { + "name": "pks", + "register": "ecx", + "bit": 31 + }, + { + "name": "fsrm", + "register": "edx", + "bit": 4 + }, + { + "name": "avx512_vp2intersect", + "register": "edx", + "bit": 8 + }, + { + "name": "md_clear", + "register": "edx", + "bit": 10 + }, + { + "name": "serialize", + "register": "edx", + "bit": 14 + }, + { + "name": "tsxldtrk", + "register": "edx", + "bit": 16 + }, + { + "name": "amx_bf16", + "register": "edx", + "bit": 22 + }, + { + "name": "avx512_fp16", + "register": "edx", + "bit": 23 + }, + { + "name": "amx_tile", + "register": "edx", + "bit": 24 + }, + { + "name": "amx_int8", + "register": "edx", + "bit": 25 + }, + { + "name": "ssbd", + "register": "edx", + "bit": 31 + } + ] + }, + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features", + "input": { + "eax": 7, + "ecx": 1 + }, + "bits": [ + { + "name": "sha512", + "register": "eax", + "bit": 0 + }, + { + "name": "sm3", + "register": "eax", + "bit": 1 + }, + { + "name": "sm4", + "register": "eax", + "bit": 2 + }, + { + "name": "rao_int", + "register": "eax", + "bit": 3 + }, + { + "name": "avx_vnni", + "register": "eax", + "bit": 4 + }, + { + "name": "avx512_bf16", + "register": "eax", + "bit": 5 + }, + { + "name": "cmpccxadd", + "register": "eax", + "bit": 7 + }, + { + "name": "arch_perfmon_ext", + "register": "eax", + "bit": 8 + }, + { + "name": "fzrm", + "register": "eax", + "bit": 10 + }, + { + "name": "fsrs", + "register": "eax", + "bit": 11 + }, + { + "name": "fsrc", + "register": "eax", + "bit": 12 + }, + { + "name": "lkgs", + "register": "eax", + "bit": 18 + }, + { + "name": "amx_fp16", + "register": "eax", + "bit": 21 + }, + { + "name": "avx_ifma", + "register": "eax", + "bit": 23 + }, + { + "name": "lam", + "register": "eax", + "bit": 26 + } + ] + }, + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=0Dh:_XSAVE_features_and_state-components", + "input": { + "eax": 13, + "ecx": 1 + }, + "bits": [ + { + "name": "xsaveopt", + "register": "eax", + "bit": 0 + }, + { + "name": "xsavec", + "register": "eax", + "bit": 1 + }, + { + "name": "xgetbv1", + "register": "eax", + "bit": 2 + }, + { + "name": "xsaves", + "register": "eax", + "bit": 3 + }, + { + "name": "xfd", + "register": "eax", + "bit": 4 + } + ] + } + ], + "extension-flags": [ + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=0Dh:_XSAVE_features_and_state-components", + "input": { + "eax": 2147483649, + "ecx": 0 + }, + "bits": [ + { + "name": "fpu", + "register": "edx", + "bit": 0 + }, + { + "name": "vme", + "register": "edx", + "bit": 1 + }, + { + "name": "de", + "register": "edx", + "bit": 2 + }, + { + "name": "pse", + "register": "edx", + "bit": 3 + }, + { + "name": "tsc", + "register": "edx", + "bit": 4 + }, + { + "name": "msr", + "register": "edx", + "bit": 5 + }, + { + "name": "pae", + "register": "edx", + "bit": 6 + }, + { + "name": "mce", + "register": "edx", + "bit": 7 + }, + { + "name": "cx8", + "register": "edx", + "bit": 8 + }, + { + "name": "apic", + "register": "edx", + "bit": 9 + }, + { + "name": "syscall", + "register": "edx", + "bit": 10 + }, + { + "name": "syscall", + "register": "edx", + "bit": 11 + }, + { + "name": "mtrr", + "register": "edx", + "bit": 12 + }, + { + "name": "pge", + "register": "edx", + "bit": 13 + }, + { + "name": "mca", + "register": "edx", + "bit": 14 + }, + { + "name": "cmov", + "register": "edx", + "bit": 15 + }, + { + "name": "pat", + "register": "edx", + "bit": 16 + }, + { + "name": "pse36", + "register": "edx", + "bit": 17 + }, + { + "name": "mp", + "register": "edx", + "bit": 19 + }, + { + "name": "nx", + "register": "edx", + "bit": 20 + }, + { + "name": "mmxext", + "register": "edx", + "bit": 22 + }, + { + "name": "mmx", + "register": "edx", + "bit": 23 + }, + { + "name": "fxsr", + "register": "edx", + "bit": 24 + }, + { + "name": "fxsr_opt", + "register": "edx", + "bit": 25 + }, + { + "name": "pdpe1gp", + "register": "edx", + "bit": 26 + }, + { + "name": "rdtscp", + "register": "edx", + "bit": 27 + }, + { + "name": "lm", + "register": "edx", + "bit": 29 + }, + { + "name": "3dnowext", + "register": "edx", + "bit": 30 + }, + { + "name": "3dnow", + "register": "edx", + "bit": 31 + }, + { + "name": "lahf_lm", + "register": "ecx", + "bit": 0 + }, + { + "name": "cmp_legacy", + "register": "ecx", + "bit": 1 + }, + { + "name": "svm", + "register": "ecx", + "bit": 2 + }, + { + "name": "extapic", + "register": "ecx", + "bit": 3 + }, + { + "name": "cr8_legacy", + "register": "ecx", + "bit": 4 + }, + { + "name": "abm", + "register": "ecx", + "bit": 5 + }, + { + "name": "sse4a", + "register": "ecx", + "bit": 6 + }, + { + "name": "misalignsse", + "register": "ecx", + "bit": 7 + }, + { + "name": "3dnowprefetch", + "register": "ecx", + "bit": 8 + }, + { + "name": "osvw", + "register": "ecx", + "bit": 9 + }, + { + "name": "ibs", + "register": "ecx", + "bit": 10 + }, + { + "name": "xop", + "register": "ecx", + "bit": 11 + }, + { + "name": "skinit", + "register": "ecx", + "bit": 12 + }, + { + "name": "wdt", + "register": "ecx", + "bit": 13 + }, + { + "name": "lwp", + "register": "ecx", + "bit": 15 + }, + { + "name": "fma4", + "register": "ecx", + "bit": 16 + }, + { + "name": "tce", + "register": "ecx", + "bit": 17 + }, + { + "name": "nodeid_msr", + "register": "ecx", + "bit": 19 + }, + { + "name": "tbm", + "register": "ecx", + "bit": 21 + }, + { + "name": "topoext", + "register": "ecx", + "bit": 22 + }, + { + "name": "perfctr_core", + "register": "ecx", + "bit": 23 + }, + { + "name": "perfctr_nb", + "register": "ecx", + "bit": 24 + }, + { + "name": "dbx", + "register": "ecx", + "bit": 26 + }, + { + "name": "perftsc", + "register": "ecx", + "bit": 27 + }, + { + "name": "pci_l2i", + "register": "ecx", + "bit": 28 + }, + { + "name": "mwaitx", + "register": "ecx", + "bit": 29 + } + ] + } + ] +} diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid_schema.json b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8dc5b982eac66a8230a107962882a11d4982240a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid_schema.json @@ -0,0 +1,134 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Schema for microarchitecture definitions and feature aliases", + "type": "object", + "additionalProperties": false, + "properties": { + "vendor": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + } + } + }, + "highest_extension_support": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + } + } + }, + "flags": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + }, + "bits": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "register": { + "type": "string" + }, + "bit": { + "type": "integer" + } + } + } + } + } + } + }, + "extension-flags": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + }, + "bits": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "register": { + "type": "string" + }, + "bit": { + "type": "integer" + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures.json b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures.json new file mode 100644 index 0000000000000000000000000000000000000000..9275422ef4da53a21daf0b774f9d6ecb622c1d3e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures.json @@ -0,0 +1,3644 @@ +{ + "microarchitectures": { + "x86": { + "from": [], + "vendor": "generic", + "features": [] + }, + "i686": { + "from": ["x86"], + "vendor": "GenuineIntel", + "features": [] + }, + "pentium2": { + "from": ["i686"], + "vendor": "GenuineIntel", + "features": [ + "mmx" + ] + }, + "pentium3": { + "from": ["pentium2"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse" + ] + }, + "pentium4": { + "from": ["pentium3"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2" + ] + }, + "prescott": { + "from": ["pentium4"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "sse3" + ] + }, + "x86_64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.2.0:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": ":4.1.2", + "name": "x86-64", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name}" + } + ], + "clang": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "intel": [ + { + "versions": ":", + "name": "pentium4", + "flags": "-march={name} -mtune=generic" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc": [] + } + }, + "x86_64_v2": { + "from": ["x86_64"], + "vendor": "generic", + "features": [ + "cx16", + "lahf_lm", + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt" + ], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "4.6:11.0", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "3.9:11.1", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "corei7", + "flags": "-march={name} -mtune=generic -mpopcnt" + } + ], + "oneapi": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc": [] + } + }, + "x86_64_v3": { + "from": ["x86_64_v2"], + "vendor": "generic", + "features": [ + "cx16", + "lahf_lm", + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "avx", + "avx2", + "bmi1", + "bmi2", + "f16c", + "fma", + "abm", + "movbe", + "xsave" + ], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "4.8:11.0", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "3.9:11.1", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "core-avx2", + "flags": "-march={name} -mtune={name} -fma -mf16c" + } + ], + "oneapi": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc" : [ + { + "versions": ":", + "name": "px", + "flags": "-tp {name} -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mxsave" + } + ] + } + }, + "x86_64_v4": { + "from": ["x86_64_v3"], + "vendor": "generic", + "features": [ + "cx16", + "lahf_lm", + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "avx", + "avx2", + "bmi1", + "bmi2", + "f16c", + "fma", + "abm", + "movbe", + "xsave", + "avx512f", + "avx512bw", + "avx512cd", + "avx512dq", + "avx512vl" + ], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "6.0:11.0", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "3.9:11.1", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "px", + "flags": "-tp {name} -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ] + } + }, + "nocona": { + "from": ["x86_64"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "sse3" + ], + "compilers": { + "gcc": [ + { + "versions": "4.0.4:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "core2": { + "from": ["nocona"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3" + ], + "compilers": { + "gcc": [ + { + "versions": "4.3.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "nehalem": { + "from": ["core2", "x86_64_v2"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.6:4.8.5", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "westmere": { + "from": ["nehalem"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "sandybridge": { + "from": ["westmere"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.6:4.8.5", + "name": "corei7-avx", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:17.9.0", + "name": "corei7-avx", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "ivybridge": { + "from": ["sandybridge"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.6:4.8.5", + "name": "core-avx-i", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:17.9.0", + "name": "core-avx-i", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "haswell": { + "from": ["ivybridge", "x86_64_v3"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.8:4.8.5", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:17.9.0", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "broadwell": { + "from": ["haswell"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "haswell", + "flags": "-tp {name}" + } + ] + } + }, + "skylake": { + "from": ["broadwell"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt" + ], + "compilers": { + "gcc": [ + { + "versions": "6.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "haswell", + "flags": "-tp {name}" + } + ] + } + }, + "mic_knl": { + "from": ["broadwell"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "avx2", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "avx512f", + "avx512pf", + "avx512er", + "avx512cd" + ], + "compilers": { + "gcc": [ + { + "versions": "5.1:", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "knl", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:2021.2", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":2021.2", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":2021.2", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ] + } + }, + "skylake_avx512": { + "from": ["skylake", "x86_64_v4"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "clwb", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd" + ], + "compilers": { + "gcc": [ + { + "name": "skylake-avx512", + "versions": "6.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "cannonlake": { + "from": ["skylake"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512vbmi", + "avx512ifma", + "sha" + ], + "compilers": { + "gcc": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "cascadelake": { + "from": ["skylake_avx512"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "clwb", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512_vnni" + ], + "compilers": { + "gcc": [ + { + "versions": "9.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "11.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "19.0.1:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "icelake": { + "from": [ + "cascadelake", + "cannonlake" + ], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512vbmi", + "avx512ifma", + "sha_ni", + "clwb", + "rdpid", + "gfni", + "avx512_vbmi2", + "avx512_vpopcntdq", + "avx512_bitalg", + "avx512_vnni", + "vpclmulqdq", + "vaes" + ], + "compilers": { + "gcc": [ + { + "name": "icelake-client", + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "7.0:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "6.0:6.9", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "10.0.1:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "10.0.0:10.0.99", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "sapphirerapids": { + "from": [ + "icelake" + ], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512vbmi", + "avx512ifma", + "sha_ni", + "clwb", + "rdpid", + "gfni", + "avx512_vbmi2", + "avx512_vpopcntdq", + "avx512_bitalg", + "avx512_vnni", + "vpclmulqdq", + "vaes", + "avx512_bf16", + "cldemote", + "movdir64b", + "movdiri", + "serialize", + "waitpkg" + ], + "compilers": { + "gcc": [ + { + "versions": "11.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "12.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "2021.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": "2021.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": "2021.2:", + "flags": "-march={name} -mtune={name}" + } + ] + } + }, + "k10": { + "from": ["x86_64"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "cx16", + "3dnow", + "3dnowext" + ], + "compilers": { + "gcc": [ + { + "name": "amdfam10", + "versions": "4.3:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "amdfam10", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "amdfam10", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse2" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse2" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse2" + } + ], + "nvhpc": [] + } + }, + "bulldozer": { + "from": ["x86_64_v2"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2" + ], + "compilers": { + "gcc": [ + { + "name": "bdver1", + "versions": "4.7:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver1", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver1", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "piledriver": { + "from": ["bulldozer"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2", + "bmi1", + "f16c", + "fma", + "tbm" + ], + "compilers": { + "gcc": [ + { + "name": "bdver2", + "versions": "4.7:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver2", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver2", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "steamroller": { + "from": ["piledriver"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2", + "bmi1", + "f16c", + "fma", + "fsgsbase", + "tbm" + ], + "compilers": { + "gcc": [ + { + "name": "bdver3", + "versions": "4.8:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver3", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver3", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse4.2" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse4.2" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse4.2" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "piledriver", + "flags": "-tp {name}" + } + ] + } + }, + "excavator": { + "from": ["steamroller", "x86_64_v3"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2", + "bmi1", + "f16c", + "fma", + "fsgsbase", + "bmi2", + "avx2", + "movbe", + "tbm" + ], + "compilers": { + "gcc": [ + { + "name": "bdver4", + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver4", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver4", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "piledriver", + "flags": "-tp {name}" + } + ] + } + }, + "zen": { + "from": ["x86_64_v3"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt" + ], + "compilers": { + "gcc": [ + { + "name": "znver1", + "versions": "6.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "4.0:", + "name": "znver1", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "znver1", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "zen2": { + "from": ["zen"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt", + "clwb" + ], + "compilers": { + "gcc": [ + { + "name": "znver2", + "versions": "9.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "9.0:", + "name": "znver2", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "znver2", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": "20.5:", + "flags": "-tp {name}" + } + ] + } + }, + "zen3": { + "from": ["zen2"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt", + "clwb", + "vaes", + "vpclmulqdq", + "pku" + ], + "compilers": { + "gcc": [ + { + "versions": "10.3:", + "name": "znver3", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "znver3", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "3.0:", + "name": "znver3", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": "21.11:", + "flags": "-tp {name}" + } + ] + } + }, + "zen4": { + "from": ["zen3", "x86_64_v4"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt", + "clwb", + "vaes", + "vpclmulqdq", + "pku", + "gfni", + "flush_l1d", + "avx512f", + "avx512dq", + "avx512ifma", + "avx512cd", + "avx512bw", + "avx512vl", + "avx512_bf16", + "avx512vbmi", + "avx512_vbmi2", + "avx512_vnni", + "avx512_bitalg", + "avx512_vpopcntdq" + ], + "compilers": { + "gcc": [ + { + "versions": "10.3:12.2", + "name": "znver3", + "flags": "-march={name} -mtune={name} -mavx512f -mavx512dq -mavx512ifma -mavx512cd -mavx512bw -mavx512vl -mavx512vbmi -mavx512vbmi2 -mavx512vnni -mavx512bitalg" + }, + { + "versions": "12.3:", + "name": "znver4", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "12.0:15.9", + "name": "znver3", + "flags": "-march={name} -mtune={name} -mavx512f -mavx512dq -mavx512ifma -mavx512cd -mavx512bw -mavx512vl -mavx512vbmi -mavx512vbmi2 -mavx512vnni -mavx512bitalg" + }, + { + "versions": "16.0:", + "name": "znver4", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "3.0:3.9", + "name": "znver3", + "flags": "-march={name} -mtune={name} -mavx512f -mavx512dq -mavx512ifma -mavx512cd -mavx512bw -mavx512vl -mavx512vbmi -mavx512vbmi2 -mavx512vnni -mavx512bitalg", + "warnings": "Zen4 processors are not fully supported by AOCC versions < 4.0. For optimal performance please upgrade to a newer version of AOCC" + }, + { + "versions": "4.0:", + "name": "znver4", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": "21.11:23.8", + "name": "zen3", + "flags": "-tp {name}", + "warnings": "zen4 is not fully supported by nvhpc versions < 23.9, falling back to zen3" + }, + { + "versions": "23.9:", + "flags": "-tp {name}" + } + ] + } + }, + "zen5": { + "from": ["zen4"], + "vendor": "AuthenticAMD", + "features": [ + "abm", + "aes", + "avx", + "avx2", + "avx512_bf16", + "avx512_bitalg", + "avx512bw", + "avx512cd", + "avx512dq", + "avx512f", + "avx512ifma", + "avx512vbmi", + "avx512_vbmi2", + "avx512vl", + "avx512_vnni", + "avx512_vp2intersect", + "avx512_vpopcntdq", + "avx_vnni", + "bmi1", + "bmi2", + "clflushopt", + "clwb", + "clzero", + "cppc", + "cx16", + "f16c", + "flush_l1d", + "fma", + "fsgsbase", + "gfni", + "ibrs_enhanced", + "mmx", + "movbe", + "movdir64b", + "movdiri", + "pclmulqdq", + "popcnt", + "rdseed", + "sse", + "sse2", + "sse4_1", + "sse4_2", + "sse4a", + "ssse3", + "tsc_adjust", + "vaes", + "vpclmulqdq", + "xsavec", + "xsaveopt" + ], + "compilers": { + "gcc": [ + { + "versions": "14.1:", + "name": "znver5", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "5.0:", + "name": "znver5", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "19.1:", + "name": "znver5", + "flags": "-march={name} -mtune={name}" + } + ] + } + }, + "ppc64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "name": "powerpc64", + "versions": ":", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power7": { + "from": ["ppc64"], + "vendor": "IBM", + "generation": 7, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.4:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power8": { + "from": ["power7"], + "vendor": "IBM", + "generation": 8, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-mcpu={name} -mtune={name}" + }, + { + "versions": "4.8:4.8.5", + "warnings": "Using GCC 4.8 to optimize for Power 8 might not work if you are not on Red Hat Enterprise Linux 7, where a custom backport of the feature has been done. Upstream support from GCC starts in version 4.9", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power9": { + "from": ["power8"], + "vendor": "IBM", + "generation": 9, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "6.0:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power10": { + "from": ["power9"], + "vendor": "IBM", + "generation": 10, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "11.0:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "ppc64le": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "name": "powerpc64le", + "versions": "4.8:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "power8le": { + "from": ["ppc64le"], + "vendor": "IBM", + "generation": 8, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "name": "power8", + "flags": "-mcpu={name} -mtune={name}" + }, + { + "versions": "4.8:4.8.5", + "warnings": "Using GCC 4.8 to optimize for Power 8 might not work if you are not on Red Hat Enterprise Linux 7, where a custom backport of the feature has been done. Upstream support from GCC starts in version 4.9", + "name": "power8", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "family": "ppc64le", + "name": "power8", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "pwr8", + "flags": "-tp {name}" + } + ] + } + }, + "power9le": { + "from": ["power8le"], + "vendor": "IBM", + "generation": 9, + "features": [], + "compilers": { + "gcc": [ + { + "name": "power9", + "versions": "6.0:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "family": "ppc64le", + "name": "power9", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "pwr9", + "flags": "-tp {name}" + } + ] + } + }, + "power10le": { + "from": ["power9le"], + "vendor": "IBM", + "generation": 10, + "features": [], + "compilers": { + "gcc": [ + { + "name": "power10", + "versions": "11.1:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "11.0:", + "family": "ppc64le", + "name": "power10", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "aarch64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.8.0:", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "nvhpc": [] + } + }, + "armv8.1a": { + "from": ["aarch64"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "5:", + "flags": "-march=armv8.1-a -mtune=generic" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-march=armv8.1-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.1-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.1-a -mtune=generic" + } + ] + } + }, + "armv8.2a": { + "from": ["armv8.1a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "6:", + "flags": "-march=armv8.2-a -mtune=generic" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-march=armv8.2-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.2-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.2-a -mtune=generic" + } + ] + } + }, + "armv8.3a": { + "from": ["armv8.2a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "6:", + "flags": "-march=armv8.3-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "6:", + "flags": "-march=armv8.3-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.3-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.3-a -mtune=generic" + } + ] + } + }, + "armv8.4a": { + "from": ["armv8.3a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "8:", + "flags": "-march=armv8.4-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "8:", + "flags": "-march=armv8.4-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.4-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.4-a -mtune=generic" + } + ] + } + }, + "armv8.5a": { + "from": ["armv8.4a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "9:", + "flags": "-march=armv8.5-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "11:", + "flags": "-march=armv8.5-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.5-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.5-a -mtune=generic" + } + ] + } + }, + "armv9.0a": { + "from": ["armv8.5a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "12:", + "flags": "-march=armv9-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "14:", + "flags": "-march=armv9-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv9-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv9-a -mtune=generic" + } + ] + } + }, + "thunderx2": { + "from": ["armv8.1a"], + "vendor": "Cavium", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "cpuid", + "asimdrdm" + ], + "compilers": { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags": "-march=armv8.1-a+crc+crypto" + }, + { + "versions": "7:", + "flags": "-mcpu=thunderx2t99" + } + ], + "clang": [ + { + "versions": "3.9:4.9", + "flags": "-march=armv8.1-a+crc+crypto" + }, + { + "versions": "5:", + "flags": "-mcpu=thunderx2t99" + } + ] + }, + "cpupart": "0x0af" + }, + "a64fx": { + "from": ["armv8.2a"], + "vendor": "Fujitsu", + "features": [ + "fp", + "asimd", + "evtstrm", + "sha1", + "sha2", + "crc32", + "atomics", + "cpuid", + "asimdrdm", + "fphp", + "asimdhp", + "fcma", + "dcpop", + "sve" + ], + "compilers": { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags": "-march=armv8.1-a+crc+crypto" + }, + { + "versions": "7:7.9", + "flags": "-march=armv8.2-a+crc+crypto+fp16" + }, + { + "versions": "8:10.2", + "flags": "-march=armv8.2-a+crc+sha2+fp16+sve -msve-vector-bits=512" + }, + { + "versions": "10.3:", + "flags": "-mcpu=a64fx -msve-vector-bits=512" + } + ], + "clang": [ + { + "versions": "3.9:4.9", + "flags": "-march=armv8.2-a+crc+sha2+fp16" + }, + { + "versions": "5:10", + "flags": "-march=armv8.2-a+crc+sha2+fp16+sve" + }, + { + "versions": "11:", + "flags": "-mcpu=a64fx" + } + ], + "arm": [ + { + "versions": "20:", + "flags": "-march=armv8.2-a+crc+crypto+fp16+sve" + } + ] + }, + "cpupart": "0x001" + }, + "cortex_a72": { + "from": ["aarch64"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "cpuid" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags" : "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags" : "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:", + "flags" : "-mcpu=cortex-a72" + } + ], + "clang" : [ + { + "versions": "3.9:", + "flags" : "-mcpu=cortex-a72" + } + ] + }, + "cpupart": "0xd08" + }, + "neoverse_n1": { + "from": ["cortex_a72", "armv8.2a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "lrcpc", + "dcpop", + "asimddp" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7:7.9", + "flags" : "-march=armv8.2-a+fp16 -mtune=cortex-a72" + }, + { + "versions": "8.0:8.0", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "8.1:8.9", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "9.0:", + "flags" : "-mcpu=neoverse-n1" + } + ], + "clang" : [ + { + "versions": "3.9:4.9", + "flags" : "-march=armv8.2-a+fp16+crc+crypto" + }, + { + "versions": "5:", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "10:", + "flags" : "-mcpu=neoverse-n1" + } + ], + "arm" : [ + { + "versions": "20:21.9", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "22:", + "flags" : "-mcpu=neoverse-n1" + } + ], + "nvhpc" : [ + { + "versions": "22.5:", + "name": "neoverse-n1", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd0c" + }, + "neoverse_v1": { + "from": ["neoverse_n1", "armv8.4a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "sve", + "asimdfhm", + "dit", + "uscat", + "ilrcpc", + "flagm", + "dcpodp", + "svei8mm", + "svebf16", + "i8mm", + "bf16", + "dgh", + "rng" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7:7.9", + "flags" : "-march=armv8.2-a+crypto+fp16 -mtune=cortex-a72" + }, + { + "versions": "8.0:8.4", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "8.5:8.9", + "flags" : "-mcpu=neoverse-v1" + }, + { + "versions": "9.0:9.3", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "9.4:9.9", + "flags" : "-mcpu=neoverse-v1" + }, + { + "versions": "10.0:10.1", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "10.2:10.2.99", + "flags" : "-mcpu=zeus" + }, + { + "versions": "10.3:", + "flags" : "-mcpu=neoverse-v1" + } + + ], + "clang" : [ + { + "versions": "3.9:4.9", + "flags" : "-march=armv8.2-a+fp16+crc+crypto" + }, + { + "versions": "5:10", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "11:", + "flags" : "-march=armv8.4-a+sve+fp16+bf16+crypto+i8mm+rng" + }, + { + "versions": "12:", + "flags" : "-mcpu=neoverse-v1" + } + ], + "arm" : [ + { + "versions": "20:21.9", + "flags" : "-march=armv8.2-a+sve+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "22:", + "flags" : "-mcpu=neoverse-v1" + } + ], + "nvhpc" : [ + { + "versions": "22.5:", + "name": "neoverse-n1", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd40" + }, + "neoverse_v2": { + "from": ["neoverse_n1", "armv9.0a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "sve", + "asimdfhm", + "uscat", + "ilrcpc", + "flagm", + "sb", + "dcpodp", + "sve2", + "flagm2", + "frint", + "svei8mm", + "svebf16", + "i8mm", + "bf16" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:5.99", + "flags": "-march=armv8-a" + }, + { + "versions": "6:6.99", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7.0:7.99", + "flags" : "-march=armv8.2-a -mtune=cortex-a72" + }, + { + "versions": "8.0:8.99", + "flags" : "-march=armv8.4-a+sve -mtune=cortex-a72" + }, + { + "versions": "9.0:9.99", + "flags" : "-march=armv8.5-a+sve -mtune=cortex-a76" + }, + { + "versions": "10.0:11.3.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16 -mtune=cortex-a77" + }, + { + "versions": "11.4:11.99", + "flags" : "-mcpu=neoverse-v2" + }, + { + "versions": "12.0:12.2.99", + "flags" : "-march=armv9-a+i8mm+bf16 -mtune=cortex-a710" + }, + { + "versions": "12.3:", + "flags" : "-mcpu=neoverse-v2" + } + ], + "clang" : [ + { + "versions": "9.0:10.99", + "flags" : "-march=armv8.5-a+sve" + }, + { + "versions": "11.0:13.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16" + }, + { + "versions": "14.0:15.99", + "flags" : "-march=armv9-a+i8mm+bf16" + }, + { + "versions": "16.0:", + "flags" : "-mcpu=neoverse-v2" + } + ], + "arm" : [ + { + "versions": "23.04.0:", + "flags" : "-mcpu=neoverse-v2" + } + ], + "nvhpc" : [ + { + "versions": "23.3:", + "name": "neoverse-v2", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd4f" + }, + "neoverse_n2": { + "from": ["neoverse_n1", "armv9.0a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "sve", + "asimdfhm", + "uscat", + "ilrcpc", + "flagm", + "sb", + "dcpodp", + "sve2", + "flagm2", + "frint", + "svei8mm", + "svebf16", + "i8mm", + "bf16" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:5.99", + "flags": "-march=armv8-a" + }, + { + "versions": "6:6.99", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7.0:7.99", + "flags" : "-march=armv8.2-a -mtune=cortex-a72" + }, + { + "versions": "8.0:8.99", + "flags" : "-march=armv8.4-a+sve -mtune=cortex-a72" + }, + { + "versions": "9.0:9.99", + "flags" : "-march=armv8.5-a+sve -mtune=cortex-a76" + }, + { + "versions": "10.0:10.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16 -mtune=cortex-a77" + }, + { + "versions": "11.0:", + "flags" : "-mcpu=neoverse-n2" + } + ], + "clang" : [ + { + "versions": "9.0:10.99", + "flags" : "-march=armv8.5-a+sve" + }, + { + "versions": "11.0:13.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16" + }, + { + "versions": "14.0:15.99", + "flags" : "-march=armv9-a+i8mm+bf16" + }, + { + "versions": "16.0:", + "flags" : "-mcpu=neoverse-n2" + } + ], + "arm" : [ + { + "versions": "23.04.0:", + "flags" : "-mcpu=neoverse-n2" + } + ], + "nvhpc" : [ + { + "versions": "23.3:", + "name": "neoverse-n1", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd49" + }, + "m1": { + "from": ["armv8.4a"], + "vendor": "Apple", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "asimdfhm", + "dit", + "uscat", + "ilrcpc", + "flagm", + "ssbs", + "sb", + "paca", + "pacg", + "dcpodp", + "flagm2", + "frint" + ], + "compilers": { + "gcc": [ + { + "versions": "8.0:", + "flags" : "-march=armv8.4-a -mtune=generic" + } + ], + "clang" : [ + { + "versions": "9.0:12.0", + "flags" : "-march=armv8.4-a" + }, + { + "versions": "13.0:", + "flags" : "-mcpu=apple-m1" + } + ], + "apple-clang": [ + { + "versions": "11.0:12.5", + "flags" : "-march=armv8.4-a" + }, + { + "versions": "13.0:", + "flags" : "-mcpu=apple-m1" + } + ] + }, + "cpupart": "0x022" + }, + "m2": { + "from": ["m1", "armv8.5a"], + "vendor": "Apple", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "asimdfhm", + "dit", + "uscat", + "ilrcpc", + "flagm", + "ssbs", + "sb", + "paca", + "pacg", + "dcpodp", + "flagm2", + "frint", + "ecv", + "bf16", + "i8mm", + "bti" + ], + "compilers": { + "gcc": [ + { + "versions": "8.0:", + "flags" : "-march=armv8.5-a -mtune=generic" + } + ], + "clang" : [ + { + "versions": "9.0:12.0", + "flags" : "-march=armv8.5-a" + }, + { + "versions": "13.0:", + "flags" : "-mcpu=apple-m1" + }, + { + "versions": "16.0:", + "flags" : "-mcpu=apple-m2" + } + ], + "apple-clang": [ + { + "versions": "11.0:12.5", + "flags" : "-march=armv8.5-a" + }, + { + "versions": "13.0:14.0.2", + "flags" : "-mcpu=apple-m1" + }, + { + "versions": "14.0.2:", + "flags" : "-mcpu=apple-m2" + } + ] + }, + "cpupart": "0x032" + }, + "arm": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "clang": [ + { + "versions": ":", + "family": "arm", + "flags": "-march={family} -mcpu=generic" + } + ] + } + }, + "ppc": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "ppcle": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "sparc": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "sparc64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "riscv64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "7.1:", + "flags" : "-march=rv64gc" + } + ], + "clang": [ + { + "versions": "9.0:", + "flags" : "-march=rv64gc" + } + ] + } + }, + "u74mc": { + "from": ["riscv64"], + "vendor": "SiFive", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "10.2:", + "flags" : "-march=rv64gc -mtune=sifive-7-series" + } + ], + "clang" : [ + { + "versions": "12.0:", + "flags" : "-march=rv64gc -mtune=sifive-7-series" + } + ] + } + } + }, + "feature_aliases": { + "sse3": { + "reason": "ssse3 is a superset of sse3 and might be the only one listed", + "any_of": [ + "ssse3" + ] + }, + "avx512": { + "reason": "avx512 indicates generic support for any of the avx512 instruction sets", + "any_of": [ + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd" + ] + }, + "altivec": { + "reason": "altivec is supported by Power PC architectures, but might not be listed in features", + "families": [ + "ppc64le", + "ppc64" + ] + }, + "vsx": { + "reason": "VSX alitvec extensions are supported by PowerISA from v2.06 (Power7+), but might not be listed in features", + "families": [ + "ppc64le", + "ppc64" + ] + }, + "fma": { + "reason": "FMA has been supported by PowerISA since Power1, but might not be listed in features", + "families": [ + "ppc64le", + "ppc64" + ] + }, + "sse4.1": { + "reason": "permits to refer to sse4_1 also as sse4.1", + "any_of": [ + "sse4_1" + ] + }, + "sse4.2": { + "reason": "permits to refer to sse4_2 also as sse4.2", + "any_of": [ + "sse4_2" + ] + }, + "neon": { + "reason": "NEON is required in all standard ARMv8 implementations", + "families": [ + "aarch64" + ] + } + }, + "conversions": { + "description": "Conversions that map some platform specific values to canonical values", + "arm_vendors": { + "0x41": "ARM", + "0x42": "Broadcom", + "0x43": "Cavium", + "0x44": "DEC", + "0x46": "Fujitsu", + "0x48": "HiSilicon", + "0x49": "Infineon Technologies AG", + "0x4d": "Motorola", + "0x4e": "Nvidia", + "0x50": "APM", + "0x51": "Qualcomm", + "0x53": "Samsung", + "0x56": "Marvell", + "0x61": "Apple", + "0x66": "Faraday", + "0x68": "HXT", + "0x69": "Intel" + }, + "darwin_flags": { + "sse4.1": "sse4_1", + "sse4.2": "sse4_2", + "avx1.0": "avx", + "clfsopt": "clflushopt", + "xsave": "xsavec xsaveopt" + } + } +} diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures_schema.json b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..085e5b95772e6a71e72afb21678cb1efe731b4d1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures_schema.json @@ -0,0 +1,113 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Schema for microarchitecture definitions and feature aliases", + "type": "object", + "additionalProperties": false, + "properties": { + "microarchitectures": { + "type": "object", + "patternProperties": { + "([\\w]*)": { + "type": "object", + "properties": { + "from": { + "$comment": "More than one parent", + "type": "array", + "items": { + "type": "string" + } + }, + "vendor": { + "type": "string" + }, + "features": { + "type": "array", + "items": { + "type": "string" + } + }, + "compilers": { + "type": "object", + "patternProperties": { + "([\\w]*)": { + "$comment": "Permit multiple entries since compilers change options across versions", + "type": "array", + "items": { + "type": "object", + "properties": { + "versions": { + "type": "string" + }, + "name": { + "type": "string" + }, + "flags": { + "type": "string" + } + }, + "required": [ + "versions", + "flags" + ] + } + } + } + }, + "cpupart": { + "type": "string" + } + }, + "required": [ + "from", + "vendor", + "features" + ] + } + } + }, + "feature_aliases": { + "type": "object", + "patternProperties": { + "([\\w]*)": { + "type": "object", + "properties": { + "reason": { + "$comment": "Comment containing the reason why an alias is there", + "type": "string" + }, + "any_of": { + "$comment": "The alias is true if any of the items is a feature of the target", + "type": "array", + "items": { + "type": "string" + } + }, + "families": { + "$comment": "The alias is true if the family of the target is in this list", + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + } + } + }, + "conversions": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "arm_vendors": { + "type": "object" + }, + "darwin_flags": { + "type": "object" + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 new file mode 100644 index 0000000000000000000000000000000000000000..39da8a49fe06920f0a9ac714612ccc625551523b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 @@ -0,0 +1,4 @@ +processor : 0 +cpu : POWER7 (architected), altivec supported +clock : 3720.000000MHz +revision : 2.1 (pvr 003f 0201) diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 new file mode 100644 index 0000000000000000000000000000000000000000..b033bcb90d939d207f6c1bec351843c4ef488634 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 @@ -0,0 +1,19 @@ +machdep.cpu.cores_per_package: 8 +machdep.cpu.core_count: 8 +machdep.cpu.logical_per_package: 8 +machdep.cpu.thread_count: 8 +machdep.cpu.brand_string: Apple processor +hw.optional.floatingpoint: 1 +hw.optional.watchpoint: 4 +hw.optional.breakpoint: 6 +hw.optional.neon: 1 +hw.optional.neon_hpfp: 1 +hw.optional.neon_fp16: 1 +hw.optional.armv8_1_atomics: 1 +hw.optional.armv8_crc32: 1 +hw.optional.armv8_2_fhm: 1 +hw.optional.armv8_2_sha512: 1 +hw.optional.armv8_2_sha3: 1 +hw.optional.amx_version: 2 +hw.optional.ucnormal_mem: 1 +hw.optional.arm64: 1 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-haswell b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-haswell new file mode 100644 index 0000000000000000000000000000000000000000..45054c567634d236bacc45274d328e42998b6ff0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-haswell @@ -0,0 +1,5 @@ +machdep.cpu.vendor: GenuineIntel +machdep.cpu.model: 70 +machdep.cpu.brand_string: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz +machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT PSE36 CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM PBE SSE3 PCLMULQDQ DTES64 MON DSCPL VMX SMX EST TM2 SSSE3 FMA CX16 TPR PDCM SSE4.1 SSE4.2 x2APIC MOVBE POPCNT AES PCID XSAVE OSXSAVE SEGLIM64 TSCTMR AVX1.0 RDRAND F16C +machdep.cpu.leaf7_features: RDWRFSGS TSC_THREAD_OFFSET BMI1 AVX2 SMEP BMI2 ERMS INVPCID FPU_CSDS MDCLEAR IBRS STIBP L1DF SSBD diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge new file mode 100644 index 0000000000000000000000000000000000000000..6a52d6c19dbe4ef8023f102d795f3f5db996ecfd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge @@ -0,0 +1,59 @@ +machdep.cpu.max_basic: 13 +machdep.cpu.max_ext: 2147483656 +machdep.cpu.vendor: GenuineIntel +machdep.cpu.brand_string: Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz +machdep.cpu.family: 6 +machdep.cpu.model: 58 +machdep.cpu.extmodel: 3 +machdep.cpu.extfamily: 0 +machdep.cpu.stepping: 9 +machdep.cpu.feature_bits: 9203919201183202303 +machdep.cpu.leaf7_feature_bits: 641 0 +machdep.cpu.leaf7_feature_bits_edx: 2617246720 +machdep.cpu.extfeature_bits: 4967106816 +machdep.cpu.signature: 198313 +machdep.cpu.brand: 0 +machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT PSE36 CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM PBE SSE3 PCLMULQDQ DTES64 MON DSCPL VMX EST TM2 SSSE3 CX16 TPR PDCM SSE4.1 SSE4.2 x2APIC POPCNT AES PCID XSAVE OSXSAVE TSCTMR AVX1.0 RDRAND F16C +machdep.cpu.leaf7_features: RDWRFSGS SMEP ERMS MDCLEAR IBRS STIBP L1DF SSBD +machdep.cpu.extfeatures: SYSCALL XD EM64T LAHF RDTSCP TSCI +machdep.cpu.logical_per_package: 16 +machdep.cpu.cores_per_package: 8 +machdep.cpu.microcode_version: 33 +machdep.cpu.processor_flag: 4 +machdep.cpu.mwait.linesize_min: 64 +machdep.cpu.mwait.linesize_max: 64 +machdep.cpu.mwait.extensions: 3 +machdep.cpu.mwait.sub_Cstates: 135456 +machdep.cpu.thermal.sensor: 1 +machdep.cpu.thermal.dynamic_acceleration: 1 +machdep.cpu.thermal.invariant_APIC_timer: 1 +machdep.cpu.thermal.thresholds: 2 +machdep.cpu.thermal.ACNT_MCNT: 1 +machdep.cpu.thermal.core_power_limits: 1 +machdep.cpu.thermal.fine_grain_clock_mod: 1 +machdep.cpu.thermal.package_thermal_intr: 1 +machdep.cpu.thermal.hardware_feedback: 0 +machdep.cpu.thermal.energy_policy: 0 +machdep.cpu.xsave.extended_state: 7 832 832 0 +machdep.cpu.xsave.extended_state1: 1 0 0 0 +machdep.cpu.arch_perf.version: 3 +machdep.cpu.arch_perf.number: 4 +machdep.cpu.arch_perf.width: 48 +machdep.cpu.arch_perf.events_number: 7 +machdep.cpu.arch_perf.events: 0 +machdep.cpu.arch_perf.fixed_number: 3 +machdep.cpu.arch_perf.fixed_width: 48 +machdep.cpu.cache.linesize: 64 +machdep.cpu.cache.L2_associativity: 8 +machdep.cpu.cache.size: 256 +machdep.cpu.tlb.inst.small: 64 +machdep.cpu.tlb.inst.large: 8 +machdep.cpu.tlb.data.small: 64 +machdep.cpu.tlb.data.large: 32 +machdep.cpu.tlb.shared: 512 +machdep.cpu.address_bits.physical: 36 +machdep.cpu.address_bits.virtual: 48 +machdep.cpu.core_count: 2 +machdep.cpu.thread_count: 4 +machdep.cpu.tsc_ccc.numerator: 0 +machdep.cpu.tsc_ccc.denominator: 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-skylake b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-skylake new file mode 100644 index 0000000000000000000000000000000000000000..67dc28a966fc4a8f83fc1d652c78217ed7f773ee --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-skylake @@ -0,0 +1,5 @@ +machdep.cpu.vendor: GenuineIntel +machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT PSE36 CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM PBE SSE3 PCLMULQDQ DTES64 MON DSCPL VMX EST TM2 SSSE3 FMA CX16 TPR PDCM SSE4.1 SSE4.2 x2APIC MOVBE POPCNT AES PCID XSAVE OSXSAVE SEGLIM64 TSCTMR AVX1.0 RDRAND F16C +machdep.cpu.leaf7_features: RDWRFSGS TSC_THREAD_OFFSET SGX BMI1 HLE AVX2 SMEP BMI2 ERMS INVPCID RTM FPU_CSDS MPX RDSEED ADX SMAP CLFSOPT IPT MDCLEAR TSXFA IBRS STIBP L1DF SSBD +machdep.cpu.model: 94 +machdep.cpu.brand_string: Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m1 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m1 new file mode 100644 index 0000000000000000000000000000000000000000..de801d480b7694b52927e1a5e0c25bd436f5e2d9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m1 @@ -0,0 +1,117 @@ +hw.ncpu: 8 +hw.byteorder: 1234 +hw.memsize: 17179869184 +hw.activecpu: 8 +hw.features.allows_security_research: 0 +hw.optional.arm.FEAT_FlagM: 1 +hw.optional.arm.FEAT_FlagM2: 1 +hw.optional.arm.FEAT_FHM: 1 +hw.optional.arm.FEAT_DotProd: 1 +hw.optional.arm.FEAT_SHA3: 1 +hw.optional.arm.FEAT_RDM: 1 +hw.optional.arm.FEAT_LSE: 1 +hw.optional.arm.FEAT_SHA256: 1 +hw.optional.arm.FEAT_SHA512: 1 +hw.optional.arm.FEAT_SHA1: 1 +hw.optional.arm.FEAT_AES: 1 +hw.optional.arm.FEAT_PMULL: 1 +hw.optional.arm.FEAT_SPECRES: 0 +hw.optional.arm.FEAT_SB: 1 +hw.optional.arm.FEAT_FRINTTS: 1 +hw.optional.arm.FEAT_LRCPC: 1 +hw.optional.arm.FEAT_LRCPC2: 1 +hw.optional.arm.FEAT_FCMA: 1 +hw.optional.arm.FEAT_JSCVT: 1 +hw.optional.arm.FEAT_PAuth: 1 +hw.optional.arm.FEAT_PAuth2: 0 +hw.optional.arm.FEAT_FPAC: 0 +hw.optional.arm.FEAT_DPB: 1 +hw.optional.arm.FEAT_DPB2: 1 +hw.optional.arm.FEAT_BF16: 0 +hw.optional.arm.FEAT_I8MM: 0 +hw.optional.arm.FEAT_ECV: 1 +hw.optional.arm.FEAT_LSE2: 1 +hw.optional.arm.FEAT_CSV2: 1 +hw.optional.arm.FEAT_CSV3: 1 +hw.optional.arm.FEAT_FP16: 1 +hw.optional.arm.FEAT_SSBS: 1 +hw.optional.arm.FEAT_BTI: 0 +hw.optional.floatingpoint: 1 +hw.optional.neon: 1 +hw.optional.neon_hpfp: 1 +hw.optional.neon_fp16: 1 +hw.optional.armv8_1_atomics: 1 +hw.optional.armv8_2_fhm: 1 +hw.optional.armv8_2_sha512: 1 +hw.optional.armv8_2_sha3: 1 +hw.optional.armv8_3_compnum: 1 +hw.optional.watchpoint: 4 +hw.optional.breakpoint: 6 +hw.optional.armv8_crc32: 1 +hw.optional.armv8_gpi: 1 +hw.optional.AdvSIMD: 1 +hw.optional.AdvSIMD_HPFPCvt: 1 +hw.optional.ucnormal_mem: 1 +hw.optional.arm64: 1 +hw.perflevel0.physicalcpu: 6 +hw.perflevel0.physicalcpu_max: 6 +hw.perflevel0.logicalcpu: 6 +hw.perflevel0.logicalcpu_max: 6 +hw.perflevel0.l1icachesize: 196608 +hw.perflevel0.l1dcachesize: 131072 +hw.perflevel0.l2cachesize: 12582912 +hw.perflevel0.cpusperl2: 3 +hw.perflevel1.physicalcpu: 2 +hw.perflevel1.physicalcpu_max: 2 +hw.perflevel1.logicalcpu: 2 +hw.perflevel1.logicalcpu_max: 2 +hw.perflevel1.l1icachesize: 131072 +hw.perflevel1.l1dcachesize: 65536 +hw.perflevel1.l2cachesize: 4194304 +hw.perflevel1.cpusperl2: 2 +hw.physicalcpu: 8 +hw.physicalcpu_max: 8 +hw.logicalcpu: 8 +hw.logicalcpu_max: 8 +hw.cputype: 16777228 +hw.cpusubtype: 2 +hw.cpu64bit_capable: 1 +hw.cpufamily: 458787763 +hw.cpusubfamily: 4 +hw.cacheconfig: 8 1 2 0 0 0 0 0 0 0 +hw.cachesize: 3443720192 65536 4194304 0 0 0 0 0 0 0 +hw.pagesize: 16384 +hw.pagesize32: 16384 +hw.cachelinesize: 128 +hw.l1icachesize: 131072 +hw.l1dcachesize: 65536 +hw.l2cachesize: 4194304 +hw.tbfrequency: 24000000 +hw.packages: 1 +hw.osenvironment: +hw.ephemeral_storage: 0 +hw.use_recovery_securityd: 0 +hw.use_kernelmanagerd: 1 +hw.serialdebugmode: 0 +hw.nperflevels: 2 +hw.targettype: J314s +machdep.cpu.cores_per_package: 8 +machdep.cpu.core_count: 8 +machdep.cpu.logical_per_package: 8 +machdep.cpu.thread_count: 8 +machdep.cpu.brand_string: Apple M1 Pro +machdep.wake_abstime: 267689415132 +machdep.time_since_reset: 309271811230 +machdep.wake_conttime: 283552239 +machdep.deferred_ipi_timeout: 64000 +machdep.lck_mtx_adaptive_spin_mode: 1 +machdep.virtual_address_size: 47 +machdep.report_phy_read_delay: 0 +machdep.report_phy_write_delay: 0 +machdep.trace_phy_read_delay: 0 +machdep.trace_phy_write_delay: 0 +machdep.report_phy_read_osbt: 0 +machdep.report_phy_write_osbt: 0 +machdep.phy_read_delay_panic: 0 +machdep.phy_writedelay_panic: 0 +machdep.user_idle_level: 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m2 new file mode 100644 index 0000000000000000000000000000000000000000..757a1fb79ea15a10ff45e2b56ff6645786385e4f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m2 @@ -0,0 +1,117 @@ +hw.ncpu: 8 +hw.byteorder: 1234 +hw.memsize: 17179869184 +hw.activecpu: 8 +hw.perflevel0.physicalcpu: 4 +hw.perflevel0.physicalcpu_max: 4 +hw.perflevel0.logicalcpu: 4 +hw.perflevel0.logicalcpu_max: 4 +hw.perflevel0.l1icachesize: 196608 +hw.perflevel0.l1dcachesize: 131072 +hw.perflevel0.l2cachesize: 16777216 +hw.perflevel0.cpusperl2: 4 +hw.perflevel1.physicalcpu: 4 +hw.perflevel1.physicalcpu_max: 4 +hw.perflevel1.logicalcpu: 4 +hw.perflevel1.logicalcpu_max: 4 +hw.perflevel1.l1icachesize: 131072 +hw.perflevel1.l1dcachesize: 65536 +hw.perflevel1.l2cachesize: 4194304 +hw.perflevel1.cpusperl2: 4 +hw.optional.arm.FEAT_FlagM: 1 +hw.optional.arm.FEAT_FlagM2: 1 +hw.optional.arm.FEAT_FHM: 1 +hw.optional.arm.FEAT_DotProd: 1 +hw.optional.arm.FEAT_SHA3: 1 +hw.optional.arm.FEAT_RDM: 1 +hw.optional.arm.FEAT_LSE: 1 +hw.optional.arm.FEAT_SHA256: 1 +hw.optional.arm.FEAT_SHA512: 1 +hw.optional.arm.FEAT_SHA1: 1 +hw.optional.arm.FEAT_AES: 1 +hw.optional.arm.FEAT_PMULL: 1 +hw.optional.arm.FEAT_SPECRES: 0 +hw.optional.arm.FEAT_SB: 1 +hw.optional.arm.FEAT_FRINTTS: 1 +hw.optional.arm.FEAT_LRCPC: 1 +hw.optional.arm.FEAT_LRCPC2: 1 +hw.optional.arm.FEAT_FCMA: 1 +hw.optional.arm.FEAT_JSCVT: 1 +hw.optional.arm.FEAT_PAuth: 1 +hw.optional.arm.FEAT_PAuth2: 1 +hw.optional.arm.FEAT_FPAC: 1 +hw.optional.arm.FEAT_DPB: 1 +hw.optional.arm.FEAT_DPB2: 1 +hw.optional.arm.FEAT_BF16: 1 +hw.optional.arm.FEAT_I8MM: 1 +hw.optional.arm.FEAT_ECV: 1 +hw.optional.arm.FEAT_LSE2: 1 +hw.optional.arm.FEAT_CSV2: 1 +hw.optional.arm.FEAT_CSV3: 1 +hw.optional.arm.FEAT_FP16: 1 +hw.optional.arm.FEAT_SSBS: 1 +hw.optional.arm.FEAT_BTI: 1 +hw.optional.floatingpoint: 1 +hw.optional.neon: 1 +hw.optional.neon_hpfp: 1 +hw.optional.neon_fp16: 1 +hw.optional.armv8_1_atomics: 1 +hw.optional.armv8_2_fhm: 1 +hw.optional.armv8_2_sha512: 1 +hw.optional.armv8_2_sha3: 1 +hw.optional.armv8_3_compnum: 1 +hw.optional.watchpoint: 4 +hw.optional.breakpoint: 6 +hw.optional.armv8_crc32: 1 +hw.optional.armv8_gpi: 1 +hw.optional.AdvSIMD: 1 +hw.optional.AdvSIMD_HPFPCvt: 1 +hw.optional.ucnormal_mem: 1 +hw.optional.arm64: 1 +hw.features.allows_security_research: 0 +hw.physicalcpu: 8 +hw.physicalcpu_max: 8 +hw.logicalcpu: 8 +hw.logicalcpu_max: 8 +hw.cputype: 16777228 +hw.cpusubtype: 2 +hw.cpu64bit_capable: 1 +hw.cpufamily: -634136515 +hw.cpusubfamily: 2 +hw.cacheconfig: 8 1 4 0 0 0 0 0 0 0 +hw.cachesize: 3697410048 65536 4194304 0 0 0 0 0 0 0 +hw.pagesize: 16384 +hw.pagesize32: 16384 +hw.cachelinesize: 128 +hw.l1icachesize: 131072 +hw.l1dcachesize: 65536 +hw.l2cachesize: 4194304 +hw.tbfrequency: 24000000 +hw.packages: 1 +hw.osenvironment: +hw.ephemeral_storage: 0 +hw.use_recovery_securityd: 0 +hw.use_kernelmanagerd: 1 +hw.serialdebugmode: 0 +hw.nperflevels: 2 +hw.targettype: J413 +machdep.cpu.cores_per_package: 8 +machdep.cpu.core_count: 8 +machdep.cpu.logical_per_package: 8 +machdep.cpu.thread_count: 8 +machdep.cpu.brand_string: Apple M2 +machdep.user_idle_level: 0 +machdep.wake_abstime: 5418683402971 +machdep.time_since_reset: 6671416324 +machdep.wake_conttime: 22097060794869 +machdep.deferred_ipi_timeout: 64000 +machdep.lck_mtx_adaptive_spin_mode: 1 +machdep.virtual_address_size: 47 +machdep.report_phy_read_delay: 0 +machdep.report_phy_write_delay: 0 +machdep.trace_phy_read_delay: 0 +machdep.trace_phy_write_delay: 0 +machdep.report_phy_read_osbt: 0 +machdep.report_phy_write_osbt: 0 +machdep.phy_read_delay_panic: 0 +machdep.phy_writedelay_panic: 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72 new file mode 100644 index 0000000000000000000000000000000000000000..f500e6f8077196a8270fc88932f4fcdb46233b5b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 166.66 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1 new file mode 100644 index 0000000000000000000000000000000000000000..17f1615825d77b3aeea6fdbbb250ca22cc9598b1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 243.75 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp ssbs +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x3 +CPU part : 0xd0c +CPU revision : 1 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1 new file mode 100644 index 0000000000000000000000000000000000000000..01246f99da41a5619a3b89e51e97b8919e94996d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2100.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs paca pacg dcpodp svei8mm svebf16 i8mm bf16 dgh rng +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0xd40 +CPU revision : 1 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids new file mode 100644 index 0000000000000000000000000000000000000000..633a8457d478ddd697aaf0e547dd4636a779079b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 143 +model name : Intel(R) Xeon(R) Platinum 8488C +stepping : 8 +microcode : 0x2b000461 +cpu MHz : 3101.940 +cache size : 107520 KB +physical id : 0 +siblings : 48 +core id : 0 +cpu cores : 48 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 31 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx512_bf16 wbnoinvd ida arat avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid cldemote movdiri movdir64b md_clear serialize flush_l1d arch_capabilities +bugs : spectre_v1 spectre_v2 spec_store_bypass swapgs +bogomips : 4800.00 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m1 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m1 new file mode 100644 index 0000000000000000000000000000000000000000..11f48d1832a52a49b47aa575a2d94a4d00b787f2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 48.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp flagm2 frint +CPU implementer : 0x61 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x022 +CPU revision : 1 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m2 new file mode 100644 index 0000000000000000000000000000000000000000..93d048bec7e4ccddc5f8189dc6b81eafaddd3767 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 48.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp flagm2 frint i8mm bf16 bti ecv +CPU implementer : 0x61 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x032 +CPU revision : 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake new file mode 100644 index 0000000000000000000000000000000000000000..e409c3d07a18c826fd9c7742b3e199cccae30d8b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake @@ -0,0 +1,20 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 85 +model name : Intel(R) Xeon(R) Platinum 8260M CPU @ 2.40GHz +stepping : 7 +microcode : 0x5000024 +cpu MHz : 2400.000 +cache size : 36608 KB +physical id : 0 +siblings : 48 +core id : 0 +cpu cores : 24 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 22 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke avx512_vnni md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-power8le b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-power8le new file mode 100644 index 0000000000000000000000000000000000000000..f21ca85323dd6f47f1bc2b2ab2a1dc9ee5529e91 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-power8le @@ -0,0 +1,4 @@ +processor : 0 +cpu : POWER8NVL (raw), altivec supported +clock : 2061.000000MHz +revision : 1.0 (pvr 004c 0100) diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 new file mode 100644 index 0000000000000000000000000000000000000000..2447306bac15024241fd123c23cf013dad31b659 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 400.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics cpuid asimdrdm +CPU implementer : 0x43 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x0af +CPU revision : 1 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel6-piledriver b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel6-piledriver new file mode 100644 index 0000000000000000000000000000000000000000..599d0c6fe7a933c2e44f79dfe473c9542395732d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel6-piledriver @@ -0,0 +1,29 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 21 +model : 2 +model name : AMD FX(tm)-8350 Eight-Core Processor +stepping : 0 +microcode : 0x6000832 +cpu MHz : 4013.832 +cache size : 2048 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 4 +apicid : 16 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 tce nodeid_msr tbm topoext perfctr_core perfctr_nb arat cpb hw_pstate npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold vmmcall bmi1 +bugs : fxsave_leak sysret_ss_attrs +bogomips : 8030.15 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb eff_freq_ro + +# /proc/cpuinfo taken from https://www.redhat.com/archives/vfio-users/2015-August/msg00111.html \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-broadwell b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..427cd85bf2eaa24b98e80e26813658659b7a04a5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-broadwell @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 79 +model name : Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz +stepping : 1 +microcode : 0xb00002a +cpu MHz : 2600.000 +cache size : 35840 KB +physical id : 0 +siblings : 14 +core id : 0 +cpu cores : 14 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 20 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 invpcid_single intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local ibpb ibrs stibp dtherm arat pln pts spec_ctrl intel_stibp +bogomips : 5188.06 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-haswell b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-haswell new file mode 100644 index 0000000000000000000000000000000000000000..7bb5aa958f8b9254990bbdc31a32434b187fe067 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-haswell @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 63 +model name : Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz +stepping : 2 +microcode : 0x3c +cpu MHz : 1757.910 +cache size : 30720 KB +physical id : 0 +siblings : 12 +core id : 0 +cpu cores : 12 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 15 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb invpcid_single tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc ibpb ibrs stibp dtherm arat pln pts spec_ctrl intel_stibp +bogomips : 4987.97 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge new file mode 100644 index 0000000000000000000000000000000000000000..7d6cfe4daaed77956694e9c14bd43a3bd739d86f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 62 +model name : Intel(R) Xeon(R) CPU E5-2650 v2 @ 2.60GHz +stepping : 4 +microcode : 0x42c +cpu MHz : 1862.554 +cache size : 20480 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 8 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt ibpb ibrs stibp dtherm ida arat pln pts spec_ctrl intel_stibp +bogomips : 5200.15 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512 new file mode 100644 index 0000000000000000000000000000000000000000..e9ab1987ddab06277177db82f6a5b590b901f276 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512 @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 85 +model name : Intel(R) Xeon(R) Gold 6132 CPU @ 2.60GHz +stepping : 4 +microcode : 0x200004d +cpu MHz : 2600.000 +cache size : 19712 KB +physical id : 0 +siblings : 14 +core id : 0 +cpu cores : 14 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 22 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 invpcid_single intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local ibpb ibrs stibp dtherm ida arat pln pts spec_ctrl intel_stibp ssbd +bogomips : 5200.00 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 new file mode 100644 index 0000000000000000000000000000000000000000..d6feeccceb82f45bb868e864d0fd7aada6c61548 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 @@ -0,0 +1,26 @@ +COMMENT : Created synthetically to mimic Haswell with AES disabled from BIOS +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 63 +model name : Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz +stepping : 2 +microcode : 0x3c +cpu MHz : 1757.910 +cache size : 30720 KB +physical id : 0 +siblings : 12 +core id : 0 +cpu cores : 12 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 15 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer xsave avx f16c rdrand lahf_lm abm epb invpcid_single tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc ibpb ibrs stibp dtherm arat pln pts spec_ctrl intel_stibp +bogomips : 4987.97 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-zen b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-zen new file mode 100644 index 0000000000000000000000000000000000000000..014dec3359e30216065e7aabde5f5671bbf5a1b9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-zen @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 23 +model : 1 +model name : AMD EPYC 7301 16-Core Processor +stepping : 2 +microcode : 0x8001227 +cpu MHz : 2200.000 +cache size : 512 KB +physical id : 0 +siblings : 32 +core id : 0 +cpu cores : 16 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc art rep_good nopl nonstop_tsc extd_apicid amd_dcm aperfmperf eagerfpu pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_l2 cpb hw_pstate retpoline_amd ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca +bogomips : 4399.40 +TLB size : 2560 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 new file mode 100644 index 0000000000000000000000000000000000000000..57853e97eafcaba26d569cc96f81213e083893a3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2100.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs dcpodp svei8mm svebf16 i8mm bf16 dgh rng +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0xd40 +CPU revision : 1 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-power9 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-power9 new file mode 100644 index 0000000000000000000000000000000000000000..7e1a89b631b51a03e4eeb94783abc422e5af64f5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-power9 @@ -0,0 +1,4 @@ +processor : 0 +cpu : POWER9, altivec supported +clock : 3666.000000MHz +revision : 2.2 (pvr 004e 1202) diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2 new file mode 100644 index 0000000000000000000000000000000000000000..f47458f51374540fbe53cb5bf7d7d9b5717c341a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2100.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb dcpodp sve2 sveaes svepmull svebitperm svesha3 flagm2 frint svei8mm svebf16 i8mm bf16 dgh +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd49 +CPU revision : 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2 new file mode 100644 index 0000000000000000000000000000000000000000..cd5024170f79f726dc9ca8ee8106b8d0d23ce40d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd4f +CPU revision : 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8-a64fx b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8-a64fx new file mode 100644 index 0000000000000000000000000000000000000000..2484dbe3e77128c56eff71ab117b62b003889746 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8-a64fx @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 200.00 +Features : fp asimd evtstrm sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm fcma dcpop sve +CPU implementer : 0x46 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x001 +CPU revision : 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4 new file mode 100644 index 0000000000000000000000000000000000000000..aa1c08bd1d68596efd425aa396244116f3e5114e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4 @@ -0,0 +1,27 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 25 +model : 17 +model name : AMD EPYC 9654 96-Core Processor +stepping : 1 +microcode : 0xa10110d +cpu MHz : 2400.000 +cache size : 1024 KB +physical id : 0 +siblings : 96 +core id : 0 +cpu cores : 96 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 16 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d sme sev sev_es +bugs : sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass +bogomips : 4792.38 +TLB size : 3584 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 52 bits physical, 57 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 new file mode 100644 index 0000000000000000000000000000000000000000..31379fde97b062bf34dd0c0ad71969fbe45a6729 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 @@ -0,0 +1,27 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 26 +model : 68 +model name : AMD Ryzen 9 9950X 16-Core Processor +stepping : 0 +microcode : 0xb40401a +cpu MHz : 600.000 +cache size : 1024 KB +physical id : 0 +siblings : 32 +core id : 0 +cpu cores : 16 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 16 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx_vnni avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid bus_lock_detect movdiri movdir64b overflow_recov succor smca fsrm avx512_vp2intersect flush_l1d amd_lbr_pmc_freeze +bugs : sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass +bogomips : 8600.84 +TLB size : 192 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-k10 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-k10 new file mode 100644 index 0000000000000000000000000000000000000000..1522b17480e1137f86d1819f17ea8aba0d9bd006 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-k10 @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 16 +model : 9 +model name : AMD Opteron(tm) Processor 6136 +stepping : 1 +microcode : 0x10000d9 +cpu MHz : 800.000 +cache size : 512 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 8 +apicid : 16 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 5 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc art rep_good nopl nonstop_tsc extd_apicid amd_dcm pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt nodeid_msr hw_pstate retpoline_amd ibp_disable vmmcall npt lbrv svm_lock nrip_save pausefilter +bogomips : 4800.19 +TLB size : 1024 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm stc 100mhzsteps hwpstate diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver new file mode 100644 index 0000000000000000000000000000000000000000..4c823f6e46baab2ee6f204340e76505b3957e0b4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 21 +model : 2 +model name : AMD Opteron(tm) Processor 6320 +stepping : 0 +microcode : 0x6000852 +cpu MHz : 1400.000 +cache size : 2048 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 4 +apicid : 32 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc art rep_good nopl nonstop_tsc extd_apicid amd_dcm aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt fma4 tce nodeid_msr tbm topoext perfctr_core perfctr_nb cpb hw_pstate retpoline_amd ssbd ibpb vmmcall bmi1 arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold +bogomips : 5600.11 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb eff_freq_ro diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer new file mode 100644 index 0000000000000000000000000000000000000000..c240cfc6ce94618217d588b98a983d6da438e671 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 21 +model : 1 +model name : AMD Opteron(TM) Processor 6212 +stepping : 2 +cpu MHz : 2600.188 +cache size : 2048 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 4 +apicid : 32 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nonstop_tsc extd_apicid amd_dcm aperfmperf pni pclmulqdq monitor ssse3 cx16 sse4_1 sse4_2 popcnt aes xsave avx lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 nodeid_msr topoext perfctr_core perfctr_nb cpb ssbd retpoline ibpb npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold +bogomips : 5200.37 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver new file mode 100644 index 0000000000000000000000000000000000000000..a87afeee612e1a71e7431ab0531f8d9c7c5564d7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver @@ -0,0 +1,25 @@ +processor : 31 +vendor_id : AuthenticAMD +cpu family : 21 +model : 2 +model name : AMD Opteron(tm) Processor 6320 +stepping : 0 +cpu MHz : 2800.154 +cache size : 2048 KB +physical id : 3 +siblings : 8 +core id : 3 +cpu cores : 4 +apicid : 135 +initial apicid : 103 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nonstop_tsc extd_apicid amd_dcm aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 tce nodeid_msr tbm topoext perfctr_core perfctr_nb cpb ssbd retpoline ibpb npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold bmi1 +bogomips : 5599.22 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb eff_freq_ro diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-sifive-u74mc b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-sifive-u74mc new file mode 100644 index 0000000000000000000000000000000000000000..8c1d29002e6952044d026945e1ab81e11a01dee4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-sifive-u74mc @@ -0,0 +1,5 @@ +processor : 0 +hart : 4 +isa : rv64imafdc +mmu : sv39 +uarch : sifive,u74-mc diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..bbe287ebf14956e40272be4e06f20d26f5a00cab --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 61 +model name : Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz +stepping : 4 +microcode : 0x2d +cpu MHz : 1944.124 +cache size : 3072 KB +physical id : 0 +siblings : 4 +core id : 0 +cpu cores : 2 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 20 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap intel_pt xsaveopt dtherm ida arat pln pts md_clear flush_l1d +bugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds +bogomips : 4389.80 +clflush size : 64 +cache_alignment : 64 +address sizes : 39 bits physical, 48 bits virtual +power management: diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3 new file mode 100644 index 0000000000000000000000000000000000000000..9d1f572b7ad812cdf5fc3c00def508841d073300 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3 @@ -0,0 +1,27 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 25 +model : 33 +model name : AMD Ryzen 9 5950X 16-Core Processor +stepping : 0 +microcode : 0xa201009 +cpu MHz : 2122.858 +cache size : 512 KB +physical id : 0 +siblings : 32 +core id : 0 +cpu cores : 16 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 16 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca +bugs : sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass +bogomips : 6786.81 +TLB size : 2560 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2 new file mode 100644 index 0000000000000000000000000000000000000000..cf555d2f49d236ed990db2791763b0eff5e61357 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm uscat ilrcpc flagm ssbs sb paca pacg dcpodp sve2 flagm2 frint svei8mm svebf16 i8mm bf16 +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd49 +CPU revision : 0 \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2 new file mode 100644 index 0000000000000000000000000000000000000000..c3c8433415d7a08c60057c01a91bafceba4923e7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh bti +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd4f +CPU revision : 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 new file mode 100644 index 0000000000000000000000000000000000000000..09087ac4e8decaf91b3d38151a2b4f13cb342c63 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd4f +CPU revision : 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-power10 b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-power10 new file mode 100644 index 0000000000000000000000000000000000000000..ad8b15f9b9039f3bbd1af29e1b392e06b5f429aa --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-power10 @@ -0,0 +1,3 @@ +processor : 0 +cpu : POWER10, altivec supported +revision : 17.0 (pvr 0080 1100) \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids new file mode 100644 index 0000000000000000000000000000000000000000..c317b6b6b515c100ddebb14f31d2c3ce5aacc563 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids @@ -0,0 +1,27 @@ +processor : 2 +vendor_id : GenuineIntel +cpu family : 6 +model : 143 +model name : Intel(R) Xeon(R) Platinum 8480+ +stepping : 6 +microcode : 0x2b000181 +cpu MHz : 2000.000 +cache size : 107520 KB +physical id : 0 +siblings : 112 +core id : 2 +cpu cores : 56 +apicid : 4 +initial apicid : 4 +fpu : yes +fpu_exception : yes +cpuid level : 32 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities +vmx flags : vnmi preemption_timer posted_intr invvpid ept_x_only ept_ad ept_1gb flexpriority apicv tsc_offset vtpr mtf vapic ept vpid unrestricted_guest vapic_reg vid ple shadow_vmcs pml ept_mode_based_exec tsc_scaling usr_wait_pause +bugs : spectre_v1 spectre_v2 spec_store_bypass swapgs eibrs_pbrsb +bogomips : 4000.00 +clflush size : 64 +cache_alignment : 64 +address sizes : 52 bits physical, 57 bits virtual +power management: diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..f19f1d4a475a08736c60a6b5ff40f2a98ca420c2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell @@ -0,0 +1,10 @@ +0, 0, 20, 1970169159, 1818588270, 1231384169 +2147483648, 0, 2147483656, 0, 0, 0 +1, 0, 198356, 34605056, 2147154879, 3219913727 +7, 0, 0, 35399595, 0, 2617247232 +7, 1, 0, 0, 0, 0 +13, 1, 1, 0, 0, 0 +2147483649, 0, 0, 0, 289, 739248128 +2147483650, 0, 1702129225, 693250156, 1919894304, 1297360997 +2147483651, 0, 929636393, 808793389, 1126192432, 1075860816 +2147483652, 0, 875442720, 2051557168, 0, 0 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-icelake b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-icelake new file mode 100644 index 0000000000000000000000000000000000000000..dcc0453e4f3418e4e5c965dddd8f2fa7edf5569c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-icelake @@ -0,0 +1,10 @@ +0, 0, 20, 1970169159, 1818588270, 1231384169 +2147483648, 0, 2147483656, 0, 0, 0 +1, 0, 526017, 68159488, 2147154943, 3219913727 +7, 0, 2, 4089423851, 415268830, 4228908816 +7, 1, 0, 0, 0, 262144 +13, 1, 15, 2440, 14592, 0 +2147483649, 0, 0, 0, 289, 739248128 +2147483650, 0, 1752445233, 1852131104, 1953384736, 1378380901 +2147483651, 0, 1866670121, 1411933554, 1763715405, 825306423 +2147483652, 0, 927413560, 857751584, 1194340398, 31304 diff --git a/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/.gitignore b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c9b568f7eac5edcb35307bb793869b2c20e5ae41 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/.gitignore @@ -0,0 +1,2 @@ +*.pyc +*.swp diff --git a/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/LICENSE b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..af36480022f9ffcd2ea82399328e271788b55503 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Anders Høst + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/README.md b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c79e37d86ce7e77133dad5cae2ea6e4e02a7d0d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/README.md @@ -0,0 +1,76 @@ +cpuid.py +======== + +Now, this is silly! + +Pure Python library for accessing information about x86 processors +by querying the [CPUID](http://en.wikipedia.org/wiki/CPUID) +instruction. Well, not exactly pure Python... + +It works by allocating a small piece of virtual memory, copying +a raw x86 function to that memory, giving the memory execute +permissions and then calling the memory as a function. The injected +function executes the CPUID instruction and copies the result back +to a ctypes.Structure where is can be read by Python. + +It should work fine on both 32 and 64 bit versions of Windows and Linux +running x86 processors. Apple OS X and other BSD systems should also work, +not tested though... + + +Why? +---- +For poops and giggles. Plus, having access to a low-level feature +without having to compile a C wrapper is pretty neat. + + +Examples +-------- +Getting info with eax=0: + + import cpuid + + q = cpuid.CPUID() + eax, ebx, ecx, edx = q(0) + +Running the files: + + $ python example.py + Vendor ID : GenuineIntel + CPU name : Intel(R) Xeon(R) CPU W3550 @ 3.07GHz + + Vector instructions supported: + SSE : Yes + SSE2 : Yes + SSE3 : Yes + SSSE3 : Yes + SSE4.1 : Yes + SSE4.2 : Yes + SSE4a : -- + AVX : -- + AVX2 : -- + + $ python cpuid.py + CPUID A B C D + 00000000 0000000b 756e6547 6c65746e 49656e69 + 00000001 000106a5 00100800 009ce3bd bfebfbff + 00000002 55035a01 00f0b2e4 00000000 09ca212c + 00000003 00000000 00000000 00000000 00000000 + 00000004 00000000 00000000 00000000 00000000 + 00000005 00000040 00000040 00000003 00001120 + 00000006 00000003 00000002 00000001 00000000 + 00000007 00000000 00000000 00000000 00000000 + 00000008 00000000 00000000 00000000 00000000 + 00000009 00000000 00000000 00000000 00000000 + 0000000a 07300403 00000044 00000000 00000603 + 0000000b 00000000 00000000 00000095 00000000 + 80000000 80000008 00000000 00000000 00000000 + 80000001 00000000 00000000 00000001 28100800 + 80000002 65746e49 2952286c 6f655820 2952286e + 80000003 55504320 20202020 20202020 57202020 + 80000004 30353533 20402020 37302e33 007a4847 + 80000005 00000000 00000000 00000000 00000000 + 80000006 00000000 00000000 01006040 00000000 + 80000007 00000000 00000000 00000000 00000100 + 80000008 00003024 00000000 00000000 00000000 + diff --git a/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/cpuid.py b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/cpuid.py new file mode 100644 index 0000000000000000000000000000000000000000..79c15d16d1ab7e4149de287823e22eeaf2218e19 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/cpuid.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2024 Anders Høst +# + +from __future__ import print_function + +import platform +import os +import ctypes +from ctypes import c_uint32, c_long, c_ulong, c_size_t, c_void_p, POINTER, CFUNCTYPE + +# Posix x86_64: +# Three first call registers : RDI, RSI, RDX +# Volatile registers : RAX, RCX, RDX, RSI, RDI, R8-11 + +# Windows x86_64: +# Three first call registers : RCX, RDX, R8 +# Volatile registers : RAX, RCX, RDX, R8-11 + +# cdecl 32 bit: +# Three first call registers : Stack (%esp) +# Volatile registers : EAX, ECX, EDX + +_POSIX_64_OPC = [ + 0x53, # push %rbx + 0x89, 0xf0, # mov %esi,%eax + 0x89, 0xd1, # mov %edx,%ecx + 0x0f, 0xa2, # cpuid + 0x89, 0x07, # mov %eax,(%rdi) + 0x89, 0x5f, 0x04, # mov %ebx,0x4(%rdi) + 0x89, 0x4f, 0x08, # mov %ecx,0x8(%rdi) + 0x89, 0x57, 0x0c, # mov %edx,0xc(%rdi) + 0x5b, # pop %rbx + 0xc3 # retq +] + +_WINDOWS_64_OPC = [ + 0x53, # push %rbx + 0x89, 0xd0, # mov %edx,%eax + 0x49, 0x89, 0xc9, # mov %rcx,%r9 + 0x44, 0x89, 0xc1, # mov %r8d,%ecx + 0x0f, 0xa2, # cpuid + 0x41, 0x89, 0x01, # mov %eax,(%r9) + 0x41, 0x89, 0x59, 0x04, # mov %ebx,0x4(%r9) + 0x41, 0x89, 0x49, 0x08, # mov %ecx,0x8(%r9) + 0x41, 0x89, 0x51, 0x0c, # mov %edx,0xc(%r9) + 0x5b, # pop %rbx + 0xc3 # retq +] + +_CDECL_32_OPC = [ + 0x53, # push %ebx + 0x57, # push %edi + 0x8b, 0x7c, 0x24, 0x0c, # mov 0xc(%esp),%edi + 0x8b, 0x44, 0x24, 0x10, # mov 0x10(%esp),%eax + 0x8b, 0x4c, 0x24, 0x14, # mov 0x14(%esp),%ecx + 0x0f, 0xa2, # cpuid + 0x89, 0x07, # mov %eax,(%edi) + 0x89, 0x5f, 0x04, # mov %ebx,0x4(%edi) + 0x89, 0x4f, 0x08, # mov %ecx,0x8(%edi) + 0x89, 0x57, 0x0c, # mov %edx,0xc(%edi) + 0x5f, # pop %edi + 0x5b, # pop %ebx + 0xc3 # ret +] + +is_windows = os.name == "nt" +is_64bit = ctypes.sizeof(ctypes.c_voidp) == 8 + + +class CPUID_struct(ctypes.Structure): + _register_names = ("eax", "ebx", "ecx", "edx") + _fields_ = [(r, c_uint32) for r in _register_names] + + def __getitem__(self, item): + if item not in self._register_names: + raise KeyError(item) + return getattr(self, item) + + def __repr__(self): + return "eax=0x{:x}, ebx=0x{:x}, ecx=0x{:x}, edx=0x{:x}".format(self.eax, self.ebx, self.ecx, self.edx) + + +class CPUID(object): + def __init__(self): + if platform.machine() not in ("AMD64", "x86_64", "x86", "i686"): + raise SystemError("Only available for x86") + + if is_windows: + if is_64bit: + # VirtualAlloc seems to fail under some weird + # circumstances when ctypes.windll.kernel32 is + # used under 64 bit Python. CDLL fixes this. + self.win = ctypes.CDLL("kernel32.dll") + opc = _WINDOWS_64_OPC + else: + # Here ctypes.windll.kernel32 is needed to get the + # right DLL. Otherwise it will fail when running + # 32 bit Python on 64 bit Windows. + self.win = ctypes.windll.kernel32 + opc = _CDECL_32_OPC + else: + opc = _POSIX_64_OPC if is_64bit else _CDECL_32_OPC + + size = len(opc) + code = (ctypes.c_ubyte * size)(*opc) + + if is_windows: + self.win.VirtualAlloc.restype = c_void_p + self.win.VirtualAlloc.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong, ctypes.c_ulong] + self.addr = self.win.VirtualAlloc(None, size, 0x1000, 0x40) + if not self.addr: + raise MemoryError("Could not allocate RWX memory") + ctypes.memmove(self.addr, code, size) + else: + from mmap import ( + mmap, + MAP_PRIVATE, + MAP_ANONYMOUS, + PROT_WRITE, + PROT_READ, + PROT_EXEC, + ) + self.mm = mmap( + -1, + size, + flags=MAP_PRIVATE | MAP_ANONYMOUS, + prot=PROT_WRITE | PROT_READ | PROT_EXEC, + ) + self.mm.write(code) + self.addr = ctypes.addressof(ctypes.c_int.from_buffer(self.mm)) + + func_type = CFUNCTYPE(None, POINTER(CPUID_struct), c_uint32, c_uint32) + self.func_ptr = func_type(self.addr) + + def __call__(self, eax, ecx=0): + struct = self.registers_for(eax=eax, ecx=ecx) + return struct.eax, struct.ebx, struct.ecx, struct.edx + + def registers_for(self, eax, ecx=0): + """Calls cpuid with eax and ecx set as the input arguments, and returns a structure + containing eax, ebx, ecx, and edx. + """ + struct = CPUID_struct() + self.func_ptr(struct, eax, ecx) + return struct + + def __del__(self): + if is_windows: + self.win.VirtualFree.restype = c_long + self.win.VirtualFree.argtypes = [c_void_p, c_size_t, c_ulong] + self.win.VirtualFree(self.addr, 0, 0x8000) + else: + self.mm.close() + + + +if __name__ == "__main__": + def valid_inputs(): + cpuid = CPUID() + for eax in (0x0, 0x80000000): + highest, _, _, _ = cpuid(eax) + while eax <= highest: + regs = cpuid(eax) + yield (eax, regs) + eax += 1 + + + print(" ".join(x.ljust(8) for x in ("CPUID", "A", "B", "C", "D")).strip()) + for eax, regs in valid_inputs(): + print("%08x" % eax, " ".join("%08x" % reg for reg in regs)) diff --git a/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/example.py b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/example.py new file mode 100644 index 0000000000000000000000000000000000000000..e07e3c15215b0a9411eb1c4cb6322ecb0fbe8892 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/example.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2024 Anders Høst +# + +from __future__ import print_function + +import struct +import cpuid + + +def cpu_vendor(cpu): + _, b, c, d = cpu(0) + return struct.pack("III", b, d, c).decode("utf-8") + + +def cpu_name(cpu): + name = "".join((struct.pack("IIII", *cpu(0x80000000 + i)).decode("utf-8") + for i in range(2, 5))) + + return name.split('\x00', 1)[0] + + +def is_set(cpu, leaf, subleaf, reg_idx, bit): + """ + @param {leaf} %eax + @param {sublead} %ecx, 0 in most cases + @param {reg_idx} idx of [%eax, %ebx, %ecx, %edx], 0-based + @param {bit} bit of reg selected by {reg_idx}, 0-based + """ + + regs = cpu(leaf, subleaf) + + if (1 << bit) & regs[reg_idx]: + return "Yes" + else: + return "--" + + +if __name__ == "__main__": + cpu = cpuid.CPUID() + + print("Vendor ID : %s" % cpu_vendor(cpu)) + print("CPU name : %s" % cpu_name(cpu)) + print() + print("Vector instructions supported:") + print("SSE : %s" % is_set(cpu, 1, 0, 3, 25)) + print("SSE2 : %s" % is_set(cpu, 1, 0, 3, 26)) + print("SSE3 : %s" % is_set(cpu, 1, 0, 2, 0)) + print("SSSE3 : %s" % is_set(cpu, 1, 0, 2, 9)) + print("SSE4.1 : %s" % is_set(cpu, 1, 0, 2, 19)) + print("SSE4.2 : %s" % is_set(cpu, 1, 0, 2, 20)) + print("SSE4a : %s" % is_set(cpu, 0x80000001, 0, 2, 6)) + print("AVX : %s" % is_set(cpu, 1, 0, 2, 28)) + print("AVX2 : %s" % is_set(cpu, 7, 0, 1, 5)) + print("BMI1 : %s" % is_set(cpu, 7, 0, 1, 3)) + print("BMI2 : %s" % is_set(cpu, 7, 0, 1, 8)) + # Intel RDT CMT/MBM + print("L3 Monitoring : %s" % is_set(cpu, 0xf, 0, 3, 1)) + print("L3 Occupancy : %s" % is_set(cpu, 0xf, 1, 3, 0)) + print("L3 Total BW : %s" % is_set(cpu, 0xf, 1, 3, 1)) + print("L3 Local BW : %s" % is_set(cpu, 0xf, 1, 3, 2)) diff --git a/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/LICENSE b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6a4c9d2496f53c61c99ae7c113e6ed94b15b038c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2013, Mahmoud Hashemi + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * 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. + + * The names of the contributors may not 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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..767d124a83b059d9193e7f637a6da7d5dfe1c7ed --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/METADATA @@ -0,0 +1,134 @@ +Metadata-Version: 2.1 +Name: boltons +Version: 25.0.0 +Summary: When they're not builtins, they're boltons. +Author-email: Mahmoud Hashemi +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +Classifier: Topic :: Utilities +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Topic :: Software Development :: Libraries +Classifier: Development Status :: 5 - Production/Stable +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Project-URL: Homepage, https://github.com/mahmoud/boltons + +# Boltons + +*boltons should be builtins.* + + + + + + + + +**Boltons** is a set of over 230 BSD-licensed, pure-Python utilities +in the same spirit as — and yet conspicuously missing from — +[the standard library][stdlib], including: + + * [Atomic file saving][atomic], bolted on with [fileutils][fileutils] + * A highly-optimized [OrderedMultiDict][omd], in [dictutils][dictutils] + * *Two* types of [PriorityQueue][pq], in [queueutils][queueutils] + * [Chunked][chunked] and [windowed][windowed] iteration, in [iterutils][iterutils] + * Recursive data structure [iteration and merging][remap], with [iterutils.remap][iterutils.remap] + * Exponential backoff functionality, including jitter, through [iterutils.backoff][iterutils.backoff] + * A full-featured [TracebackInfo][tbinfo] type, for representing stack traces, + in [tbutils][tbutils] + +**[Full and extensive docs are available on Read The Docs.][rtd]** See +what's new [by checking the CHANGELOG][changelog]. + +Boltons is tested against Python 3.7-3.13, as well as PyPy3. + +[stdlib]: https://docs.python.org/3/library/index.html +[rtd]: https://boltons.readthedocs.org/en/latest/ +[changelog]: https://github.com/mahmoud/boltons/blob/master/CHANGELOG.md + +[atomic]: https://boltons.readthedocs.org/en/latest/fileutils.html#boltons.fileutils.atomic_save +[omd]: https://boltons.readthedocs.org/en/latest/dictutils.html#boltons.dictutils.OrderedMultiDict +[pq]: https://boltons.readthedocs.org/en/latest/queueutils.html#boltons.queueutils.PriorityQueue +[chunked]: https://boltons.readthedocs.org/en/latest/iterutils.html#boltons.iterutils.chunked +[windowed]: https://boltons.readthedocs.org/en/latest/iterutils.html#boltons.iterutils.windowed +[tbinfo]: https://boltons.readthedocs.org/en/latest/tbutils.html#boltons.tbutils.TracebackInfo + +[fileutils]: https://boltons.readthedocs.org/en/latest/fileutils.html#module-boltons.fileutils +[ioutils]: https://boltons.readthedocs.org/en/latest/ioutils.html#module-boltons.ioutils +[dictutils]: https://boltons.readthedocs.org/en/latest/dictutils.html#module-boltons.dictutils +[queueutils]: https://boltons.readthedocs.org/en/latest/queueutils.html#module-boltons.queueutils +[iterutils]: https://boltons.readthedocs.org/en/latest/iterutils.html#module-boltons.iterutils +[iterutils.remap]: http://boltons.readthedocs.org/en/latest/iterutils.html#boltons.iterutils.remap +[iterutils.backoff]: http://boltons.readthedocs.org/en/latest/iterutils.html#boltons.iterutils.backoff +[tbutils]: https://boltons.readthedocs.org/en/latest/tbutils.html#module-boltons.tbutils + +[remap]: http://sedimental.org/remap.html + +## Installation + +Boltons can be added to a project in a few ways. There's the obvious one: + +```bash +pip install boltons +``` +On macOS, it can also be installed via [MacPorts](https://ports.macports.org/port/py-boltons/summary): + +```bash +sudo port install py-boltons +``` + + +Then, [thanks to PyPI][boltons_pypi], dozens of boltons are just an import away: + +```python +from boltons.cacheutils import LRU +my_cache = LRU() +``` + +However, due to the nature of utilities, application developers might +want to consider other options, including vendorization of individual +modules into a project. Boltons is pure-Python and has no +dependencies. If the whole project is too big, each module is +independent, and can be copied directly into a project. See the +[Integration][integration] section of the docs for more details. + +[boltons_pypi]: https://pypi.python.org/pypi/boltons +[integration]: https://boltons.readthedocs.org/en/latest/architecture.html#integration + +## Third-party packages + +The majority of boltons strive to be "good enough" for a wide range of +basic uses, leaving advanced use cases to Python's [myriad specialized +3rd-party libraries][pypi]. In many cases the respective ``boltons`` module +will describe 3rd-party alternatives worth investigating when use +cases outgrow `boltons`. If you've found a natural "next-step" +library worth mentioning, see the next section! + +[pypi]: https://pypi.python.org/pypi + +## Gaps + +Found something missing in the standard library that should be in +`boltons`? Found something missing in `boltons`? First, take a +moment to read the very brief [architecture statement][architecture] to make +sure the functionality would be a good fit. + +Then, if you are very motivated, submit [a Pull Request][prs]. Otherwise, +submit a short feature request on [the Issues page][issues], and we will +figure something out. + +[architecture]: https://boltons.readthedocs.org/en/latest/architecture.html +[issues]: https://github.com/mahmoud/boltons/issues +[prs]: https://github.com/mahmoud/boltons/pulls + diff --git a/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8ae377f1a60e6cb00dddc492801a01447c1ebaf5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/RECORD @@ -0,0 +1,67 @@ +boltons-25.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +boltons-25.0.0.dist-info/LICENSE,sha256=wwGRJlOo2Mmeq2ISqjrqjRZOoknYrVPJQeBVigpaweM,1497 +boltons-25.0.0.dist-info/METADATA,sha256=R9BODd9Cwf6_cKkw2vT21-GNfaDtGHcbdqO672bOChs,6511 +boltons-25.0.0.dist-info/RECORD,, +boltons-25.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +boltons-25.0.0.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +boltons-25.0.0.dist-info/direct_url.json,sha256=16WJY3WPSSaHOcTbTvVQonsJsOcFwWc8tkW81mApf0M,67 +boltons/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +boltons/__pycache__/__init__.cpython-313.pyc,, +boltons/__pycache__/cacheutils.cpython-313.pyc,, +boltons/__pycache__/debugutils.cpython-313.pyc,, +boltons/__pycache__/deprutils.cpython-313.pyc,, +boltons/__pycache__/dictutils.cpython-313.pyc,, +boltons/__pycache__/easterutils.cpython-313.pyc,, +boltons/__pycache__/ecoutils.cpython-313.pyc,, +boltons/__pycache__/excutils.cpython-313.pyc,, +boltons/__pycache__/fileutils.cpython-313.pyc,, +boltons/__pycache__/formatutils.cpython-313.pyc,, +boltons/__pycache__/funcutils.cpython-313.pyc,, +boltons/__pycache__/gcutils.cpython-313.pyc,, +boltons/__pycache__/ioutils.cpython-313.pyc,, +boltons/__pycache__/iterutils.cpython-313.pyc,, +boltons/__pycache__/jsonutils.cpython-313.pyc,, +boltons/__pycache__/listutils.cpython-313.pyc,, +boltons/__pycache__/mathutils.cpython-313.pyc,, +boltons/__pycache__/mboxutils.cpython-313.pyc,, +boltons/__pycache__/namedutils.cpython-313.pyc,, +boltons/__pycache__/pathutils.cpython-313.pyc,, +boltons/__pycache__/queueutils.cpython-313.pyc,, +boltons/__pycache__/setutils.cpython-313.pyc,, +boltons/__pycache__/socketutils.cpython-313.pyc,, +boltons/__pycache__/statsutils.cpython-313.pyc,, +boltons/__pycache__/strutils.cpython-313.pyc,, +boltons/__pycache__/tableutils.cpython-313.pyc,, +boltons/__pycache__/tbutils.cpython-313.pyc,, +boltons/__pycache__/timeutils.cpython-313.pyc,, +boltons/__pycache__/typeutils.cpython-313.pyc,, +boltons/__pycache__/urlutils.cpython-313.pyc,, +boltons/cacheutils.py,sha256=yyKZj0YBPZHJayjhQb_HXeJ095PjhLPbmp21mwyCDqU,30399 +boltons/debugutils.py,sha256=5wGrghJoNqpmH36ScqmoszmBSuYCl3tHIT8K66z9ooM,10320 +boltons/deprutils.py,sha256=2PLA_c6dgnZGYSfwk3ceGgqIRLzRvZLmiA8w0nguAVE,2478 +boltons/dictutils.py,sha256=q1TgCuN1tkzaqL-o2j36o3kK60DOBxcYi-l7GZwy_rE,37642 +boltons/easterutils.py,sha256=G_xungVgZomrQIewBYXBg_9PzE60pCP5vhU6C-aBjUA,1798 +boltons/ecoutils.py,sha256=OKbC8EXSisBsjZuXEYW9i7kZbPhPobnxbMH2cwsSLZ8,14036 +boltons/excutils.py,sha256=ai7d0m9G29zu2hJb0gN51S_8mKlB_oZ-NDTRe5MRmVc,8972 +boltons/fileutils.py,sha256=PPZeBOrttj1x5aS_5pdBlIAq4gNDnP2PP4fygH_HMfw,25486 +boltons/formatutils.py,sha256=FceWPVyXsR7HpBnp5K7HwgynZbz3ATBlEMnFfH6usaQ,12728 +boltons/funcutils.py,sha256=VNgmEyqXlr5KrfDDDj5ipY1h5MWnpfaZOiuVnQu7A6A,36840 +boltons/gcutils.py,sha256=6CoyCTVgwUu4KYUyaBozONLsb0jSDM8vGkSW3Wehf5c,6229 +boltons/ioutils.py,sha256=NnJ-UDp0g9H5Hvx82DflAtxLVg4b_19_nmbNoJQhtrw,17991 +boltons/iterutils.py,sha256=Ip8Pdnqjyp-8CwV91xkRcIFb_7Q1mdOik6JGvVp1r7Y,57562 +boltons/jsonutils.py,sha256=9xh2qX6BjTmIsyls8qEXiNBRPPJR8mn463_UKqtZEJQ,9864 +boltons/listutils.py,sha256=qmgBY8s0EpwI2J4ja1Xn1b5hzDIaSFZ9nQgLf_Yz0RA,12088 +boltons/mathutils.py,sha256=KY-A0nLdaVEKPG7VDmrXbyisXp-SrsCquBMi98iDaaQ,7941 +boltons/mboxutils.py,sha256=QmtSEfezzm7p0cgNeUtW2VRENYZbSKAW0ZVc0KHgMg0,5938 +boltons/namedutils.py,sha256=E_EnM4b1aVxHQJnPIvzADc_MzaNxnh_zDfihOMPc35Y,14957 +boltons/pathutils.py,sha256=ZnpLtG7Xn2avg7B_rEGfP5FXbC5-1AThHyjNaLRkX70,6497 +boltons/queueutils.py,sha256=pg8E9fJ4A0Kcennz9R-bKGy6O9mX8SIWHyUsZsoEmbs,7650 +boltons/setutils.py,sha256=bcPJGyw7ww0xnWKAOluhrDJgIvznsk40AtRVyJfzxHg,33482 +boltons/socketutils.py,sha256=stXaLVjdPQXBQVOoPzbako_mKFpKRIUMLquYd8GVmtw,29900 +boltons/statsutils.py,sha256=z9bdX-cnxLFovu7q8f-XNuc90ZUDf8jRrQPBBtFXl0U,29923 +boltons/strutils.py,sha256=qUU6Hq-oA3kp_xL6NJb66-VRFMViUYZmjSOFk7jlE4k,43592 +boltons/tableutils.py,sha256=AERJEZMfZA0AlxDPvagT8wtoObgtPWoohgob9aRyJn4,21922 +boltons/tbutils.py,sha256=QxTvWB-l60cpTTHcU0xyzPmGOvSRppMk-I3mtwPWRlI,30474 +boltons/timeutils.py,sha256=_e_iKuOUZmuVGV5bKQyZac21zpecycN4Bc78wCq-LfU,20308 +boltons/typeutils.py,sha256=TaKybXE4bukBDftSEE5GHsukhrpVRKjPUNnibNNOnAk,5814 +boltons/urlutils.py,sha256=jAs0TEyj_Zr5S26x4NmDbkpPbx5EaLzPDs50e7rVSY4,57489 diff --git a/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..3b5e64b5e6c4a210201d1676a891fd57b15cda99 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.9.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..dfef5ea31e16851edb58ddfc4257e1709e8adad1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons-25.0.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/boltons_1751383775419/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/boltons/__init__.py b/miniconda3/lib/python3.13/site-packages/boltons/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/boltons/cacheutils.py b/miniconda3/lib/python3.13/site-packages/boltons/cacheutils.py new file mode 100644 index 0000000000000000000000000000000000000000..856bf195483aafbfcdb8f6f93a168daf0c9b5857 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/cacheutils.py @@ -0,0 +1,870 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""``cacheutils`` contains consistent implementations of fundamental +cache types. Currently there are two to choose from: + + * :class:`LRI` - Least-recently inserted + * :class:`LRU` - Least-recently used + +Both caches are :class:`dict` subtypes, designed to be as +interchangeable as possible, to facilitate experimentation. A key +practice with performance enhancement with caching is ensuring that +the caching strategy is working. If the cache is constantly missing, +it is just adding more overhead and code complexity. The standard +statistics are: + + * ``hit_count`` - the number of times the queried key has been in + the cache + * ``miss_count`` - the number of times a key has been absent and/or + fetched by the cache + * ``soft_miss_count`` - the number of times a key has been absent, + but a default has been provided by the caller, as with + :meth:`dict.get` and :meth:`dict.setdefault`. Soft misses are a + subset of misses, so this number is always less than or equal to + ``miss_count``. + +Additionally, ``cacheutils`` provides :class:`ThresholdCounter`, a +cache-like bounded counter useful for online statistics collection. + +Learn more about `caching algorithms on Wikipedia +`_. + +""" + +# TODO: TimedLRI +# TODO: support 0 max_size? + + +import heapq +import weakref +import itertools +from operator import attrgetter + +try: + from threading import RLock +except Exception: + class RLock: + 'Dummy reentrant lock for builds without threads' + def __enter__(self): + pass + + def __exit__(self, exctype, excinst, exctb): + pass + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') + _KWARG_MARK = make_sentinel(var_name='_KWARG_MARK') +except ImportError: + _MISSING = object() + _KWARG_MARK = object() + +PREV, NEXT, KEY, VALUE = range(4) # names for the link fields +DEFAULT_MAX_SIZE = 128 + + +class LRI(dict): + """The ``LRI`` implements the basic *Least Recently Inserted* strategy to + caching. One could also think of this as a ``SizeLimitedDefaultDict``. + + *on_miss* is a callable that accepts the missing key (as opposed + to :class:`collections.defaultdict`'s "default_factory", which + accepts no arguments.) Also note that, like the :class:`LRI`, + the ``LRI`` is instrumented with statistics tracking. + + >>> cap_cache = LRI(max_size=2) + >>> cap_cache['a'], cap_cache['b'] = 'A', 'B' + >>> from pprint import pprint as pp + >>> pp(dict(cap_cache)) + {'a': 'A', 'b': 'B'} + >>> [cap_cache['b'] for i in range(3)][0] + 'B' + >>> cap_cache['c'] = 'C' + >>> print(cap_cache.get('a')) + None + >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count + (3, 1, 1) + """ + def __init__(self, max_size=DEFAULT_MAX_SIZE, values=None, + on_miss=None): + if max_size <= 0: + raise ValueError('expected max_size > 0, not %r' % max_size) + self.hit_count = self.miss_count = self.soft_miss_count = 0 + self.max_size = max_size + self._lock = RLock() + self._init_ll() + + if on_miss is not None and not callable(on_miss): + raise TypeError('expected on_miss to be a callable' + ' (or None), not %r' % on_miss) + self.on_miss = on_miss + + if values: + self.update(values) + + # TODO: fromkeys()? + + # linked list manipulation methods. + # + # invariants: + # 1) 'anchor' is the sentinel node in the doubly linked list. there is + # always only one, and its KEY and VALUE are both _MISSING. + # 2) the most recently accessed node comes immediately before 'anchor'. + # 3) the least recently accessed node comes immediately after 'anchor'. + def _init_ll(self): + anchor = [] + anchor[:] = [anchor, anchor, _MISSING, _MISSING] + # a link lookup table for finding linked list links in O(1) + # time. + self._link_lookup = {} + self._anchor = anchor + + def _print_ll(self): + print('***') + for (key, val) in self._get_flattened_ll(): + print(key, val) + print('***') + return + + def _get_flattened_ll(self): + flattened_list = [] + link = self._anchor + while True: + flattened_list.append((link[KEY], link[VALUE])) + link = link[NEXT] + if link is self._anchor: + break + return flattened_list + + def _get_link_and_move_to_front_of_ll(self, key): + # find what will become the newest link. this may raise a + # KeyError, which is useful to __getitem__ and __setitem__ + newest = self._link_lookup[key] + + # splice out what will become the newest link. + newest[PREV][NEXT] = newest[NEXT] + newest[NEXT][PREV] = newest[PREV] + + # move what will become the newest link immediately before + # anchor (invariant 2) + anchor = self._anchor + second_newest = anchor[PREV] + second_newest[NEXT] = anchor[PREV] = newest + newest[PREV] = second_newest + newest[NEXT] = anchor + return newest + + def _set_key_and_add_to_front_of_ll(self, key, value): + # create a new link and place it immediately before anchor + # (invariant 2). + anchor = self._anchor + second_newest = anchor[PREV] + newest = [second_newest, anchor, key, value] + second_newest[NEXT] = anchor[PREV] = newest + self._link_lookup[key] = newest + + def _set_key_and_evict_last_in_ll(self, key, value): + # the link after anchor is the oldest in the linked list + # (invariant 3). the current anchor becomes a link that holds + # the newest key, and the oldest link becomes the new anchor + # (invariant 1). now the newest link comes before anchor + # (invariant 2). no links are moved; only their keys + # and values are changed. + oldanchor = self._anchor + oldanchor[KEY] = key + oldanchor[VALUE] = value + + self._anchor = anchor = oldanchor[NEXT] + evicted = anchor[KEY] + anchor[KEY] = anchor[VALUE] = _MISSING + del self._link_lookup[evicted] + self._link_lookup[key] = oldanchor + return evicted + + def _remove_from_ll(self, key): + # splice a link out of the list and drop it from our lookup + # table. + link = self._link_lookup.pop(key) + link[PREV][NEXT] = link[NEXT] + link[NEXT][PREV] = link[PREV] + + def __setitem__(self, key, value): + with self._lock: + try: + link = self._get_link_and_move_to_front_of_ll(key) + except KeyError: + if len(self) < self.max_size: + self._set_key_and_add_to_front_of_ll(key, value) + else: + evicted = self._set_key_and_evict_last_in_ll(key, value) + super().__delitem__(evicted) + else: + link[VALUE] = value + super().__setitem__(key, value) + return + + def __getitem__(self, key): + with self._lock: + try: + link = self._link_lookup[key] + except KeyError: + self.miss_count += 1 + if not self.on_miss: + raise + ret = self[key] = self.on_miss(key) + return ret + + self.hit_count += 1 + return link[VALUE] + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + self.soft_miss_count += 1 + return default + + def __delitem__(self, key): + with self._lock: + super().__delitem__(key) + self._remove_from_ll(key) + + def pop(self, key, default=_MISSING): + # NB: hit/miss counts are bypassed for pop() + with self._lock: + try: + ret = super().pop(key) + except KeyError: + if default is _MISSING: + raise + ret = default + else: + self._remove_from_ll(key) + return ret + + def popitem(self): + with self._lock: + item = super().popitem() + self._remove_from_ll(item[0]) + return item + + def clear(self): + with self._lock: + super().clear() + self._init_ll() + + def copy(self): + return self.__class__(max_size=self.max_size, values=self) + + def setdefault(self, key, default=None): + with self._lock: + try: + return self[key] + except KeyError: + self.soft_miss_count += 1 + self[key] = default + return default + + def update(self, E, **F): + # E and F are throwback names to the dict() __doc__ + with self._lock: + if E is self: + return + setitem = self.__setitem__ + if callable(getattr(E, 'keys', None)): + for k in E.keys(): + setitem(k, E[k]) + else: + for k, v in E: + setitem(k, v) + for k in F: + setitem(k, F[k]) + return + + def __eq__(self, other): + with self._lock: + if self is other: + return True + if len(other) != len(self): + return False + if not isinstance(other, LRI): + return other == self + return super().__eq__(other) + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + cn = self.__class__.__name__ + val_map = super().__repr__() + return ('%s(max_size=%r, on_miss=%r, values=%s)' + % (cn, self.max_size, self.on_miss, val_map)) + + +class LRU(LRI): + """The ``LRU`` is :class:`dict` subtype implementation of the + *Least-Recently Used* caching strategy. + + Args: + max_size (int): Max number of items to cache. Defaults to ``128``. + values (iterable): Initial values for the cache. Defaults to ``None``. + on_miss (callable): a callable which accepts a single argument, the + key not present in the cache, and returns the value to be cached. + + >>> cap_cache = LRU(max_size=2) + >>> cap_cache['a'], cap_cache['b'] = 'A', 'B' + >>> from pprint import pprint as pp + >>> pp(dict(cap_cache)) + {'a': 'A', 'b': 'B'} + >>> [cap_cache['b'] for i in range(3)][0] + 'B' + >>> cap_cache['c'] = 'C' + >>> print(cap_cache.get('a')) + None + + This cache is also instrumented with statistics + collection. ``hit_count``, ``miss_count``, and ``soft_miss_count`` + are all integer members that can be used to introspect the + performance of the cache. ("Soft" misses are misses that did not + raise :exc:`KeyError`, e.g., ``LRU.get()`` or ``on_miss`` was used to + cache a default. + + >>> cap_cache.hit_count, cap_cache.miss_count, cap_cache.soft_miss_count + (3, 1, 1) + + Other than the size-limiting caching behavior and statistics, + ``LRU`` acts like its parent class, the built-in Python :class:`dict`. + """ + def __getitem__(self, key): + with self._lock: + try: + link = self._get_link_and_move_to_front_of_ll(key) + except KeyError: + self.miss_count += 1 + if not self.on_miss: + raise + ret = self[key] = self.on_miss(key) + return ret + + self.hit_count += 1 + return link[VALUE] + + +### Cached decorator +# Key-making technique adapted from Python 3.4's functools + +class _HashedKey(list): + """The _HashedKey guarantees that hash() will be called no more than once + per cached function invocation. + """ + __slots__ = 'hash_value' + + def __init__(self, key): + self[:] = key + self.hash_value = hash(tuple(key)) + + def __hash__(self): + return self.hash_value + + def __repr__(self): + return f'{self.__class__.__name__}({list.__repr__(self)})' + + +def make_cache_key(args, kwargs, typed=False, + kwarg_mark=_KWARG_MARK, + fasttypes=frozenset([int, str, frozenset, type(None)])): + """Make a generic key from a function's positional and keyword + arguments, suitable for use in caches. Arguments within *args* and + *kwargs* must be `hashable`_. If *typed* is ``True``, ``3`` and + ``3.0`` will be treated as separate keys. + + The key is constructed in a way that is flat as possible rather than + as a nested structure that would take more memory. + + If there is only a single argument and its data type is known to cache + its hash value, then that argument is returned without a wrapper. This + saves space and improves lookup speed. + + >>> tuple(make_cache_key(('a', 'b'), {'c': ('d')})) + ('a', 'b', _KWARG_MARK, ('c', 'd')) + + .. _hashable: https://docs.python.org/2/glossary.html#term-hashable + """ + + # key = [func_name] if func_name else [] + # key.extend(args) + key = list(args) + if kwargs: + sorted_items = sorted(kwargs.items()) + key.append(kwarg_mark) + key.extend(sorted_items) + if typed: + key.extend([type(v) for v in args]) + if kwargs: + key.extend([type(v) for k, v in sorted_items]) + elif len(key) == 1 and type(key[0]) in fasttypes: + return key[0] + return _HashedKey(key) + +# for backwards compatibility in case someone was importing it +_make_cache_key = make_cache_key + + +class CachedFunction: + """This type is used by :func:`cached`, below. Instances of this + class are used to wrap functions in caching logic. + """ + def __init__(self, func, cache, scoped=True, typed=False, key=None): + self.func = func + if callable(cache): + self.get_cache = cache + elif not (callable(getattr(cache, '__getitem__', None)) + and callable(getattr(cache, '__setitem__', None))): + raise TypeError('expected cache to be a dict-like object,' + ' or callable returning a dict-like object, not %r' + % cache) + else: + def _get_cache(): + return cache + self.get_cache = _get_cache + self.scoped = scoped + self.typed = typed + self.key_func = key or make_cache_key + + def __call__(self, *args, **kwargs): + cache = self.get_cache() + key = self.key_func(args, kwargs, typed=self.typed) + try: + ret = cache[key] + except KeyError: + ret = cache[key] = self.func(*args, **kwargs) + return ret + + def __repr__(self): + cn = self.__class__.__name__ + if self.typed or not self.scoped: + return ("%s(func=%r, scoped=%r, typed=%r)" + % (cn, self.func, self.scoped, self.typed)) + return f"{cn}(func={self.func!r})" + + +class CachedMethod: + """Similar to :class:`CachedFunction`, this type is used by + :func:`cachedmethod` to wrap methods in caching logic. + """ + def __init__(self, func, cache, scoped=True, typed=False, key=None): + self.func = func + self.__isabstractmethod__ = getattr(func, '__isabstractmethod__', False) + if isinstance(cache, str): + self.get_cache = attrgetter(cache) + elif callable(cache): + self.get_cache = cache + elif not (callable(getattr(cache, '__getitem__', None)) + and callable(getattr(cache, '__setitem__', None))): + raise TypeError('expected cache to be an attribute name,' + ' dict-like object, or callable returning' + ' a dict-like object, not %r' % cache) + else: + def _get_cache(obj): + return cache + self.get_cache = _get_cache + self.scoped = scoped + self.typed = typed + self.key_func = key or make_cache_key + self.bound_to = None + + def __get__(self, obj, objtype=None): + if obj is None: + return self + cls = self.__class__ + ret = cls(self.func, self.get_cache, typed=self.typed, + scoped=self.scoped, key=self.key_func) + ret.bound_to = obj + return ret + + def __call__(self, *args, **kwargs): + obj = args[0] if self.bound_to is None else self.bound_to + cache = self.get_cache(obj) + key_args = (self.bound_to, self.func) + args if self.scoped else args + key = self.key_func(key_args, kwargs, typed=self.typed) + try: + ret = cache[key] + except KeyError: + if self.bound_to is not None: + args = (self.bound_to,) + args + ret = cache[key] = self.func(*args, **kwargs) + return ret + + def __repr__(self): + cn = self.__class__.__name__ + args = (cn, self.func, self.scoped, self.typed) + if self.bound_to is not None: + args += (self.bound_to,) + return ('<%s func=%r scoped=%r typed=%r bound_to=%r>' % args) + return ("%s(func=%r, scoped=%r, typed=%r)" % args) + + +def cached(cache, scoped=True, typed=False, key=None): + """Cache any function with the cache object of your choosing. Note + that the function wrapped should take only `hashable`_ arguments. + + Args: + cache (Mapping): Any :class:`dict`-like object suitable for + use as a cache. Instances of the :class:`LRU` and + :class:`LRI` are good choices, but a plain :class:`dict` + can work in some cases, as well. This argument can also be + a callable which accepts no arguments and returns a mapping. + scoped (bool): Whether the function itself is part of the + cache key. ``True`` by default, different functions will + not read one another's cache entries, but can evict one + another's results. ``False`` can be useful for certain + shared cache use cases. More advanced behavior can be + produced through the *key* argument. + typed (bool): Whether to factor argument types into the cache + check. Default ``False``, setting to ``True`` causes the + cache keys for ``3`` and ``3.0`` to be considered unequal. + + >>> my_cache = LRU() + >>> @cached(my_cache) + ... def cached_lower(x): + ... return x.lower() + ... + >>> cached_lower("CaChInG's FuN AgAiN!") + "caching's fun again!" + >>> len(my_cache) + 1 + + .. _hashable: https://docs.python.org/2/glossary.html#term-hashable + + """ + def cached_func_decorator(func): + return CachedFunction(func, cache, scoped=scoped, typed=typed, key=key) + return cached_func_decorator + + +def cachedmethod(cache, scoped=True, typed=False, key=None): + """Similar to :func:`cached`, ``cachedmethod`` is used to cache + methods based on their arguments, using any :class:`dict`-like + *cache* object. + + Args: + cache (str/Mapping/callable): Can be the name of an attribute + on the instance, any Mapping/:class:`dict`-like object, or + a callable which returns a Mapping. + scoped (bool): Whether the method itself and the object it is + bound to are part of the cache keys. ``True`` by default, + different methods will not read one another's cache + results. ``False`` can be useful for certain shared cache + use cases. More advanced behavior can be produced through + the *key* arguments. + typed (bool): Whether to factor argument types into the cache + check. Default ``False``, setting to ``True`` causes the + cache keys for ``3`` and ``3.0`` to be considered unequal. + key (callable): A callable with a signature that matches + :func:`make_cache_key` that returns a tuple of hashable + values to be used as the key in the cache. + + >>> class Lowerer(object): + ... def __init__(self): + ... self.cache = LRI() + ... + ... @cachedmethod('cache') + ... def lower(self, text): + ... return text.lower() + ... + >>> lowerer = Lowerer() + >>> lowerer.lower('WOW WHO COULD GUESS CACHING COULD BE SO NEAT') + 'wow who could guess caching could be so neat' + >>> len(lowerer.cache) + 1 + + """ + def cached_method_decorator(func): + return CachedMethod(func, cache, scoped=scoped, typed=typed, key=key) + return cached_method_decorator + + +class cachedproperty: + """The ``cachedproperty`` is used similar to :class:`property`, except + that the wrapped method is only called once. This is commonly used + to implement lazy attributes. + + After the property has been accessed, the value is stored on the + instance itself, using the same name as the cachedproperty. This + allows the cache to be cleared with :func:`delattr`, or through + manipulating the object's ``__dict__``. + """ + def __init__(self, func): + self.__doc__ = getattr(func, '__doc__') + self.__isabstractmethod__ = getattr(func, '__isabstractmethod__', False) + self.func = func + + def __get__(self, obj, objtype=None): + if obj is None: + return self + value = obj.__dict__[self.func.__name__] = self.func(obj) + return value + + def __repr__(self): + cn = self.__class__.__name__ + return f'<{cn} func={self.func}>' + + +class ThresholdCounter: + """A **bounded** dict-like Mapping from keys to counts. The + ThresholdCounter automatically compacts after every (1 / + *threshold*) additions, maintaining exact counts for any keys + whose count represents at least a *threshold* ratio of the total + data. In other words, if a particular key is not present in the + ThresholdCounter, its count represents less than *threshold* of + the total data. + + >>> tc = ThresholdCounter(threshold=0.1) + >>> tc.add(1) + >>> tc.items() + [(1, 1)] + >>> tc.update([2] * 10) + >>> tc.get(1) + 0 + >>> tc.add(5) + >>> 5 in tc + True + >>> len(list(tc.elements())) + 11 + + As you can see above, the API is kept similar to + :class:`collections.Counter`. The most notable feature omissions + being that counted items cannot be set directly, uncounted, or + removed, as this would disrupt the math. + + Use the ThresholdCounter when you need best-effort long-lived + counts for dynamically-keyed data. Without a bounded datastructure + such as this one, the dynamic keys often represent a memory leak + and can impact application reliability. The ThresholdCounter's + item replacement strategy is fully deterministic and can be + thought of as *Amortized Least Relevant*. The absolute upper bound + of keys it will store is *(2/threshold)*, but realistically + *(1/threshold)* is expected for uniformly random datastreams, and + one or two orders of magnitude better for real-world data. + + This algorithm is an implementation of the Lossy Counting + algorithm described in "Approximate Frequency Counts over Data + Streams" by Manku & Motwani. Hat tip to Kurt Rose for discovery + and initial implementation. + + """ + # TODO: hit_count/miss_count? + def __init__(self, threshold=0.001): + if not 0 < threshold < 1: + raise ValueError('expected threshold between 0 and 1, not: %r' + % threshold) + + self.total = 0 + self._count_map = {} + self._threshold = threshold + self._thresh_count = int(1 / threshold) + self._cur_bucket = 1 + + @property + def threshold(self): + return self._threshold + + def add(self, key): + """Increment the count of *key* by 1, automatically adding it if it + does not exist. + + Cache compaction is triggered every *1/threshold* additions. + """ + self.total += 1 + try: + self._count_map[key][0] += 1 + except KeyError: + self._count_map[key] = [1, self._cur_bucket - 1] + + if self.total % self._thresh_count == 0: + self._count_map = {k: v for k, v in self._count_map.items() + if sum(v) > self._cur_bucket} + self._cur_bucket += 1 + return + + def elements(self): + """Return an iterator of all the common elements tracked by the + counter. Yields each key as many times as it has been seen. + """ + repeaters = itertools.starmap(itertools.repeat, self.iteritems()) + return itertools.chain.from_iterable(repeaters) + + def most_common(self, n=None): + """Get the top *n* keys and counts as tuples. If *n* is omitted, + returns all the pairs. + """ + if not n or n <= 0: + return [] + ret = sorted(self.iteritems(), key=lambda x: x[1], reverse=True) + if n is None or n >= len(ret): + return ret + return ret[:n] + + def get_common_count(self): + """Get the sum of counts for keys exceeding the configured data + threshold. + """ + return sum([count for count, _ in self._count_map.values()]) + + def get_uncommon_count(self): + """Get the sum of counts for keys that were culled because the + associated counts represented less than the configured + threshold. The long-tail counts. + """ + return self.total - self.get_common_count() + + def get_commonality(self): + """Get a float representation of the effective count accuracy. The + higher the number, the less uniform the keys being added, and + the higher accuracy and efficiency of the ThresholdCounter. + + If a stronger measure of data cardinality is required, + consider using hyperloglog. + """ + return float(self.get_common_count()) / self.total + + def __getitem__(self, key): + return self._count_map[key][0] + + def __len__(self): + return len(self._count_map) + + def __contains__(self, key): + return key in self._count_map + + def iterkeys(self): + return iter(self._count_map) + + def keys(self): + return list(self.iterkeys()) + + def itervalues(self): + count_map = self._count_map + for k in count_map: + yield count_map[k][0] + + def values(self): + return list(self.itervalues()) + + def iteritems(self): + count_map = self._count_map + for k in count_map: + yield (k, count_map[k][0]) + + def items(self): + return list(self.iteritems()) + + def get(self, key, default=0): + "Get count for *key*, defaulting to 0." + try: + return self[key] + except KeyError: + return default + + def update(self, iterable, **kwargs): + """Like dict.update() but add counts instead of replacing them, used + to add multiple items in one call. + + Source can be an iterable of keys to add, or a mapping of keys + to integer counts. + """ + if iterable is not None: + if callable(getattr(iterable, 'iteritems', None)): + for key, count in iterable.iteritems(): + for i in range(count): + self.add(key) + else: + for key in iterable: + self.add(key) + if kwargs: + self.update(kwargs) + + +class MinIDMap: + """ + Assigns arbitrary weakref-able objects the smallest possible unique + integer IDs, such that no two objects have the same ID at the same + time. + + Maps arbitrary hashable objects to IDs. + + Based on https://gist.github.com/kurtbrose/25b48114de216a5e55df + """ + def __init__(self): + self.mapping = weakref.WeakKeyDictionary() + self.ref_map = {} + self.free = [] + + def get(self, a): + try: + return self.mapping[a][0] # if object is mapped, return ID + except KeyError: + pass + + if self.free: # if there are any free IDs, use the smallest + nxt = heapq.heappop(self.free) + else: # if there are no free numbers, use the next highest ID + nxt = len(self.mapping) + ref = weakref.ref(a, self._clean) + self.mapping[a] = (nxt, ref) + self.ref_map[ref] = nxt + return nxt + + def drop(self, a): + freed, ref = self.mapping[a] + del self.mapping[a] + del self.ref_map[ref] + heapq.heappush(self.free, freed) + + def _clean(self, ref): + print(self.ref_map[ref]) + heapq.heappush(self.free, self.ref_map[ref]) + del self.ref_map[ref] + + def __contains__(self, a): + return a in self.mapping + + def __iter__(self): + return iter(self.mapping) + + def __len__(self): + return self.mapping.__len__() + + def iteritems(self): + return iter((k, self.mapping[k][0]) for k in iter(self.mapping)) + + +# end cacheutils.py diff --git a/miniconda3/lib/python3.13/site-packages/boltons/debugutils.py b/miniconda3/lib/python3.13/site-packages/boltons/debugutils.py new file mode 100644 index 0000000000000000000000000000000000000000..16d18d4b9078d8864477cbe445d142addfae7134 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/debugutils.py @@ -0,0 +1,292 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +A small set of utilities useful for debugging misbehaving +applications. Currently this focuses on ways to use :mod:`pdb`, the +built-in Python debugger. +""" + +import sys +import time +from reprlib import Repr + +try: + from .typeutils import make_sentinel + _UNSET = make_sentinel(var_name='_UNSET') +except ImportError: + _UNSET = object() + +__all__ = ['pdb_on_signal', 'pdb_on_exception', 'wrap_trace'] + + +def pdb_on_signal(signalnum=None): + """Installs a signal handler for *signalnum*, which defaults to + ``SIGINT``, or keyboard interrupt/ctrl-c. This signal handler + launches a :mod:`pdb` breakpoint. Results vary in concurrent + systems, but this technique can be useful for debugging infinite + loops, or easily getting into deep call stacks. + + Args: + signalnum (int): The signal number of the signal to handle + with pdb. Defaults to :mod:`signal.SIGINT`, see + :mod:`signal` for more information. + """ + import pdb + import signal + if not signalnum: + signalnum = signal.SIGINT + + old_handler = signal.getsignal(signalnum) + + def pdb_int_handler(sig, frame): + signal.signal(signalnum, old_handler) + pdb.set_trace() + pdb_on_signal(signalnum) # use 'u' to find your code and 'h' for help + + signal.signal(signalnum, pdb_int_handler) + return + + +def pdb_on_exception(limit=100): + """Installs a handler which, instead of exiting, attaches a + post-mortem pdb console whenever an unhandled exception is + encountered. + + Args: + limit (int): the max number of stack frames to display when + printing the traceback + + A similar effect can be achieved from the command-line using the + following command:: + + python -m pdb your_code.py + + But ``pdb_on_exception`` allows you to do this conditionally and within + your application. To restore default behavior, just do:: + + sys.excepthook = sys.__excepthook__ + """ + import pdb + import sys + import traceback + + def pdb_excepthook(exc_type, exc_val, exc_tb): + traceback.print_tb(exc_tb, limit=limit) + pdb.post_mortem(exc_tb) + + sys.excepthook = pdb_excepthook + return + +_repr_obj = Repr() +_repr_obj.maxstring = 50 +_repr_obj.maxother = 50 +brief_repr = _repr_obj.repr + + +# events: call, return, get, set, del, raise +def trace_print_hook(event, label, obj, attr_name, + args=(), kwargs={}, result=_UNSET): + fargs = (event.ljust(6), time.time(), label.rjust(10), + obj.__class__.__name__, attr_name) + if event == 'get': + tmpl = '%s %s - %s - %s.%s -> %s' + fargs += (brief_repr(result),) + elif event == 'set': + tmpl = '%s %s - %s - %s.%s = %s' + fargs += (brief_repr(args[0]),) + elif event == 'del': + tmpl = '%s %s - %s - %s.%s' + else: # call/return/raise + tmpl = '%s %s - %s - %s.%s(%s)' + fargs += (', '.join([brief_repr(a) for a in args]),) + if kwargs: + tmpl = '%s %s - %s - %s.%s(%s, %s)' + fargs += (', '.join([f'{k}={brief_repr(v)}' + for k, v in kwargs.items()]),) + if result is not _UNSET: + tmpl += ' -> %s' + fargs += (brief_repr(result),) + print(tmpl % fargs) + return + + +def wrap_trace(obj, hook=trace_print_hook, + which=None, events=None, label=None): + """Monitor an object for interactions. Whenever code calls a method, + gets an attribute, or sets an attribute, an event is called. By + default the trace output is printed, but a custom tracing *hook* + can be passed. + + Args: + obj (object): New- or old-style object to be traced. Built-in + objects like lists and dicts also supported. + hook (callable): A function called once for every event. See + below for details. + which (str): One or more attribute names to trace, or a + function accepting attribute name and value, and returning + True/False. + events (str): One or more kinds of events to call *hook* + on. Expected values are ``['get', 'set', 'del', 'call', + 'raise', 'return']``. Defaults to all events. + label (str): A name to associate with the traced object + Defaults to hexadecimal memory address, similar to repr. + + The object returned is not the same object as the one passed + in. It will not pass identity checks. However, it will pass + :func:`isinstance` checks, as it is a new instance of a new + subtype of the object passed. + + """ + # other actions: pdb.set_trace, print, aggregate, aggregate_return + # (like aggregate but with the return value) + + # TODO: test classmethod/staticmethod/property + # TODO: wrap __dict__ for old-style classes? + + if isinstance(which, str): + which_func = lambda attr_name, attr_val: attr_name == which + elif callable(getattr(which, '__contains__', None)): + which_func = lambda attr_name, attr_val: attr_name in which + elif which is None or callable(which): + which_func = which + else: + raise TypeError('expected attr name(s) or callable, not: %r' % which) + + label = label or hex(id(obj)) + + if isinstance(events, str): + events = [events] + do_get = not events or 'get' in events + do_set = not events or 'set' in events + do_del = not events or 'del' in events + do_call = not events or 'call' in events + do_raise = not events or 'raise' in events + do_return = not events or 'return' in events + + def wrap_method(attr_name, func, _hook=hook, _label=label): + def wrapped(*a, **kw): + a = a[1:] + if do_call: + hook(event='call', label=_label, obj=obj, + attr_name=attr_name, args=a, kwargs=kw) + if do_raise: + try: + ret = func(*a, **kw) + except Exception: + if not hook(event='raise', label=_label, obj=obj, + attr_name=attr_name, args=a, kwargs=kw, + result=sys.exc_info()): + raise + else: + ret = func(*a, **kw) + if do_return: + hook(event='return', label=_label, obj=obj, + attr_name=attr_name, args=a, kwargs=kw, result=ret) + return ret + + wrapped.__name__ = func.__name__ + wrapped.__doc__ = func.__doc__ + try: + wrapped.__module__ = func.__module__ + except Exception: + pass + try: + if func.__dict__: + wrapped.__dict__.update(func.__dict__) + except Exception: + pass + return wrapped + + def __getattribute__(self, attr_name): + ret = type(obj).__getattribute__(obj, attr_name) + if callable(ret): # wrap any bound methods + ret = type(obj).__getattribute__(self, attr_name) + if do_get: + hook('get', label, obj, attr_name, (), {}, result=ret) + return ret + + def __setattr__(self, attr_name, value): + type(obj).__setattr__(obj, attr_name, value) + if do_set: + hook('set', label, obj, attr_name, (value,), {}) + return + + def __delattr__(self, attr_name): + type(obj).__delattr__(obj, attr_name) + if do_del: + hook('del', label, obj, attr_name, (), {}) + return + + attrs = {} + for attr_name in dir(obj): + try: + attr_val = getattr(obj, attr_name) + except Exception: + continue + + if not callable(attr_val) or attr_name in ('__new__',): + continue + elif which_func and not which_func(attr_name, attr_val): + continue + + if attr_name == '__getattribute__': + wrapped_method = __getattribute__ + elif attr_name == '__setattr__': + wrapped_method = __setattr__ + elif attr_name == '__delattr__': + wrapped_method = __delattr__ + else: + wrapped_method = wrap_method(attr_name, attr_val) + attrs[attr_name] = wrapped_method + + cls_name = obj.__class__.__name__ + if cls_name == cls_name.lower(): + type_name = 'traced_' + cls_name + else: + type_name = 'Traced' + cls_name + + if hasattr(obj, '__mro__'): + bases = (obj.__class__,) + else: + # need new-style class for even basic wrapping of callables to + # work. getattribute won't work for old-style classes of course. + bases = (obj.__class__, object) + + trace_type = type(type_name, bases, attrs) + for cls in trace_type.__mro__: + try: + return cls.__new__(trace_type) + except Exception: + pass + raise TypeError('unable to wrap_trace %r instance %r' + % (obj.__class__, obj)) + + diff --git a/miniconda3/lib/python3.13/site-packages/boltons/deprutils.py b/miniconda3/lib/python3.13/site-packages/boltons/deprutils.py new file mode 100644 index 0000000000000000000000000000000000000000..6c56736f98156e3b1aa63d867f23f400601bab8a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/deprutils.py @@ -0,0 +1,63 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import sys +from types import ModuleType +from warnings import warn + +# todo: only warn once + + +class DeprecatableModule(ModuleType): + def __init__(self, module): + name = module.__name__ + super().__init__(name=name) + self.__dict__.update(module.__dict__) + + def __getattribute__(self, name): + get_attribute = super().__getattribute__ + try: + depros = get_attribute('_deprecated_members') + except AttributeError: + self._deprecated_members = depros = {} + ret = get_attribute(name) + message = depros.get(name) + if message is not None: + warn(message, DeprecationWarning, stacklevel=2) + return ret + + +def deprecate_module_member(mod_name, name, message): + module = sys.modules[mod_name] + if not isinstance(module, DeprecatableModule): + sys.modules[mod_name] = module = DeprecatableModule(module) + module._deprecated_members[name] = message + return diff --git a/miniconda3/lib/python3.13/site-packages/boltons/dictutils.py b/miniconda3/lib/python3.13/site-packages/boltons/dictutils.py new file mode 100644 index 0000000000000000000000000000000000000000..f913f29f61fc4e1d2f5f5ef6dc32936817ab33f2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/dictutils.py @@ -0,0 +1,1120 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python has a very powerful mapping type at its core: the :class:`dict` +type. While versatile and featureful, the :class:`dict` prioritizes +simplicity and performance. As a result, it does not retain the order +of item insertion [1]_, nor does it store multiple values per key. It +is a fast, unordered 1:1 mapping. + +The :class:`OrderedMultiDict` contrasts to the built-in :class:`dict`, +as a relatively maximalist, ordered 1:n subtype of +:class:`dict`. Virtually every feature of :class:`dict` has been +retooled to be intuitive in the face of this added +complexity. Additional methods have been added, such as +:class:`collections.Counter`-like functionality. + +A prime advantage of the :class:`OrderedMultiDict` (OMD) is its +non-destructive nature. Data can be added to an :class:`OMD` without being +rearranged or overwritten. The property can allow the developer to +work more freely with the data, as well as make more assumptions about +where input data will end up in the output, all without any extra +work. + +One great example of this is the :meth:`OMD.inverted()` method, which +returns a new OMD with the values as keys and the keys as values. All +the data and the respective order is still represented in the inverted +form, all from an operation which would be outright wrong and reckless +with a built-in :class:`dict` or :class:`collections.OrderedDict`. + +The OMD has been performance tuned to be suitable for a wide range of +usages, including as a basic unordered MultiDict. Special +thanks to `Mark Williams`_ for all his help. + +.. [1] As of 2015, `basic dicts on PyPy are ordered + `_, + and as of December 2017, `basic dicts in CPython 3 are now ordered + `_, as + well. +.. _Mark Williams: https://github.com/markrwilliams + +""" + +from collections.abc import KeysView, ValuesView, ItemsView +from itertools import zip_longest + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + + +PREV, NEXT, KEY, VALUE, SPREV, SNEXT = range(6) + + +__all__ = ['MultiDict', 'OMD', 'OrderedMultiDict', 'OneToOne', 'ManyToMany', 'subdict', 'FrozenDict'] + + +class OrderedMultiDict(dict): + """A MultiDict is a dictionary that can have multiple values per key + and the OrderedMultiDict (OMD) is a MultiDict that retains + original insertion order. Common use cases include: + + * handling query strings parsed from URLs + * inverting a dictionary to create a reverse index (values to keys) + * stacking data from multiple dictionaries in a non-destructive way + + The OrderedMultiDict constructor is identical to the built-in + :class:`dict`, and overall the API constitutes an intuitive + superset of the built-in type: + + >>> omd = OrderedMultiDict() + >>> omd['a'] = 1 + >>> omd['b'] = 2 + >>> omd.add('a', 3) + >>> omd.get('a') + 3 + >>> omd.getlist('a') + [1, 3] + + Some non-:class:`dict`-like behaviors also make an appearance, + such as support for :func:`reversed`: + + >>> list(reversed(omd)) + ['b', 'a'] + + Note that unlike some other MultiDicts, this OMD gives precedence + to the most recent value added. ``omd['a']`` refers to ``3``, not + ``1``. + + >>> omd + OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> omd.poplast('a') + 3 + >>> omd + OrderedMultiDict([('a', 1), ('b', 2)]) + >>> omd.pop('a') + 1 + >>> omd + OrderedMultiDict([('b', 2)]) + + If you want a safe-to-modify or flat dictionary, use + :meth:`OrderedMultiDict.todict()`. + + >>> from pprint import pprint as pp # preserve printed ordering + >>> omd = OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> pp(omd.todict()) + {'a': 3, 'b': 2} + >>> pp(omd.todict(multi=True)) + {'a': [1, 3], 'b': [2]} + + With ``multi=False``, items appear with the keys in to original + insertion order, alongside the most-recently inserted value for + that key. + + >>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False) + [('a', 3), ('b', 2)] + + .. warning:: + + ``dict(omd)`` changed behavior `in Python 3.7 + `_ due to changes made to + support the transition from :class:`collections.OrderedDict` to + the built-in dictionary being ordered. Before 3.7, the result + would be a new dictionary, with values that were lists, similar + to ``omd.todict(multi=True)`` (but only shallow-copy; the lists + were direct references to OMD internal structures). From 3.7 + onward, the values became singular, like + ``omd.todict(multi=False)``. For reliable cross-version + behavior, just use :meth:`~OrderedMultiDict.todict()`. + + """ + def __new__(cls, *a, **kw): + ret = super().__new__(cls) + ret._clear_ll() + return ret + + def __init__(self, *args, **kwargs): + if len(args) > 1: + raise TypeError('%s expected at most 1 argument, got %s' + % (self.__class__.__name__, len(args))) + super().__init__() + + if args: + self.update_extend(args[0]) + if kwargs: + self.update(kwargs) + + def __getstate__(self): + return list(self.iteritems(multi=True)) + + def __setstate__(self, state): + self.clear() + self.update_extend(state) + + def _clear_ll(self): + try: + _map = self._map + except AttributeError: + _map = self._map = {} + self.root = [] + _map.clear() + self.root[:] = [self.root, self.root, None] + + def _insert(self, k, v): + root = self.root + cells = self._map.setdefault(k, []) + last = root[PREV] + cell = [last, root, k, v] + last[NEXT] = root[PREV] = cell + cells.append(cell) + + def add(self, k, v): + """Add a single value *v* under a key *k*. Existing values under *k* + are preserved. + """ + values = super().setdefault(k, []) + self._insert(k, v) + values.append(v) + + def addlist(self, k, v): + """Add an iterable of values underneath a specific key, preserving + any values already under that key. + + >>> omd = OrderedMultiDict([('a', -1)]) + >>> omd.addlist('a', range(3)) + >>> omd + OrderedMultiDict([('a', -1), ('a', 0), ('a', 1), ('a', 2)]) + + Called ``addlist`` for consistency with :meth:`getlist`, but + tuples and other sequences and iterables work. + """ + if not v: + return + self_insert = self._insert + values = super().setdefault(k, []) + for subv in v: + self_insert(k, subv) + values.extend(v) + + def get(self, k, default=None): + """Return the value for key *k* if present in the dictionary, else + *default*. If *default* is not given, ``None`` is returned. + This method never raises a :exc:`KeyError`. + + To get all values under a key, use :meth:`OrderedMultiDict.getlist`. + """ + return super().get(k, [default])[-1] + + def getlist(self, k, default=_MISSING): + """Get all values for key *k* as a list, if *k* is in the + dictionary, else *default*. The list returned is a copy and + can be safely mutated. If *default* is not given, an empty + :class:`list` is returned. + """ + try: + return super().__getitem__(k)[:] + except KeyError: + if default is _MISSING: + return [] + return default + + def clear(self): + "Empty the dictionary." + super().clear() + self._clear_ll() + + def setdefault(self, k, default=_MISSING): + """If key *k* is in the dictionary, return its value. If not, insert + *k* with a value of *default* and return *default*. *default* + defaults to ``None``. See :meth:`dict.setdefault` for more + information. + """ + if not super().__contains__(k): + self[k] = None if default is _MISSING else default + return self[k] + + def copy(self): + "Return a shallow copy of the dictionary." + return self.__class__(self.iteritems(multi=True)) + + @classmethod + def fromkeys(cls, keys, default=None): + """Create a dictionary from a list of keys, with all the values + set to *default*, or ``None`` if *default* is not set. + """ + return cls([(k, default) for k in keys]) + + def update(self, E, **F): + """Add items from a dictionary or iterable (and/or keyword arguments), + overwriting values under an existing key. See + :meth:`dict.update` for more details. + """ + # E and F are throwback names to the dict() __doc__ + if E is self: + return + self_add = self.add + if isinstance(E, OrderedMultiDict): + for k in E: + if k in self: + del self[k] + for k, v in E.iteritems(multi=True): + self_add(k, v) + elif callable(getattr(E, 'keys', None)): + for k in E.keys(): + self[k] = E[k] + else: + seen = set() + seen_add = seen.add + for k, v in E: + if k not in seen and k in self: + del self[k] + seen_add(k) + self_add(k, v) + for k in F: + self[k] = F[k] + return + + def update_extend(self, E, **F): + """Add items from a dictionary, iterable, and/or keyword + arguments without overwriting existing items present in the + dictionary. Like :meth:`update`, but adds to existing keys + instead of overwriting them. + """ + if E is self: + iterator = iter(E.items()) + elif isinstance(E, OrderedMultiDict): + iterator = E.iteritems(multi=True) + elif hasattr(E, 'keys'): + iterator = ((k, E[k]) for k in E.keys()) + else: + iterator = E + + self_add = self.add + for k, v in iterator: + self_add(k, v) + + def __setitem__(self, k, v): + if super().__contains__(k): + self._remove_all(k) + self._insert(k, v) + super().__setitem__(k, [v]) + + def __getitem__(self, k): + return super().__getitem__(k)[-1] + + def __delitem__(self, k): + super().__delitem__(k) + self._remove_all(k) + + def __eq__(self, other): + if self is other: + return True + try: + if len(other) != len(self): + return False + except TypeError: + return False + if isinstance(other, OrderedMultiDict): + selfi = self.iteritems(multi=True) + otheri = other.iteritems(multi=True) + zipped_items = zip_longest(selfi, otheri, fillvalue=(None, None)) + for (selfk, selfv), (otherk, otherv) in zipped_items: + if selfk != otherk or selfv != otherv: + return False + if not(next(selfi, _MISSING) is _MISSING + and next(otheri, _MISSING) is _MISSING): + # leftovers (TODO: watch for StopIteration?) + return False + return True + elif hasattr(other, 'keys'): + for selfk in self: + try: + other[selfk] == self[selfk] + except KeyError: + return False + return True + return False + + def __ne__(self, other): + return not (self == other) + + def __ior__(self, other): + self.update(other) + return self + + def pop(self, k, default=_MISSING): + """Remove all values under key *k*, returning the most-recently + inserted value. Raises :exc:`KeyError` if the key is not + present and no *default* is provided. + """ + try: + return self.popall(k)[-1] + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + + def popall(self, k, default=_MISSING): + """Remove all values under key *k*, returning them in the form of + a list. Raises :exc:`KeyError` if the key is not present and no + *default* is provided. + """ + super_self = super() + if super_self.__contains__(k): + self._remove_all(k) + if default is _MISSING: + return super_self.pop(k) + return super_self.pop(k, default) + + def poplast(self, k=_MISSING, default=_MISSING): + """Remove and return the most-recently inserted value under the key + *k*, or the most-recently inserted key if *k* is not + provided. If no values remain under *k*, it will be removed + from the OMD. Raises :exc:`KeyError` if *k* is not present in + the dictionary, or the dictionary is empty. + """ + if k is _MISSING: + if self: + k = self.root[PREV][KEY] + else: + if default is _MISSING: + raise KeyError('empty %r' % type(self)) + return default + try: + self._remove(k) + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + values = super().__getitem__(k) + v = values.pop() + if not values: + super().__delitem__(k) + return v + + def _remove(self, k): + values = self._map[k] + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + if not values: + del self._map[k] + + def _remove_all(self, k): + values = self._map[k] + while values: + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + del self._map[k] + + def iteritems(self, multi=False): + """Iterate over the OMD's items in insertion order. By default, + yields only the most-recently inserted value for each key. Set + *multi* to ``True`` to get all inserted items. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY], curr[VALUE] + curr = curr[NEXT] + else: + for key in self.iterkeys(): + yield key, self[key] + + def iterkeys(self, multi=False): + """Iterate over the OMD's keys in insertion order. By default, yields + each key once, according to the most recent insertion. Set + *multi* to ``True`` to get all keys, including duplicates, in + insertion order. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY] + curr = curr[NEXT] + else: + yielded = set() + yielded_add = yielded.add + while curr is not root: + k = curr[KEY] + if k not in yielded: + yielded_add(k) + yield k + curr = curr[NEXT] + + def itervalues(self, multi=False): + """Iterate over the OMD's values in insertion order. By default, + yields the most-recently inserted value per unique key. Set + *multi* to ``True`` to get all values according to insertion + order. + """ + for k, v in self.iteritems(multi=multi): + yield v + + def todict(self, multi=False): + """Gets a basic :class:`dict` of the items in this dictionary. Keys + are the same as the OMD, values are the most recently inserted + values for each key. + + Setting the *multi* arg to ``True`` is yields the same + result as calling :class:`dict` on the OMD, except that all the + value lists are copies that can be safely mutated. + """ + if multi: + return {k: self.getlist(k) for k in self} + return {k: self[k] for k in self} + + def sorted(self, key=None, reverse=False): + """Similar to the built-in :func:`sorted`, except this method returns + a new :class:`OrderedMultiDict` sorted by the provided key + function, optionally reversed. + + Args: + key (callable): A callable to determine the sort key of + each element. The callable should expect an **item** + (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict(zip(range(3), range(3))) + >>> omd.sorted(reverse=True) + OrderedMultiDict([(2, 2), (1, 1), (0, 0)]) + + Note that the key function receives an **item** (key-value + tuple), so the recommended signature looks like: + + >>> omd = OrderedMultiDict(zip('hello', 'world')) + >>> omd.sorted(key=lambda i: i[1]) # i[0] is the key, i[1] is the val + OrderedMultiDict([('o', 'd'), ('l', 'l'), ('e', 'o'), ('l', 'r'), ('h', 'w')]) + """ + cls = self.__class__ + return cls(sorted(self.iteritems(multi=True), key=key, reverse=reverse)) + + def sortedvalues(self, key=None, reverse=False): + """Returns a copy of the :class:`OrderedMultiDict` with the same keys + in the same order as the original OMD, but the values within + each keyspace have been sorted according to *key* and + *reverse*. + + Args: + key (callable): A single-argument callable to determine + the sort key of each element. The callable should expect + an **item** (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict() + >>> omd.addlist('even', [6, 2]) + >>> omd.addlist('odd', [1, 5]) + >>> omd.add('even', 4) + >>> omd.add('odd', 3) + >>> somd = omd.sortedvalues() + >>> somd.getlist('even') + [2, 4, 6] + >>> somd.keys(multi=True) == omd.keys(multi=True) + True + >>> omd == somd + False + >>> somd + OrderedMultiDict([('even', 2), ('even', 4), ('odd', 1), ('odd', 3), ('even', 6), ('odd', 5)]) + + As demonstrated above, contents and key order are + retained. Only value order changes. + """ + try: + superself_iteritems = super().iteritems() + except AttributeError: + superself_iteritems = super().items() + # (not reverse) because they pop off in reverse order for reinsertion + sorted_val_map = {k: sorted(v, key=key, reverse=(not reverse)) + for k, v in superself_iteritems} + ret = self.__class__() + for k in self.iterkeys(multi=True): + ret.add(k, sorted_val_map[k].pop()) + return ret + + def inverted(self): + """Returns a new :class:`OrderedMultiDict` with values and keys + swapped, like creating dictionary transposition or reverse + index. Insertion order is retained and all keys and values + are represented in the output. + + >>> omd = OMD([(0, 2), (1, 2)]) + >>> omd.inverted().getlist(2) + [0, 1] + + Inverting twice yields a copy of the original: + + >>> omd.inverted().inverted() + OrderedMultiDict([(0, 2), (1, 2)]) + """ + return self.__class__((v, k) for k, v in self.iteritems(multi=True)) + + def counts(self): + """Returns a mapping from key to number of values inserted under that + key. Like :py:class:`collections.Counter`, but returns a new + :class:`OrderedMultiDict`. + """ + # Returns an OMD because Counter/OrderedDict may not be + # available, and neither Counter nor dict maintain order. + super_getitem = super().__getitem__ + return self.__class__((k, len(super_getitem(k))) for k in self) + + def keys(self, multi=False): + """Returns a list containing the output of :meth:`iterkeys`. See + that method's docs for more details. + """ + return list(self.iterkeys(multi=multi)) + + def values(self, multi=False): + """Returns a list containing the output of :meth:`itervalues`. See + that method's docs for more details. + """ + return list(self.itervalues(multi=multi)) + + def items(self, multi=False): + """Returns a list containing the output of :meth:`iteritems`. See + that method's docs for more details. + """ + return list(self.iteritems(multi=multi)) + + def __iter__(self): + return self.iterkeys() + + def __reversed__(self): + root = self.root + curr = root[PREV] + lengths = {} + lengths_sd = lengths.setdefault + get_values = super().__getitem__ + while curr is not root: + k = curr[KEY] + vals = get_values(k) + if lengths_sd(k, 1) == len(vals): + yield k + lengths[k] += 1 + curr = curr[PREV] + + def __repr__(self): + cn = self.__class__.__name__ + kvs = ', '.join([repr((k, v)) for k, v in self.iteritems(multi=True)]) + return f'{cn}([{kvs}])' + + def viewkeys(self): + "OMD.viewkeys() -> a set-like object providing a view on OMD's keys" + return KeysView(self) + + def viewvalues(self): + "OMD.viewvalues() -> an object providing a view on OMD's values" + return ValuesView(self) + + def viewitems(self): + "OMD.viewitems() -> a set-like object providing a view on OMD's items" + return ItemsView(self) + + +# A couple of convenient aliases +OMD = OrderedMultiDict +MultiDict = OrderedMultiDict + + +class FastIterOrderedMultiDict(OrderedMultiDict): + """An OrderedMultiDict backed by a skip list. Iteration over keys + is faster and uses constant memory but adding duplicate key-value + pairs is slower. Brainchild of Mark Williams. + """ + def _clear_ll(self): + # TODO: always reset objects? (i.e., no else block below) + try: + _map = self._map + except AttributeError: + _map = self._map = {} + self.root = [] + _map.clear() + self.root[:] = [self.root, self.root, + None, None, + self.root, self.root] + + def _insert(self, k, v): + root = self.root + empty = [] + cells = self._map.setdefault(k, empty) + last = root[PREV] + + if cells is empty: + cell = [last, root, + k, v, + last, root] + # was the last one skipped? + if last[SPREV][SNEXT] is root: + last[SPREV][SNEXT] = cell + last[NEXT] = last[SNEXT] = root[PREV] = root[SPREV] = cell + cells.append(cell) + else: + # if the previous was skipped, go back to the cell that + # skipped it + sprev = last[SPREV] if (last[SPREV][SNEXT] is not last) else last + cell = [last, root, + k, v, + sprev, root] + # skip me + last[SNEXT] = root + last[NEXT] = root[PREV] = root[SPREV] = cell + cells.append(cell) + + def _remove(self, k): + cells = self._map[k] + cell = cells.pop() + if not cells: + del self._map[k] + cell[PREV][SNEXT] = cell[SNEXT] + + if cell[PREV][SPREV][SNEXT] is cell: + cell[PREV][SPREV][SNEXT] = cell[NEXT] + elif cell[SNEXT] is cell[NEXT]: + cell[SPREV][SNEXT], cell[SNEXT][SPREV] = cell[SNEXT], cell[SPREV] + + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + + def _remove_all(self, k): + cells = self._map.pop(k) + while cells: + cell = cells.pop() + if cell[PREV][SPREV][SNEXT] is cell: + cell[PREV][SPREV][SNEXT] = cell[NEXT] + elif cell[SNEXT] is cell[NEXT]: + cell[SPREV][SNEXT], cell[SNEXT][SPREV] = cell[SNEXT], cell[SPREV] + + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + cell[PREV][SNEXT] = cell[SNEXT] + + def iteritems(self, multi=False): + next_link = NEXT if multi else SNEXT + root = self.root + curr = root[next_link] + while curr is not root: + yield curr[KEY], curr[VALUE] + curr = curr[next_link] + + def iterkeys(self, multi=False): + next_link = NEXT if multi else SNEXT + root = self.root + curr = root[next_link] + while curr is not root: + yield curr[KEY] + curr = curr[next_link] + + def __reversed__(self): + root = self.root + curr = root[PREV] + while curr is not root: + if curr[SPREV][SNEXT] is not curr: + curr = curr[SPREV] + if curr is root: + break + yield curr[KEY] + curr = curr[PREV] + + +_OTO_INV_MARKER = object() +_OTO_UNIQUE_MARKER = object() + + +class OneToOne(dict): + """Implements a one-to-one mapping dictionary. In addition to + inheriting from and behaving exactly like the builtin + :class:`dict`, all values are automatically added as keys on a + reverse mapping, available as the `inv` attribute. This + arrangement keeps key and value namespaces distinct. + + Basic operations are intuitive: + + >>> oto = OneToOne({'a': 1, 'b': 2}) + >>> print(oto['a']) + 1 + >>> print(oto.inv[1]) + a + >>> len(oto) + 2 + + Overwrites happens in both directions: + + >>> oto.inv[1] = 'c' + >>> print(oto.get('a')) + None + >>> len(oto) + 2 + + For a very similar project, with even more one-to-one + functionality, check out `bidict `_. + """ + __slots__ = ('inv',) + + def __init__(self, *a, **kw): + raise_on_dupe = False + if a: + if a[0] is _OTO_INV_MARKER: + self.inv = a[1] + dict.__init__(self, [(v, k) for k, v in self.inv.items()]) + return + elif a[0] is _OTO_UNIQUE_MARKER: + a, raise_on_dupe = a[1:], True + + dict.__init__(self, *a, **kw) + self.inv = self.__class__(_OTO_INV_MARKER, self) + + if len(self) == len(self.inv): + # if lengths match, that means everything's unique + return + + if not raise_on_dupe: + dict.clear(self) + dict.update(self, [(v, k) for k, v in self.inv.items()]) + return + + # generate an error message if the values aren't 1:1 + + val_multidict = {} + for k, v in self.items(): + val_multidict.setdefault(v, []).append(k) + + dupes = {v: k_list for v, k_list in + val_multidict.items() if len(k_list) > 1} + + raise ValueError('expected unique values, got multiple keys for' + ' the following values: %r' % dupes) + + @classmethod + def unique(cls, *a, **kw): + """This alternate constructor for OneToOne will raise an exception + when input values overlap. For instance: + + >>> OneToOne.unique({'a': 1, 'b': 1}) + Traceback (most recent call last): + ... + ValueError: expected unique values, got multiple keys for the following values: ... + + This even works across inputs: + + >>> a_dict = {'a': 2} + >>> OneToOne.unique(a_dict, b=2) + Traceback (most recent call last): + ... + ValueError: expected unique values, got multiple keys for the following values: ... + """ + return cls(_OTO_UNIQUE_MARKER, *a, **kw) + + def __setitem__(self, key, val): + hash(val) # ensure val is a valid key + if key in self: + dict.__delitem__(self.inv, self[key]) + if val in self.inv: + del self.inv[val] + dict.__setitem__(self, key, val) + dict.__setitem__(self.inv, val, key) + + def __delitem__(self, key): + dict.__delitem__(self.inv, self[key]) + dict.__delitem__(self, key) + + def clear(self): + dict.clear(self) + dict.clear(self.inv) + + def copy(self): + return self.__class__(self) + + def pop(self, key, default=_MISSING): + if key in self: + dict.__delitem__(self.inv, self[key]) + return dict.pop(self, key) + if default is not _MISSING: + return default + raise KeyError() + + def popitem(self): + key, val = dict.popitem(self) + dict.__delitem__(self.inv, val) + return key, val + + def setdefault(self, key, default=None): + if key not in self: + self[key] = default + return self[key] + + def update(self, dict_or_iterable, **kw): + keys_vals = [] + if isinstance(dict_or_iterable, dict): + for val in dict_or_iterable.values(): + hash(val) + keys_vals = list(dict_or_iterable.items()) + else: + for key, val in dict_or_iterable: + hash(key) + hash(val) + keys_vals = list(dict_or_iterable) + for val in kw.values(): + hash(val) + keys_vals.extend(kw.items()) + for key, val in keys_vals: + self[key] = val + + def __repr__(self): + cn = self.__class__.__name__ + dict_repr = dict.__repr__(self) + return f"{cn}({dict_repr})" + + +# marker for the secret handshake used internally to set up the invert ManyToMany +_PAIRING = object() + + +class ManyToMany: + """ + a dict-like entity that represents a many-to-many relationship + between two groups of objects + + behaves like a dict-of-tuples; also has .inv which is kept + up to date which is a dict-of-tuples in the other direction + + also, can be used as a directed graph among hashable python objects + """ + def __init__(self, items=None): + self.data = {} + if type(items) is tuple and items and items[0] is _PAIRING: + self.inv = items[1] + else: + self.inv = self.__class__((_PAIRING, self)) + if items: + self.update(items) + return + + def get(self, key, default=frozenset()): + try: + return self[key] + except KeyError: + return default + + def __getitem__(self, key): + return frozenset(self.data[key]) + + def __setitem__(self, key, vals): + vals = set(vals) + if key in self: + to_remove = self.data[key] - vals + vals -= self.data[key] + for val in to_remove: + self.remove(key, val) + for val in vals: + self.add(key, val) + + def __delitem__(self, key): + for val in self.data.pop(key): + self.inv.data[val].remove(key) + if not self.inv.data[val]: + del self.inv.data[val] + + def update(self, iterable): + """given an iterable of (key, val), add them all""" + if type(iterable) is type(self): + other = iterable + for k in other.data: + if k not in self.data: + self.data[k] = other.data[k] + else: + self.data[k].update(other.data[k]) + for k in other.inv.data: + if k not in self.inv.data: + self.inv.data[k] = other.inv.data[k] + else: + self.inv.data[k].update(other.inv.data[k]) + elif callable(getattr(iterable, 'keys', None)): + for k in iterable.keys(): + self.add(k, iterable[k]) + else: + for key, val in iterable: + self.add(key, val) + return + + def add(self, key, val): + if key not in self.data: + self.data[key] = set() + self.data[key].add(val) + if val not in self.inv.data: + self.inv.data[val] = set() + self.inv.data[val].add(key) + + def remove(self, key, val): + self.data[key].remove(val) + if not self.data[key]: + del self.data[key] + self.inv.data[val].remove(key) + if not self.inv.data[val]: + del self.inv.data[val] + + def replace(self, key, newkey): + """ + replace instances of key by newkey + """ + if key not in self.data: + return + self.data[newkey] = fwdset = self.data.pop(key) + for val in fwdset: + revset = self.inv.data[val] + revset.remove(key) + revset.add(newkey) + + def iteritems(self): + for key in self.data: + for val in self.data[key]: + yield key, val + + def keys(self): + return self.data.keys() + + def __contains__(self, key): + return key in self.data + + def __iter__(self): + return self.data.__iter__() + + def __len__(self): + return self.data.__len__() + + def __eq__(self, other): + return type(self) == type(other) and self.data == other.data + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({list(self.iteritems())!r})' + + +def subdict(d, keep=None, drop=None): + """Compute the "subdictionary" of a dict, *d*. + + A subdict is to a dict what a subset is a to set. If *A* is a + subdict of *B*, that means that all keys of *A* are present in + *B*. + + Returns a new dict with any keys in *drop* removed, and any keys + in *keep* still present, provided they were in the original + dict. *keep* defaults to all keys, *drop* defaults to empty, so + without one of these arguments, calling this function is + equivalent to calling ``dict()``. + + >>> from pprint import pprint as pp + >>> pp(subdict({'a': 1, 'b': 2})) + {'a': 1, 'b': 2} + >>> subdict({'a': 1, 'b': 2, 'c': 3}, drop=['b', 'c']) + {'a': 1} + >>> pp(subdict({'a': 1, 'b': 2, 'c': 3}, keep=['a', 'c'])) + {'a': 1, 'c': 3} + + """ + if keep is None: + keep = d.keys() + if drop is None: + drop = [] + + keys = set(keep) - set(drop) + + return type(d)([(k, v) for k, v in d.items() if k in keys]) + + +class FrozenHashError(TypeError): + pass + + +class FrozenDict(dict): + """An immutable dict subtype that is hashable and can itself be used + as a :class:`dict` key or :class:`set` entry. What + :class:`frozenset` is to :class:`set`, FrozenDict is to + :class:`dict`. + + There was once an attempt to introduce such a type to the standard + library, but it was rejected: `PEP 416 `_. + + Because FrozenDict is a :class:`dict` subtype, it automatically + works everywhere a dict would, including JSON serialization. + + """ + __slots__ = ('_hash',) + + def updated(self, *a, **kw): + """Make a copy and add items from a dictionary or iterable (and/or + keyword arguments), overwriting values under an existing + key. See :meth:`dict.update` for more details. + """ + data = dict(self) + data.update(*a, **kw) + return type(self)(data) + + @classmethod + def fromkeys(cls, keys, value=None): + # one of the lesser known and used/useful dict methods + return cls(dict.fromkeys(keys, value)) + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({dict.__repr__(self)})' + + def __reduce_ex__(self, protocol): + return type(self), (dict(self),) + + def __hash__(self): + try: + ret = self._hash + except AttributeError: + try: + ret = self._hash = hash(frozenset(self.items())) + except Exception as e: + ret = self._hash = FrozenHashError(e) + + if ret.__class__ is FrozenHashError: + raise ret + + return ret + + def __copy__(self): + return self # immutable types don't copy, see tuple's behavior + + # block everything else + def _raise_frozen_typeerror(self, *a, **kw): + "raises a TypeError, because FrozenDicts are immutable" + raise TypeError('%s object is immutable' % self.__class__.__name__) + + __ior__ = __setitem__ = __delitem__ = update = _raise_frozen_typeerror + setdefault = pop = popitem = clear = _raise_frozen_typeerror + + del _raise_frozen_typeerror + + +# end dictutils.py diff --git a/miniconda3/lib/python3.13/site-packages/boltons/easterutils.py b/miniconda3/lib/python3.13/site-packages/boltons/easterutils.py new file mode 100644 index 0000000000000000000000000000000000000000..02a930a6b26d714b1037fff3059293a6a23ac0e6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/easterutils.py @@ -0,0 +1,44 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +def gobs_program(): + """ + A pure-Python implementation of Gob's Algorithm (2006). A brief + explanation can be found here: + https://www.youtube.com/watch?v=JbnjusltDHk + """ + while True: + print("Penus", end=" ") + + +if __name__ == '__main__': + gobs_program() diff --git a/miniconda3/lib/python3.13/site-packages/boltons/ecoutils.py b/miniconda3/lib/python3.13/site-packages/boltons/ecoutils.py new file mode 100644 index 0000000000000000000000000000000000000000..23fb25fbf329a4b10ea5c4fa5c3fd250257b12ee --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/ecoutils.py @@ -0,0 +1,479 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""As a programming ecosystem grows, so do the chances of runtime +variability. + +Python boasts one of the widest deployments for a high-level +programming environment, making it a viable target for all manner of +application. But with breadth comes variance, so it's important to +know what you're working with. + +Some basic variations that are common among development machines: + +* **Executable runtime**: CPython, PyPy, Jython, etc., plus build date and compiler +* **Language version**: 2.7 through 3.12 +* **Host operating system**: Windows, OS X, Ubuntu, Debian, CentOS, RHEL, etc. +* **Features**: 64-bit, IPv6, Unicode character support (UCS-2/UCS-4) +* **Built-in library support**: OpenSSL, threading, SQLite, zlib +* **User environment**: umask, ulimit, working directory path +* **Machine info**: CPU count, hostname, filesystem encoding + +See the full example profile below for more. + +ecoutils was created to quantify that variability. ecoutils quickly +produces an information-dense description of critical runtime factors, +with minimal side effects. In short, ecoutils is like browser and user +agent analytics, but for Python environments. + +Transmission and collection +--------------------------- + +The data is all JSON serializable, and is suitable for sending to a +central analytics server. An HTTP-backed service for this can be found +at: https://github.com/mahmoud/espymetrics/ + +Notable omissions +----------------- + +Due to space constraints (and possibly latency constraints), the +following information is deemed not dense enough, and thus omitted: + +* :data:`sys.path` +* full :mod:`sysconfig` +* environment variables (:data:`os.environ`) + +Compatibility +------------- + +So far ecoutils has has been tested on Python 3.7+ and PyPy3. +Various versions have been tested on Ubuntu, Debian, +RHEL, OS X, FreeBSD, and Windows 7. + +.. note:: + + ``boltons.ecoutils`` historically supported back to Python 2.4, but in 2024, + due to increasing testing burden, ecoutils support tracks the same + versions of Python as the rest of the boltons package. + For older Pythons, see `this version`_ from boltons 23.0.0. + +.. _this version: https://github.com/mahmoud/boltons/blob/4b1d728f31a8378b193be9c966c853be0a57527d/boltons/ecoutils.py + +Profile generation +------------------ + +Profiles are generated by :func:`ecoutils.get_profile`. + +When run as a module, ecoutils will call :func:`~ecoutils.get_profile` +and print a profile in JSON format:: + + $ python -m boltons.ecoutils + { + "_eco_version": "1.0.0", + "cpu_count": 4, + "cwd": "/home/mahmoud/projects/boltons", + "fs_encoding": "UTF-8", + "guid": "6b139e7bbf5ad4ed8d4063bf6235b4d2", + "hostfqdn": "mahmoud-host", + "hostname": "mahmoud-host", + "linux_dist_name": "Ubuntu", + "linux_dist_version": "14.04", + "python": { + "argv": "boltons/ecoutils.py", + "bin": "/usr/bin/python", + "build_date": "Jun 22 2015 17:58:13", + "compiler": "GCC 4.8.2", + "features": { + "64bit": true, + "expat": "expat_2.1.0", + "ipv6": true, + "openssl": "OpenSSL 1.0.1f 6 Jan 2014", + "readline": true, + "sqlite": "3.8.2", + "threading": true, + "tkinter": "8.6", + "unicode_wide": true, + "zlib": "1.2.8" + }, + "version": "2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]", + "version_info": [ + 2, + 7, + 6, + "final", + 0 + ] + }, + "time_utc": "2016-05-24 07:59:40.473140", + "time_utc_offset": -8.0, + "ulimit_hard": 4096, + "ulimit_soft": 1024, + "umask": "002", + "uname": { + "machine": "x86_64", + "node": "mahmoud-host", + "processor": "x86_64", + "release": "3.13.0-85-generic", + "system": "Linux", + "version": "#129-Ubuntu SMP Thu Mar 17 20:50:15 UTC 2016" + }, + "username": "mahmoud" + } + +``pip install boltons`` and try it yourself! + +""" + +import re +import os +import sys +import json +import time +import random +import socket +import struct +import getpass +import datetime +import platform + +ECO_VERSION = '1.1.0' # see version history below + + +try: + getrandbits = random.SystemRandom().getrandbits + HAVE_URANDOM = True +except Exception: + HAVE_URANDOM = False + getrandbits = random.getrandbits + + +# 128-bit GUID just like a UUID, but backwards compatible to 2.4 +INSTANCE_ID = hex(getrandbits(128))[2:-1].lower() + +IS_64BIT = struct.calcsize("P") > 4 +HAVE_UCS4 = getattr(sys, 'maxunicode', 0) > 65536 +HAVE_READLINE = True + +try: + import readline +except Exception: + HAVE_READLINE = False + +try: + import sqlite3 + SQLITE_VERSION = sqlite3.sqlite_version +except Exception: + # note: 2.5 and older have sqlite, but not sqlite3 + SQLITE_VERSION = '' + + +try: + + import ssl + try: + OPENSSL_VERSION = ssl.OPENSSL_VERSION + except AttributeError: + # This is a conservative estimate for Python <2.6 + # SSL module added in 2006, when 0.9.7 was standard + OPENSSL_VERSION = 'OpenSSL >0.8.0' +except Exception: + OPENSSL_VERSION = '' + + +try: + import tkinter + TKINTER_VERSION = str(tkinter.TkVersion) +except Exception: + TKINTER_VERSION = '' + + +try: + import zlib + ZLIB_VERSION = zlib.ZLIB_VERSION +except Exception: + ZLIB_VERSION = '' + + +try: + from xml.parsers import expat + EXPAT_VERSION = expat.EXPAT_VERSION +except Exception: + EXPAT_VERSION = '' + + +try: + from multiprocessing import cpu_count + CPU_COUNT = cpu_count() +except Exception: + CPU_COUNT = 0 + +try: + import threading + HAVE_THREADING = True +except Exception: + HAVE_THREADING = False + + +try: + HAVE_IPV6 = socket.has_ipv6 +except Exception: + HAVE_IPV6 = False + + +try: + from resource import getrlimit, RLIMIT_NOFILE + RLIMIT_FDS_SOFT, RLIMIT_FDS_HARD = getrlimit(RLIMIT_NOFILE) +except Exception: + RLIMIT_FDS_SOFT, RLIMIT_FDS_HARD = 0, 0 + + +START_TIME_INFO = {'time_utc': str(datetime.datetime.now(datetime.timezone.utc)), + 'time_utc_offset': -time.timezone / 3600.0} + + +def get_python_info(): + ret = {} + ret['argv'] = _escape_shell_args(sys.argv) + ret['bin'] = sys.executable + + # Even though compiler/build_date are already here, they're + # actually parsed from the version string. So, in the rare case of + # the unparsable version string, we're still transmitting it. + ret['version'] = ' '.join(sys.version.split()) + + ret['compiler'] = platform.python_compiler() + ret['build_date'] = platform.python_build()[1] + ret['version_info'] = list(sys.version_info) + + ret['features'] = {'openssl': OPENSSL_VERSION, + 'expat': EXPAT_VERSION, + 'sqlite': SQLITE_VERSION, + 'tkinter': TKINTER_VERSION, + 'zlib': ZLIB_VERSION, + 'unicode_wide': HAVE_UCS4, + 'readline': HAVE_READLINE, + '64bit': IS_64BIT, + 'ipv6': HAVE_IPV6, + 'threading': HAVE_THREADING, + 'urandom': HAVE_URANDOM} + + return ret + + +def get_profile(**kwargs): + """The main entrypoint to ecoutils. Calling this will return a + JSON-serializable dictionary of information about the current + process. + + It is very unlikely that the information returned will change + during the lifetime of the process, and in most cases the majority + of the information stays the same between runs as well. + + :func:`get_profile` takes one optional keyword argument, *scrub*, + a :class:`bool` that, if True, blanks out identifiable + information. This includes current working directory, hostname, + Python executable path, command-line arguments, and + username. Values are replaced with '-', but for compatibility keys + remain in place. + + """ + scrub = kwargs.pop('scrub', False) + if kwargs: + raise TypeError(f'unexpected keyword arguments: {kwargs.keys()!r}') + ret = {} + try: + ret['username'] = getpass.getuser() + except Exception: + ret['username'] = '' + ret['guid'] = str(INSTANCE_ID) + ret['hostname'] = socket.gethostname() + ret['hostfqdn'] = socket.getfqdn() + uname = platform.uname() + ret['uname'] = {'system': uname[0], + 'node': uname[1], + 'release': uname[2], # linux: distro name + 'version': uname[3], # linux: kernel version + 'machine': uname[4], + 'processor': uname[5]} + try: + # TODO: removed in 3.7, replaced with freedesktop_os_release in 3.10 + linux_dist = platform.linux_distribution() + except Exception: + linux_dist = ('', '', '') + ret['linux_dist_name'] = linux_dist[0] + ret['linux_dist_version'] = linux_dist[1] + ret['cpu_count'] = CPU_COUNT + + ret['fs_encoding'] = sys.getfilesystemencoding() + ret['ulimit_soft'] = RLIMIT_FDS_SOFT + ret['ulimit_hard'] = RLIMIT_FDS_HARD + ret['cwd'] = os.getcwd() + ret['umask'] = oct(os.umask(os.umask(2))).rjust(3, '0') + + ret['python'] = get_python_info() + ret.update(START_TIME_INFO) + ret['_eco_version'] = ECO_VERSION + + if scrub: + # mask identifiable information + ret['cwd'] = '-' + ret['hostname'] = '-' + ret['hostfqdn'] = '-' + ret['python']['bin'] = '-' + ret['python']['argv'] = '-' + ret['uname']['node'] = '-' + ret['username'] = '-' + + return ret + + +def dumps(val, indent): + if indent: + return json.dumps(val, sort_keys=True, indent=indent) + return json.dumps(val, sort_keys=True) + + +def get_profile_json(indent=False): + if indent: + indent = 2 + else: + indent = 0 + + data_dict = get_profile() + return dumps(data_dict, indent) + + +def main(): + print(get_profile_json(indent=True)) + +############################################# +# The shell escaping copied in from strutils +############################################# + + +def _escape_shell_args(args, sep=' ', style=None): + if not style: + if sys.platform == 'win32': + style = 'cmd' + else: + style = 'sh' + + if style == 'sh': + return _args2sh(args, sep=sep) + elif style == 'cmd': + return _args2cmd(args, sep=sep) + + raise ValueError("style expected one of 'cmd' or 'sh', not %r" % style) + + +_find_sh_unsafe = re.compile(r'[^a-zA-Z0-9_@%+=:,./-]').search + + +def _args2sh(args, sep=' '): + # see strutils + ret_list = [] + + for arg in args: + if not arg: + ret_list.append("''") + continue + if _find_sh_unsafe(arg) is None: + ret_list.append(arg) + continue + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + ret_list.append("'" + arg.replace("'", "'\"'\"'") + "'") + + return ' '.join(ret_list) + + +def _args2cmd(args, sep=' '): + # see strutils + result = [] + needquote = False + for arg in args: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) or not arg + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + + +############################ +# End shell escaping code +############################ + +if __name__ == '__main__': + main() + + +""" + +ecoutils protocol version history +--------------------------------- + +The version is ECO_VERSION module-level constant, and _eco_version key +in the dictionary returned from ecoutils.get_profile(). + +1.1.0 - (boltons version 24.0.0+) Drop Python <=3.6 compat +1.0.1 - (boltons version 16.3.2+) Remove uuid dependency and add HAVE_URANDOM +1.0.0 - (boltons version 16.3.0-16.3.1) Initial release + +""" diff --git a/miniconda3/lib/python3.13/site-packages/boltons/excutils.py b/miniconda3/lib/python3.13/site-packages/boltons/excutils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa3262d4d8d21207341f3f1ae4ec9b26eb866fea --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/excutils.py @@ -0,0 +1,287 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +import sys +import traceback +import linecache +from collections import namedtuple + +# TODO: last arg or first arg? (last arg makes it harder to *args +# into, but makes it more readable in the default exception +# __repr__ output) +# TODO: Multiexception wrapper + + +__all__ = ['ExceptionCauseMixin'] + + +class ExceptionCauseMixin(Exception): + """ + A mixin class for wrapping an exception in another exception, or + otherwise indicating an exception was caused by another exception. + + This is most useful in concurrent or failure-intolerant scenarios, + where just because one operation failed, doesn't mean the remainder + should be aborted, or that it's the appropriate time to raise + exceptions. + + This is still a work in progress, but an example use case at the + bottom of this module. + + NOTE: when inheriting, you will probably want to put the + ExceptionCauseMixin first. Builtin exceptions are not good about + calling super() + """ + + cause = None + + def __new__(cls, *args, **kw): + cause = None + if args and isinstance(args[0], Exception): + cause, args = args[0], args[1:] + ret = super().__new__(cls, *args, **kw) + ret.cause = cause + if cause is None: + return ret + root_cause = getattr(cause, 'root_cause', None) + if root_cause is None: + ret.root_cause = cause + else: + ret.root_cause = root_cause + + full_trace = getattr(cause, 'full_trace', None) + if full_trace is not None: + ret.full_trace = list(full_trace) + ret._tb = list(cause._tb) + ret._stack = list(cause._stack) + return ret + + try: + exc_type, exc_value, exc_tb = sys.exc_info() + if exc_type is None and exc_value is None: + return ret + if cause is exc_value or root_cause is exc_value: + # handles when cause is the current exception or when + # there are multiple wraps while handling the original + # exception, but a cause was never provided + ret._tb = _extract_from_tb(exc_tb) + ret._stack = _extract_from_frame(exc_tb.tb_frame) + ret.full_trace = ret._stack[:-1] + ret._tb + finally: + del exc_tb + return ret + + def get_str(self): + """ + Get formatted the formatted traceback and exception + message. This function exists separately from __str__() + because __str__() is somewhat specialized for the built-in + traceback module's particular usage. + """ + ret = [] + trace_str = self._get_trace_str() + if trace_str: + ret.extend(['Traceback (most recent call last):\n', trace_str]) + ret.append(self._get_exc_str()) + return ''.join(ret) + + def _get_message(self): + args = getattr(self, 'args', []) + if self.cause: + args = args[1:] + if args and args[0]: + return args[0] + return '' + + def _get_trace_str(self): + if not self.cause: + return super().__repr__() + if self.full_trace: + return ''.join(traceback.format_list(self.full_trace)) + return '' + + def _get_exc_str(self, incl_name=True): + cause_str = _format_exc(self.root_cause) + message = self._get_message() + ret = [] + if incl_name: + ret = [self.__class__.__name__, ': '] + if message: + ret.extend([message, ' (caused by ', cause_str, ')']) + else: + ret.extend([' caused by ', cause_str]) + return ''.join(ret) + + def __str__(self): + if not self.cause: + return super().__str__() + trace_str = self._get_trace_str() + ret = [] + if trace_str: + message = self._get_message() + if message: + ret.extend([message, ' --- ']) + ret.extend(['Wrapped traceback (most recent call last):\n', + trace_str, + self._get_exc_str(incl_name=True)]) + return ''.join(ret) + else: + return self._get_exc_str(incl_name=False) + + +def _format_exc(exc, message=None): + if message is None: + message = exc + exc_str = traceback._format_final_exc_line(exc.__class__.__name__, message) + return exc_str.rstrip() + + +_BaseTBItem = namedtuple('_BaseTBItem', 'filename, lineno, name, line') + + +class _TBItem(_BaseTBItem): + def __repr__(self): + ret = super().__repr__() + ret += ' <%r>' % self.frame_id + return ret + + +class _DeferredLine: + def __init__(self, filename, lineno, module_globals=None): + self.filename = filename + self.lineno = lineno + module_globals = module_globals or {} + self.module_globals = {k: v for k, v in module_globals.items() + if k in ('__name__', '__loader__')} + + def __eq__(self, other): + return (self.lineno, self.filename) == (other.lineno, other.filename) + + def __ne__(self, other): + return (self.lineno, self.filename) != (other.lineno, other.filename) + + def __str__(self): + if hasattr(self, '_line'): + return self._line + linecache.checkcache(self.filename) + line = linecache.getline(self.filename, + self.lineno, + self.module_globals) + if line: + line = line.strip() + else: + line = None + self._line = line + return line + + def __repr__(self): + return repr(str(self)) + + def __len__(self): + return len(str(self)) + + def strip(self): + return str(self).strip() + + +def _extract_from_frame(f=None, limit=None): + ret = [] + if f is None: + f = sys._getframe(1) # cross-impl yadayada + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while f is not None and n < limit: + filename = f.f_code.co_filename + lineno = f.f_lineno + name = f.f_code.co_name + line = _DeferredLine(filename, lineno, f.f_globals) + item = _TBItem(filename, lineno, name, line) + item.frame_id = id(f) + ret.append(item) + f = f.f_back + n += 1 + ret.reverse() + return ret + + +def _extract_from_tb(tb, limit=None): + ret = [] + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while tb is not None and n < limit: + filename = tb.tb_frame.f_code.co_filename + lineno = tb.tb_lineno + name = tb.tb_frame.f_code.co_name + line = _DeferredLine(filename, lineno, tb.tb_frame.f_globals) + item = _TBItem(filename, lineno, name, line) + item.frame_id = id(tb.tb_frame) + ret.append(item) + tb = tb.tb_next + n += 1 + return ret + + +# An Example/Prototest: + + +class MathError(ExceptionCauseMixin, ValueError): + pass + + +def whoops_math(): + return 1/0 + + +def math_lol(n=0): + if n < 3: + return math_lol(n=n+1) + try: + return whoops_math() + except ZeroDivisionError as zde: + exc = MathError(zde, 'ya done messed up') + raise exc + +def main(): + try: + math_lol() + except ValueError as me: + exc = MathError(me, 'hi') + raise exc + + +if __name__ == '__main__': + try: + main() + except Exception: + import pdb;pdb.post_mortem() + raise diff --git a/miniconda3/lib/python3.13/site-packages/boltons/fileutils.py b/miniconda3/lib/python3.13/site-packages/boltons/fileutils.py new file mode 100644 index 0000000000000000000000000000000000000000..2a0577047d11697e2eba6cd639f6a3319100c243 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/fileutils.py @@ -0,0 +1,727 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Virtually every Python programmer has used Python for wrangling +disk contents, and ``fileutils`` collects solutions to some of the +most commonly-found gaps in the standard library. +""" + + +import os +import re +import sys +import stat +import errno +import fnmatch +from shutil import copy2, copystat, Error + + +__all__ = ['mkdir_p', 'atomic_save', 'AtomicSaver', 'FilePerms', + 'iter_find_files', 'copytree'] + + +FULL_PERMS = 0o777 +RW_PERMS = 438 +_SINGLE_FULL_PERM = 7 + + +def mkdir_p(path): + """Creates a directory and any parent directories that may need to + be created along the way, without raising errors for any existing + directories. This function mimics the behavior of the ``mkdir -p`` + command available in Linux/BSD environments, but also works on + Windows. + """ + try: + os.makedirs(path) + except OSError as exc: + if exc.errno == errno.EEXIST and os.path.isdir(path): + return + raise + return + + +class FilePerms: + """The :class:`FilePerms` type is used to represent standard POSIX + filesystem permissions: + + * Read + * Write + * Execute + + Across three classes of user: + + * Owning (u)ser + * Owner's (g)roup + * Any (o)ther user + + This class assists with computing new permissions, as well as + working with numeric octal ``777``-style and ``rwx``-style + permissions. Currently it only considers the bottom 9 permission + bits; it does not support sticky bits or more advanced permission + systems. + + Args: + user (str): A string in the 'rwx' format, omitting characters + for which owning user's permissions are not provided. + group (str): A string in the 'rwx' format, omitting characters + for which owning group permissions are not provided. + other (str): A string in the 'rwx' format, omitting characters + for which owning other/world permissions are not provided. + + There are many ways to use :class:`FilePerms`: + + >>> FilePerms(user='rwx', group='xrw', other='wxr') # note character order + FilePerms(user='rwx', group='rwx', other='rwx') + >>> int(FilePerms('r', 'r', '')) + 288 + >>> oct(288)[-3:] # XXX Py3k + '440' + + See also the :meth:`FilePerms.from_int` and + :meth:`FilePerms.from_path` classmethods for useful alternative + ways to construct :class:`FilePerms` objects. + """ + # TODO: consider more than the lower 9 bits + class _FilePermProperty: + _perm_chars = 'rwx' + _perm_set = frozenset('rwx') + _perm_val = {'r': 4, 'w': 2, 'x': 1} # for sorting + + def __init__(self, attribute, offset): + self.attribute = attribute + self.offset = offset + + def __get__(self, fp_obj, type_=None): + if fp_obj is None: + return self + return getattr(fp_obj, self.attribute) + + def __set__(self, fp_obj, value): + cur = getattr(fp_obj, self.attribute) + if cur == value: + return + try: + invalid_chars = set(str(value)) - self._perm_set + except TypeError: + raise TypeError('expected string, not %r' % value) + if invalid_chars: + raise ValueError('got invalid chars %r in permission' + ' specification %r, expected empty string' + ' or one or more of %r' + % (invalid_chars, value, self._perm_chars)) + + def sort_key(c): return self._perm_val[c] + new_value = ''.join(sorted(set(value), + key=sort_key, reverse=True)) + setattr(fp_obj, self.attribute, new_value) + self._update_integer(fp_obj, new_value) + + def _update_integer(self, fp_obj, value): + mode = 0 + key = 'xwr' + for symbol in value: + bit = 2 ** key.index(symbol) + mode |= (bit << (self.offset * 3)) + fp_obj._integer |= mode + + def __init__(self, user='', group='', other=''): + self._user, self._group, self._other = '', '', '' + self._integer = 0 + self.user = user + self.group = group + self.other = other + + @classmethod + def from_int(cls, i): + """Create a :class:`FilePerms` object from an integer. + + >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal + FilePerms(user='rw', group='r', other='r') + """ + i &= FULL_PERMS + key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx') + parts = [] + while i: + parts.append(key[i & _SINGLE_FULL_PERM]) + i >>= 3 + parts.reverse() + return cls(*parts) + + @classmethod + def from_path(cls, path): + """Make a new :class:`FilePerms` object based on the permissions + assigned to the file or directory at *path*. + + Args: + path (str): Filesystem path of the target file. + + Here's an example that holds true on most systems: + + >>> import tempfile + >>> 'r' in FilePerms.from_path(tempfile.gettempdir()).user + True + """ + stat_res = os.stat(path) + return cls.from_int(stat.S_IMODE(stat_res.st_mode)) + + def __int__(self): + return self._integer + + # Sphinx tip: attribute docstrings come after the attribute + user = _FilePermProperty('_user', 2) + "Stores the ``rwx``-formatted *user* permission." + group = _FilePermProperty('_group', 1) + "Stores the ``rwx``-formatted *group* permission." + other = _FilePermProperty('_other', 0) + "Stores the ``rwx``-formatted *other* permission." + + def __repr__(self): + cn = self.__class__.__name__ + return ('%s(user=%r, group=%r, other=%r)' + % (cn, self.user, self.group, self.other)) + +#### + + +_TEXT_OPENFLAGS = os.O_RDWR | os.O_CREAT | os.O_EXCL +if hasattr(os, 'O_NOINHERIT'): + _TEXT_OPENFLAGS |= os.O_NOINHERIT +if hasattr(os, 'O_NOFOLLOW'): + _TEXT_OPENFLAGS |= os.O_NOFOLLOW +_BIN_OPENFLAGS = _TEXT_OPENFLAGS +if hasattr(os, 'O_BINARY'): + _BIN_OPENFLAGS |= os.O_BINARY + + +try: + import fcntl as fcntl +except ImportError: + def set_cloexec(fd): + "Dummy set_cloexec for platforms without fcntl support" + pass +else: + def set_cloexec(fd): + """Does a best-effort :func:`fcntl.fcntl` call to set a fd to be + automatically closed by any future child processes. + + Implementation from the :mod:`tempfile` module. + """ + try: + flags = fcntl.fcntl(fd, fcntl.F_GETFD, 0) + except OSError: + pass + else: + # flags read successfully, modify + flags |= fcntl.FD_CLOEXEC + fcntl.fcntl(fd, fcntl.F_SETFD, flags) + return + + +def atomic_save(dest_path, **kwargs): + """A convenient interface to the :class:`AtomicSaver` type. Example: + + >>> try: + ... with atomic_save("file.txt", text_mode=True) as fo: + ... _ = fo.write('bye') + ... 1/0 # will error + ... fo.write('bye') + ... except ZeroDivisionError: + ... pass # at least our file.txt didn't get overwritten + + See the :class:`AtomicSaver` documentation for details. + """ + return AtomicSaver(dest_path, **kwargs) + + +def path_to_unicode(path): + if isinstance(path, str): + return path + encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() + return path.decode(encoding) + + +if os.name == 'nt': + import ctypes + from ctypes import c_wchar_p + from ctypes.wintypes import DWORD, LPVOID + + _ReplaceFile = ctypes.windll.kernel32.ReplaceFile + _ReplaceFile.argtypes = [c_wchar_p, c_wchar_p, c_wchar_p, + DWORD, LPVOID, LPVOID] + + def replace(src, dst): + # argument names match stdlib docs, docstring below + try: + # ReplaceFile fails if the dest file does not exist, so + # first try to rename it into position + os.rename(src, dst) + return + except OSError as we: + if we.errno == errno.EEXIST: + pass # continue with the ReplaceFile logic below + else: + raise + + src = path_to_unicode(src) + dst = path_to_unicode(dst) + res = _ReplaceFile(c_wchar_p(dst), c_wchar_p(src), + None, 0, None, None) + if not res: + raise OSError(f'failed to replace {dst!r} with {src!r}') + return + + def atomic_rename(src, dst, overwrite=False): + "Rename *src* to *dst*, replacing *dst* if *overwrite is True" + if overwrite: + replace(src, dst) + else: + os.rename(src, dst) + return +else: + # wrapper func for cross compat + docs + def replace(src, dst): + # os.replace does the same thing on unix + return os.rename(src, dst) + + def atomic_rename(src, dst, overwrite=False): + "Rename *src* to *dst*, replacing *dst* if *overwrite is True" + if overwrite: + os.rename(src, dst) + else: + os.link(src, dst) + os.unlink(src) + return + + +_atomic_rename = atomic_rename # backwards compat + +replace.__doc__ = """Similar to :func:`os.replace` in Python 3.3+, +this function will atomically create or replace the file at path +*dst* with the file at path *src*. + +On Windows, this function uses the ReplaceFile API for maximum +possible atomicity on a range of filesystems. +""" + + +class AtomicSaver: + """``AtomicSaver`` is a configurable `context manager`_ that provides + a writable :class:`file` which will be moved into place as long as + no exceptions are raised within the context manager's block. These + "part files" are created in the same directory as the destination + path to ensure atomic move operations (i.e., no cross-filesystem + moves occur). + + Args: + dest_path (str): The path where the completed file will be + written. + overwrite (bool): Whether to overwrite the destination file if + it exists at completion time. Defaults to ``True``. + file_perms (int): Integer representation of file permissions + for the newly-created file. Defaults are, when the + destination path already exists, to copy the permissions + from the previous file, or if the file did not exist, to + respect the user's configured `umask`_, usually resulting + in octal 0644 or 0664. + text_mode (bool): Whether to open the destination file in text + mode (i.e., ``'w'`` not ``'wb'``). Defaults to ``False`` (``wb``). + part_file (str): Name of the temporary *part_file*. Defaults + to *dest_path* + ``.part``. Note that this argument is + just the filename, and not the full path of the part + file. To guarantee atomic saves, part files are always + created in the same directory as the destination path. + overwrite_part (bool): Whether to overwrite the *part_file*, + should it exist at setup time. Defaults to ``False``, + which results in an :exc:`OSError` being raised on + pre-existing part files. Be careful of setting this to + ``True`` in situations when multiple threads or processes + could be writing to the same part file. + rm_part_on_exc (bool): Remove *part_file* on exception cases. + Defaults to ``True``, but ``False`` can be useful for + recovery in some cases. Note that resumption is not + automatic and by default an :exc:`OSError` is raised if + the *part_file* exists. + + Practically, the AtomicSaver serves a few purposes: + + * Avoiding overwriting an existing, valid file with a partially + written one. + * Providing a reasonable guarantee that a part file only has one + writer at a time. + * Optional recovery of partial data in failure cases. + + .. _context manager: https://docs.python.org/2/reference/compound_stmts.html#with + .. _umask: https://en.wikipedia.org/wiki/Umask + + """ + _default_file_perms = RW_PERMS + + # TODO: option to abort if target file modify date has changed since start? + def __init__(self, dest_path, **kwargs): + self.dest_path = dest_path + self.overwrite = kwargs.pop('overwrite', True) + self.file_perms = kwargs.pop('file_perms', None) + self.overwrite_part = kwargs.pop('overwrite_part', False) + self.part_filename = kwargs.pop('part_file', None) + self.rm_part_on_exc = kwargs.pop('rm_part_on_exc', True) + self.text_mode = kwargs.pop('text_mode', False) + self.buffering = kwargs.pop('buffering', -1) + if kwargs: + raise TypeError(f'unexpected kwargs: {kwargs.keys()!r}') + + self.dest_path = os.path.abspath(self.dest_path) + self.dest_dir = os.path.dirname(self.dest_path) + if not self.part_filename: + self.part_path = dest_path + '.part' + else: + self.part_path = os.path.join(self.dest_dir, self.part_filename) + self.mode = 'w+' if self.text_mode else 'w+b' + self.open_flags = _TEXT_OPENFLAGS if self.text_mode else _BIN_OPENFLAGS + + self.part_file = None + + def _open_part_file(self): + do_chmod = True + file_perms = self.file_perms + if file_perms is None: + try: + # try to copy from file being replaced + stat_res = os.stat(self.dest_path) + file_perms = stat.S_IMODE(stat_res.st_mode) + except OSError: + # default if no destination file exists + file_perms = self._default_file_perms + do_chmod = False # respect the umask + + fd = os.open(self.part_path, self.open_flags, file_perms) + set_cloexec(fd) + self.part_file = os.fdopen(fd, self.mode, self.buffering) + + # if default perms are overridden by the user or previous dest_path + # chmod away the effects of the umask + if do_chmod: + try: + os.chmod(self.part_path, file_perms) + except OSError: + self.part_file.close() + raise + return + + def setup(self): + """Called on context manager entry (the :keyword:`with` statement), + the ``setup()`` method creates the temporary file in the same + directory as the destination file. + + ``setup()`` tests for a writable directory with rename permissions + early, as the part file may not be written to immediately (not + using :func:`os.access` because of the potential issues of + effective vs. real privileges). + + If the caller is not using the :class:`AtomicSaver` as a + context manager, this method should be called explicitly + before writing. + """ + if os.path.lexists(self.dest_path): + if not self.overwrite: + raise OSError(errno.EEXIST, + 'Overwrite disabled and file already exists', + self.dest_path) + if self.overwrite_part and os.path.lexists(self.part_path): + os.unlink(self.part_path) + self._open_part_file() + return + + def __enter__(self): + self.setup() + return self.part_file + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.part_file: + # Ensure data is flushed and synced to disk before closing + self.part_file.flush() + os.fsync(self.part_file.fileno()) + self.part_file.close() + if exc_type: + if self.rm_part_on_exc: + try: + os.unlink(self.part_path) + except Exception: + pass # avoid masking original error + return + try: + atomic_rename(self.part_path, self.dest_path, + overwrite=self.overwrite) + except OSError: + if self.rm_part_on_exc: + try: + os.unlink(self.part_path) + except Exception: + pass # avoid masking original error + raise # could not save destination file + return + + +def iter_find_files(directory, patterns, ignored=None, include_dirs=False, max_depth=None): + """Returns a generator that yields file paths under a *directory*, + matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also + supports *ignored* patterns. + + Args: + directory (str): Path that serves as the root of the + search. Yielded paths will include this as a prefix. + patterns (str or list): A single pattern or list of + glob-formatted patterns to find under *directory*. + ignored (str or list): A single pattern or list of + glob-formatted patterns to ignore. + include_dirs (bool): Whether to include directories that match + patterns, as well. Defaults to ``False``. + max_depth (int): traverse up to this level of subdirectory. + I.e., 0 for the specified *directory* only, 1 for *directory* + and one level of subdirectory. + + For example, finding Python files in the current directory: + + >>> _CUR_DIR = os.path.dirname(os.path.abspath(__file__)) + >>> filenames = sorted(iter_find_files(_CUR_DIR, '*.py')) + >>> os.path.basename(filenames[-1]) + 'urlutils.py' + + Or, Python files while ignoring emacs lockfiles: + + >>> filenames = iter_find_files(_CUR_DIR, '*.py', ignored='.#*') + + .. _glob: https://en.wikipedia.org/wiki/Glob_%28programming%29 + + """ + if isinstance(patterns, str): + patterns = [patterns] + pats_re = re.compile('|'.join([fnmatch.translate(p) for p in patterns])) + + if not ignored: + ignored = [] + elif isinstance(ignored, str): + ignored = [ignored] + ign_re = re.compile('|'.join([fnmatch.translate(p) for p in ignored])) + start_depth = len(directory.split(os.path.sep)) + for root, dirs, files in os.walk(directory): + if max_depth is not None and (len(root.split(os.path.sep)) - start_depth) > max_depth: + continue + if include_dirs: + for basename in dirs: + if pats_re.match(basename): + if ignored and ign_re.match(basename): + continue + filename = os.path.join(root, basename) + yield filename + + for basename in files: + if pats_re.match(basename): + if ignored and ign_re.match(basename): + continue + filename = os.path.join(root, basename) + yield filename + return + + +def copy_tree(src, dst, symlinks=False, ignore=None): + """The ``copy_tree`` function is an exact copy of the built-in + :func:`shutil.copytree`, with one key difference: it will not + raise an exception if part of the tree already exists. It achieves + this by using :func:`mkdir_p`. + + As of Python 3.8, you may pass :func:`shutil.copytree` the + `dirs_exist_ok=True` flag to achieve the same effect. + + Args: + src (str): Path of the source directory to copy. + dst (str): Destination path. Existing directories accepted. + symlinks (bool): If ``True``, copy symlinks rather than their + contents. + ignore (callable): A callable that takes a path and directory + listing, returning the files within the listing to be ignored. + + For more details, check out :func:`shutil.copytree` and + :func:`shutil.copy2`. + + """ + names = os.listdir(src) + if ignore is not None: + ignored_names = ignore(src, names) + else: + ignored_names = set() + + mkdir_p(dst) + errors = [] + for name in names: + if name in ignored_names: + continue + srcname = os.path.join(src, name) + dstname = os.path.join(dst, name) + try: + if symlinks and os.path.islink(srcname): + linkto = os.readlink(srcname) + os.symlink(linkto, dstname) + elif os.path.isdir(srcname): + copytree(srcname, dstname, symlinks, ignore) + else: + # Will raise a SpecialFileError for unsupported file types + copy2(srcname, dstname) + # catch the Error from the recursive copytree so that we can + # continue with other files + except Error as e: + errors.extend(e.args[0]) + except OSError as why: + errors.append((srcname, dstname, str(why))) + try: + copystat(src, dst) + except OSError as why: + errors.append((src, dst, str(why))) + if errors: + raise Error(errors) + + +copytree = copy_tree # alias for drop-in replacement of shutil + + +# like open(os.devnull) but with even fewer side effects +class DummyFile: + # TODO: raise ValueErrors on closed for all methods? + # TODO: enforce read/write + def __init__(self, path, mode='r', buffering=None): + self.name = path + self.mode = mode + self.closed = False + self.errors = None + self.isatty = False + self.encoding = None + self.newlines = None + self.softspace = 0 + + def close(self): + self.closed = True + + def fileno(self): + return -1 + + def flush(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def next(self): + raise StopIteration() + + def read(self, size=0): + if self.closed: + raise ValueError('I/O operation on a closed file') + return '' + + def readline(self, size=0): + if self.closed: + raise ValueError('I/O operation on a closed file') + return '' + + def readlines(self, size=0): + if self.closed: + raise ValueError('I/O operation on a closed file') + return [] + + def seek(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def tell(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return 0 + + def truncate(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def write(self, string): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def writelines(self, list_of_strings): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def __next__(self): + raise StopIteration() + + def __enter__(self): + if self.closed: + raise ValueError('I/O operation on a closed file') + return + + def __exit__(self, exc_type, exc_val, exc_tb): + return + + +def rotate_file(filename, *, keep: int = 5): + """ + If *filename.ext* exists, it will be moved to *filename.1.ext*, + with all conflicting filenames being moved up by one, dropping any files beyond *keep*. + + After rotation, *filename* will be available for creation as a new file. + + Fails if *filename* is not a file or if *keep* is not > 0. + """ + if keep < 1: + raise ValueError(f'expected "keep" to be >=1, not {keep}') + if not os.path.exists(filename): + return + if not os.path.isfile(filename): + raise ValueError(f'expected {filename} to be a file') + + fn_root, fn_ext = os.path.splitext(filename) + kept_names = [] + for i in range(1, keep + 1): + if fn_ext: + kept_names.append(f'{fn_root}.{i}{fn_ext}') + else: + kept_names.append(f'{fn_root}.{i}') + + fns = [filename] + kept_names + for orig_name, kept_name in reversed(list(zip(fns, fns[1:]))): + if not os.path.exists(orig_name): + continue + os.rename(orig_name, kept_name) + + if os.path.exists(kept_names[-1]): + os.remove(kept_names[-1]) + + return diff --git a/miniconda3/lib/python3.13/site-packages/boltons/formatutils.py b/miniconda3/lib/python3.13/site-packages/boltons/formatutils.py new file mode 100644 index 0000000000000000000000000000000000000000..303403493c2421f5950285b012f777e3742ec463 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/formatutils.py @@ -0,0 +1,356 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""`PEP 3101`_ introduced the :meth:`str.format` method, and what +would later be called "new-style" string formatting. For the sake of +explicit correctness, it is probably best to refer to Python's dual +string formatting capabilities as *bracket-style* and +*percent-style*. There is overlap, but one does not replace the +other. + + * Bracket-style is more pluggable, slower, and uses a method. + * Percent-style is simpler, faster, and uses an operator. + +Bracket-style formatting brought with it a much more powerful toolbox, +but it was far from a full one. :meth:`str.format` uses `more powerful +syntax`_, but `the tools and idioms`_ for working with +that syntax are not well-developed nor well-advertised. + +``formatutils`` adds several functions for working with bracket-style +format strings: + + * :class:`DeferredValue`: Defer fetching or calculating a value + until format time. + * :func:`get_format_args`: Parse the positional and keyword + arguments out of a format string. + * :func:`tokenize_format_str`: Tokenize a format string into + literals and :class:`BaseFormatField` objects. + * :func:`construct_format_field_str`: Assists in programmatic + construction of format strings. + * :func:`infer_positional_format_args`: Converts anonymous + references in 2.7+ format strings to explicit positional arguments + suitable for usage with Python 2.6. + +.. _more powerful syntax: https://docs.python.org/2/library/string.html#format-string-syntax +.. _the tools and idioms: https://docs.python.org/2/library/string.html#string-formatting +.. _PEP 3101: https://www.python.org/dev/peps/pep-3101/ +""" +# TODO: also include percent-formatting utils? +# TODO: include lithoxyl.formatters.Formatter (or some adaptation)? + + +import re +from string import Formatter + +__all__ = ['DeferredValue', 'get_format_args', 'tokenize_format_str', + 'construct_format_field_str', 'infer_positional_format_args', + 'BaseFormatField'] + + +_pos_farg_re = re.compile('({{)|' # escaped open-brace + '(}})|' # escaped close-brace + r'({[:!.\[}])') # anon positional format arg + + +def construct_format_field_str(fname, fspec, conv): + """ + Constructs a format field string from the field name, spec, and + conversion character (``fname``, ``fspec``, ``conv``). See Python + String Formatting for more info. + """ + if fname is None: + return '' + ret = '{' + fname + if conv: + ret += '!' + conv + if fspec: + ret += ':' + fspec + ret += '}' + return ret + + +def split_format_str(fstr): + """Does very basic splitting of a format string, returns a list of + strings. For full tokenization, see :func:`tokenize_format_str`. + + """ + ret = [] + + for lit, fname, fspec, conv in Formatter().parse(fstr): + if fname is None: + ret.append((lit, None)) + continue + field_str = construct_format_field_str(fname, fspec, conv) + ret.append((lit, field_str)) + return ret + + +def infer_positional_format_args(fstr): + """Takes format strings with anonymous positional arguments, (e.g., + "{}" and {:d}), and converts them into numbered ones for explicitness and + compatibility with 2.6. + + Returns a string with the inferred positional arguments. + """ + # TODO: memoize + ret, max_anon = '', 0 + # look for {: or {! or {. or {[ or {} + start, end, prev_end = 0, 0, 0 + for match in _pos_farg_re.finditer(fstr): + start, end, group = match.start(), match.end(), match.group() + if prev_end < start: + ret += fstr[prev_end:start] + prev_end = end + if group == '{{' or group == '}}': + ret += group + continue + ret += f'{{{max_anon}{group[1:]}' + max_anon += 1 + ret += fstr[prev_end:] + return ret + + +# This approach is hardly exhaustive but it works for most builtins +_INTCHARS = 'bcdoxXn' +_FLOATCHARS = 'eEfFgGn%' +_TYPE_MAP = dict([(x, int) for x in _INTCHARS] + + [(x, float) for x in _FLOATCHARS]) +_TYPE_MAP['s'] = str + + +def get_format_args(fstr): + """ + Turn a format string into two lists of arguments referenced by the + format string. One is positional arguments, and the other is named + arguments. Each element of the list includes the name and the + nominal type of the field. + + # >>> get_format_args("{noun} is {1:d} years old{punct}") + # ([(1, )], [('noun', ), ('punct', )]) + + # XXX: Py3k + >>> get_format_args("{noun} is {1:d} years old{punct}") == \ + ([(1, int)], [('noun', str), ('punct', str)]) + True + """ + # TODO: memoize + formatter = Formatter() + fargs, fkwargs, _dedup = [], [], set() + + def _add_arg(argname, type_char='s'): + if argname not in _dedup: + _dedup.add(argname) + argtype = _TYPE_MAP.get(type_char, str) # TODO: unicode + try: + fargs.append((int(argname), argtype)) + except ValueError: + fkwargs.append((argname, argtype)) + + for lit, fname, fspec, conv in formatter.parse(fstr): + if fname is not None: + type_char = fspec[-1:] + fname_list = re.split('[.[]', fname) + if len(fname_list) > 1: + raise ValueError('encountered compound format arg: %r' % fname) + try: + base_fname = fname_list[0] + assert base_fname + except (IndexError, AssertionError): + raise ValueError('encountered anonymous positional argument') + _add_arg(fname, type_char) + for sublit, subfname, _, _ in formatter.parse(fspec): + # TODO: positional and anon args not allowed here. + if subfname is not None: + _add_arg(subfname) + return fargs, fkwargs + + +def tokenize_format_str(fstr, resolve_pos=True): + """Takes a format string, turns it into a list of alternating string + literals and :class:`BaseFormatField` tokens. By default, also + infers anonymous positional references into explicit, numbered + positional references. To disable this behavior set *resolve_pos* + to ``False``. + """ + ret = [] + if resolve_pos: + fstr = infer_positional_format_args(fstr) + formatter = Formatter() + for lit, fname, fspec, conv in formatter.parse(fstr): + if lit: + ret.append(lit) + if fname is None: + continue + ret.append(BaseFormatField(fname, fspec, conv)) + return ret + + +class BaseFormatField: + """A class representing a reference to an argument inside of a + bracket-style format string. For instance, in ``"{greeting}, + world!"``, there is a field named "greeting". + + These fields can have many options applied to them. See the + Python docs on `Format String Syntax`_ for the full details. + + .. _Format String Syntax: https://docs.python.org/2/library/string.html#string-formatting + """ + def __init__(self, fname, fspec='', conv=None): + self.set_fname(fname) + self.set_fspec(fspec) + self.set_conv(conv) + + def set_fname(self, fname): + "Set the field name." + + path_list = re.split('[.[]', fname) # TODO + + self.base_name = path_list[0] + self.fname = fname + self.subpath = path_list[1:] + self.is_positional = not self.base_name or self.base_name.isdigit() + + def set_fspec(self, fspec): + "Set the field spec." + fspec = fspec or '' + subfields = [] + for sublit, subfname, _, _ in Formatter().parse(fspec): + if subfname is not None: + subfields.append(subfname) + self.subfields = subfields + self.fspec = fspec + self.type_char = fspec[-1:] + self.type_func = _TYPE_MAP.get(self.type_char, str) + + def set_conv(self, conv): + """There are only two built-in converters: ``s`` and ``r``. They are + somewhat rare and appearlike ``"{ref!r}"``.""" + # TODO + self.conv = conv + self.conv_func = None # TODO + + @property + def fstr(self): + "The current state of the field in string format." + return construct_format_field_str(self.fname, self.fspec, self.conv) + + def __repr__(self): + cn = self.__class__.__name__ + args = [self.fname] + if self.conv is not None: + args.extend([self.fspec, self.conv]) + elif self.fspec != '': + args.append(self.fspec) + args_repr = ', '.join([repr(a) for a in args]) + return f'{cn}({args_repr})' + + def __str__(self): + return self.fstr + + +_UNSET = object() + + +class DeferredValue: + """:class:`DeferredValue` is a wrapper type, used to defer computing + values which would otherwise be expensive to stringify and + format. This is most valuable in areas like logging, where one + would not want to waste time formatting a value for a log message + which will subsequently be filtered because the message's log + level was DEBUG and the logger was set to only emit CRITICAL + messages. + + The :class:``DeferredValue`` is initialized with a callable that + takes no arguments and returns the value, which can be of any + type. By default DeferredValue only calls that callable once, and + future references will get a cached value. This behavior can be + disabled by setting *cache_value* to ``False``. + + Args: + + func (function): A callable that takes no arguments and + computes the value being represented. + cache_value (bool): Whether subsequent usages will call *func* + again. Defaults to ``True``. + + >>> import sys + >>> dv = DeferredValue(lambda: len(sys._current_frames())) + >>> output = "works great in all {0} threads!".format(dv) + + PROTIP: To keep lines shorter, use: ``from formatutils import + DeferredValue as DV`` + """ + def __init__(self, func, cache_value=True): + self.func = func + self.cache_value = cache_value + self._value = _UNSET + + def get_value(self): + """Computes, optionally caches, and returns the value of the + *func*. If ``get_value()`` has been called before, a cached + value may be returned depending on the *cache_value* option + passed to the constructor. + """ + if self._value is not _UNSET and self.cache_value: + value = self._value + else: + value = self.func() + if self.cache_value: + self._value = value + return value + + def __int__(self): + return int(self.get_value()) + + def __float__(self): + return float(self.get_value()) + + def __str__(self): + return str(self.get_value()) + + def __unicode__(self): + return str(self.get_value()) + + def __repr__(self): + return repr(self.get_value()) + + def __format__(self, fmt): + value = self.get_value() + + pt = fmt[-1:] # presentation type + type_conv = _TYPE_MAP.get(pt, str) + + try: + return value.__format__(fmt) + except (ValueError, TypeError): + # TODO: this may be overkill + return type_conv(value).__format__(fmt) + +# end formatutils.py diff --git a/miniconda3/lib/python3.13/site-packages/boltons/funcutils.py b/miniconda3/lib/python3.13/site-packages/boltons/funcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..0bdc28e9bf54bef76741eae72ae838517e0a87d9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/funcutils.py @@ -0,0 +1,1007 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's built-in :mod:`functools` module builds several useful +utilities on top of Python's first-class function +support. ``funcutils`` generally stays in the same vein, adding to and +correcting Python's standard metaprogramming facilities. +""" + +import sys +import re +import inspect +import functools +import itertools +from inspect import formatannotation +from types import FunctionType, MethodType + +# For legacy compatibility. +# boltons used to offer an implementation of total_ordering for Python <2.7 +from functools import total_ordering as total_ordering + +try: + from .typeutils import make_sentinel + NO_DEFAULT = make_sentinel(var_name='NO_DEFAULT') +except ImportError: + NO_DEFAULT = object() + + +def inspect_formatargspec( + args, varargs=None, varkw=None, defaults=None, + kwonlyargs=(), kwonlydefaults={}, annotations={}, + formatarg=str, + formatvarargs=lambda name: '*' + name, + formatvarkw=lambda name: '**' + name, + formatvalue=lambda value: '=' + repr(value), + formatreturns=lambda text: ' -> ' + text, + formatannotation=formatannotation): + """Copy formatargspec from python 3.7 standard library. + Python 3 has deprecated formatargspec and requested that Signature + be used instead, however this requires a full reimplementation + of formatargspec() in terms of creating Parameter objects and such. + Instead of introducing all the object-creation overhead and having + to reinvent from scratch, just copy their compatibility routine. + """ + + def formatargandannotation(arg): + result = formatarg(arg) + if arg in annotations: + result += ': ' + formatannotation(annotations[arg]) + return result + specs = [] + if defaults: + firstdefault = len(args) - len(defaults) + for i, arg in enumerate(args): + spec = formatargandannotation(arg) + if defaults and i >= firstdefault: + spec = spec + formatvalue(defaults[i - firstdefault]) + specs.append(spec) + if varargs is not None: + specs.append(formatvarargs(formatargandannotation(varargs))) + else: + if kwonlyargs: + specs.append('*') + if kwonlyargs: + for kwonlyarg in kwonlyargs: + spec = formatargandannotation(kwonlyarg) + if kwonlydefaults and kwonlyarg in kwonlydefaults: + spec += formatvalue(kwonlydefaults[kwonlyarg]) + specs.append(spec) + if varkw is not None: + specs.append(formatvarkw(formatargandannotation(varkw))) + result = '(' + ', '.join(specs) + ')' + if 'return' in annotations: + result += formatreturns(formatannotation(annotations['return'])) + return result + + +def get_module_callables(mod, ignore=None): + """Returns two maps of (*types*, *funcs*) from *mod*, optionally + ignoring based on the :class:`bool` return value of the *ignore* + callable. *mod* can be a string name of a module in + :data:`sys.modules` or the module instance itself. + """ + if isinstance(mod, str): + mod = sys.modules[mod] + types, funcs = {}, {} + for attr_name in dir(mod): + if ignore and ignore(attr_name): + continue + try: + attr = getattr(mod, attr_name) + except Exception: + continue + try: + attr_mod_name = attr.__module__ + except AttributeError: + continue + if attr_mod_name != mod.__name__: + continue + if isinstance(attr, type): + types[attr_name] = attr + elif callable(attr): + funcs[attr_name] = attr + return types, funcs + + +def mro_items(type_obj): + """Takes a type and returns an iterator over all class variables + throughout the type hierarchy (respecting the MRO). + + >>> sorted(set([k for k, v in mro_items(int) if not k.startswith('__') and 'bytes' not in k and not callable(v)])) + ['denominator', 'imag', 'numerator', 'real'] + """ + # TODO: handle slots? + return itertools.chain.from_iterable(ct.__dict__.items() + for ct in type_obj.__mro__) + + +def dir_dict(obj, raise_exc=False): + """Return a dictionary of attribute names to values for a given + object. Unlike ``obj.__dict__``, this function returns all + attributes on the object, including ones on parent classes. + """ + # TODO: separate function for handling descriptors on types? + ret = {} + for k in dir(obj): + try: + ret[k] = getattr(obj, k) + except Exception: + if raise_exc: + raise + return ret + + +def copy_function(orig, copy_dict=True): + """Returns a shallow copy of the function, including code object, + globals, closure, etc. + + >>> func = lambda: func + >>> func() is func + True + >>> func_copy = copy_function(func) + >>> func_copy() is func + True + >>> func_copy is not func + True + + Args: + orig (function): The function to be copied. Must be a + function, not just any method or callable. + copy_dict (bool): Also copy any attributes set on the function + instance. Defaults to ``True``. + """ + ret = FunctionType(orig.__code__, + orig.__globals__, + name=orig.__name__, + argdefs=getattr(orig, "__defaults__", None), + closure=getattr(orig, "__closure__", None)) + if hasattr(orig, "__kwdefaults__"): + ret.__kwdefaults__ = orig.__kwdefaults__ + if copy_dict: + ret.__dict__.update(orig.__dict__) + return ret + + +def partial_ordering(cls): + """Class decorator, similar to :func:`functools.total_ordering`, + except it is used to define `partial orderings`_ (i.e., it is + possible that *x* is neither greater than, equal to, or less than + *y*). It assumes the presence of the ``__le__()`` and ``__ge__()`` + method, but nothing else. It will not override any existing + additional comparison methods. + + .. _partial orderings: https://en.wikipedia.org/wiki/Partially_ordered_set + + >>> @partial_ordering + ... class MySet(set): + ... def __le__(self, other): + ... return self.issubset(other) + ... def __ge__(self, other): + ... return self.issuperset(other) + ... + >>> a = MySet([1,2,3]) + >>> b = MySet([1,2]) + >>> c = MySet([1,2,4]) + >>> b < a + True + >>> b > a + False + >>> b < c + True + >>> a < c + False + >>> c > a + False + """ + def __lt__(self, other): return self <= other and not self >= other + def __gt__(self, other): return self >= other and not self <= other + def __eq__(self, other): return self >= other and self <= other + + if not hasattr(cls, '__lt__'): cls.__lt__ = __lt__ + if not hasattr(cls, '__gt__'): cls.__gt__ = __gt__ + if not hasattr(cls, '__eq__'): cls.__eq__ = __eq__ + + return cls + + +class InstancePartial(functools.partial): + """:class:`functools.partial` is a huge convenience for anyone + working with Python's great first-class functions. It allows + developers to curry arguments and incrementally create simpler + callables for a variety of use cases. + + Unfortunately there's one big gap in its usefulness: + methods. Partials just don't get bound as methods and + automatically handed a reference to ``self``. The + ``InstancePartial`` type remedies this by inheriting from + :class:`functools.partial` and implementing the necessary + descriptor protocol. There are no other differences in + implementation or usage. :class:`CachedInstancePartial`, below, + has the same ability, but is slightly more efficient. + + """ + @property + def _partialmethod(self): + # py3.13 switched from _partialmethod to __partialmethod__, this is kept for backwards compat <=py3.12 + return self.__partialmethod__ + + @property + def __partialmethod__(self): + return functools.partialmethod(self.func, *self.args, **self.keywords) + + def __get__(self, obj, obj_type): + return MethodType(self, obj) + + + +class CachedInstancePartial(functools.partial): + """The ``CachedInstancePartial`` is virtually the same as + :class:`InstancePartial`, adding support for method-usage to + :class:`functools.partial`, except that upon first access, it + caches the bound method on the associated object, speeding it up + for future accesses, and bringing the method call overhead to + about the same as non-``partial`` methods. + + See the :class:`InstancePartial` docstring for more details. + """ + @property + def _partialmethod(self): + # py3.13 switched from _partialmethod to __partialmethod__, this is kept for backwards compat <=py3.12 + return self.__partialmethod__ + + @property + def __partialmethod__(self): + return functools.partialmethod(self.func, *self.args, **self.keywords) + + def __set_name__(self, obj_type, name): + self.__name__ = name + + def __get__(self, obj, obj_type): + # These assignments could've been in __init__, but there was + # no simple way to do it without breaking one of PyPy or Py3. + self.__name__ = getattr(self, "__name__", None) + self.__doc__ = self.func.__doc__ + self.__module__ = self.func.__module__ + + name = self.__name__ + + if obj is None: + return MethodType(self, obj) + try: + # since this is a data descriptor, this block + # is probably only hit once (per object) + return obj.__dict__[name] + except KeyError: + obj.__dict__[name] = ret = MethodType(self, obj) + return ret + + +partial = CachedInstancePartial + + +def format_invocation(name='', args=(), kwargs=None, **kw): + """Given a name, positional arguments, and keyword arguments, format + a basic Python-style function call. + + >>> print(format_invocation('func', args=(1, 2), kwargs={'c': 3})) + func(1, 2, c=3) + >>> print(format_invocation('a_func', args=(1,))) + a_func(1) + >>> print(format_invocation('kw_func', kwargs=[('a', 1), ('b', 2)])) + kw_func(a=1, b=2) + + """ + _repr = kw.pop('repr', repr) + if kw: + raise TypeError('unexpected keyword args: %r' % ', '.join(kw.keys())) + kwargs = kwargs or {} + a_text = ', '.join([_repr(a) for a in args]) + if isinstance(kwargs, dict): + kwarg_items = [(k, kwargs[k]) for k in sorted(kwargs)] + else: + kwarg_items = kwargs + kw_text = ', '.join([f'{k}={_repr(v)}' for k, v in kwarg_items]) + + all_args_text = a_text + if all_args_text and kw_text: + all_args_text += ', ' + all_args_text += kw_text + + return f'{name}({all_args_text})' + + +def format_exp_repr(obj, pos_names, req_names=None, opt_names=None, opt_key=None): + """Render an expression-style repr of an object, based on attribute + names, which are assumed to line up with arguments to an initializer. + + >>> class Flag(object): + ... def __init__(self, length, width, depth=None): + ... self.length = length + ... self.width = width + ... self.depth = depth + ... + + That's our Flag object, here are some example reprs for it: + + >>> flag = Flag(5, 10) + >>> print(format_exp_repr(flag, ['length', 'width'], [], ['depth'])) + Flag(5, 10) + >>> flag2 = Flag(5, 15, 2) + >>> print(format_exp_repr(flag2, ['length'], ['width', 'depth'])) + Flag(5, width=15, depth=2) + + By picking the pos_names, req_names, opt_names, and opt_key, you + can fine-tune how you want the repr to look. + + Args: + obj (object): The object whose type name will be used and + attributes will be checked + pos_names (list): Required list of attribute names which will be + rendered as positional arguments in the output repr. + req_names (list): List of attribute names which will always + appear in the keyword arguments in the output repr. Defaults to None. + opt_names (list): List of attribute names which may appear in + the keyword arguments in the output repr, provided they pass + the *opt_key* check. Defaults to None. + opt_key (callable): A function or callable which checks whether + an opt_name should be in the repr. Defaults to a + ``None``-check. + + """ + cn = type(obj).__name__ + req_names = req_names or [] + opt_names = opt_names or [] + uniq_names, all_names = set(), [] + for name in req_names + opt_names: + if name in uniq_names: + continue + uniq_names.add(name) + all_names.append(name) + + if opt_key is None: + opt_key = lambda v: v is None + assert callable(opt_key) + + args = [getattr(obj, name, None) for name in pos_names] + + kw_items = [(name, getattr(obj, name, None)) for name in all_names] + kw_items = [(name, val) for name, val in kw_items + if not (name in opt_names and opt_key(val))] + + return format_invocation(cn, args, kw_items) + + +def format_nonexp_repr(obj, req_names=None, opt_names=None, opt_key=None): + """Format a non-expression-style repr + + Some object reprs look like object instantiation, e.g., App(r=[], mw=[]). + + This makes sense for smaller, lower-level objects whose state + roundtrips. But a lot of objects contain values that don't + roundtrip, like types and functions. + + For those objects, there is the non-expression style repr, which + mimic's Python's default style to make a repr like so: + + >>> class Flag(object): + ... def __init__(self, length, width, depth=None): + ... self.length = length + ... self.width = width + ... self.depth = depth + ... + >>> flag = Flag(5, 10) + >>> print(format_nonexp_repr(flag, ['length', 'width'], ['depth'])) + + + If no attributes are specified or set, utilizes the id, not unlike Python's + built-in behavior. + + >>> print(format_nonexp_repr(flag)) + + """ + cn = obj.__class__.__name__ + req_names = req_names or [] + opt_names = opt_names or [] + uniq_names, all_names = set(), [] + for name in req_names + opt_names: + if name in uniq_names: + continue + uniq_names.add(name) + all_names.append(name) + + if opt_key is None: + opt_key = lambda v: v is None + assert callable(opt_key) + + items = [(name, getattr(obj, name, None)) for name in all_names] + labels = [f'{name}={val!r}' for name, val in items + if not (name in opt_names and opt_key(val))] + if not labels: + labels = ['id=%s' % id(obj)] + ret = '<{} {}>'.format(cn, ' '.join(labels)) + return ret + + + +# # # +# # # Function builder +# # # + + +def wraps(func, injected=None, expected=None, **kw): + """Decorator factory to apply update_wrapper() to a wrapper function. + + Modeled after built-in :func:`functools.wraps`. Returns a decorator + that invokes update_wrapper() with the decorated function as the wrapper + argument and the arguments to wraps() as the remaining arguments. + Default arguments are as for update_wrapper(). This is a convenience + function to simplify applying partial() to update_wrapper(). + + Same example as in update_wrapper's doc but with wraps: + + >>> from boltons.funcutils import wraps + >>> + >>> def print_return(func): + ... @wraps(func) + ... def wrapper(*args, **kwargs): + ... ret = func(*args, **kwargs) + ... print(ret) + ... return ret + ... return wrapper + ... + >>> @print_return + ... def example(): + ... '''docstring''' + ... return 'example return value' + >>> + >>> val = example() + example return value + >>> example.__name__ + 'example' + >>> example.__doc__ + 'docstring' + """ + return partial(update_wrapper, func=func, build_from=None, + injected=injected, expected=expected, **kw) + + +def update_wrapper(wrapper, func, injected=None, expected=None, build_from=None, **kw): + """Modeled after the built-in :func:`functools.update_wrapper`, + this function is used to make your wrapper function reflect the + wrapped function's: + + * Name + * Documentation + * Module + * Signature + + The built-in :func:`functools.update_wrapper` copies the first three, but + does not copy the signature. This version of ``update_wrapper`` can copy + the inner function's signature exactly, allowing seamless usage + and :mod:`introspection `. Usage is identical to the + built-in version:: + + >>> from boltons.funcutils import update_wrapper + >>> + >>> def print_return(func): + ... def wrapper(*args, **kwargs): + ... ret = func(*args, **kwargs) + ... print(ret) + ... return ret + ... return update_wrapper(wrapper, func) + ... + >>> @print_return + ... def example(): + ... '''docstring''' + ... return 'example return value' + >>> + >>> val = example() + example return value + >>> example.__name__ + 'example' + >>> example.__doc__ + 'docstring' + + In addition, the boltons version of update_wrapper supports + modifying the outer signature. By passing a list of + *injected* argument names, those arguments will be removed from + the outer wrapper's signature, allowing your decorator to provide + arguments that aren't passed in. + + Args: + + wrapper (function) : The callable to which the attributes of + *func* are to be copied. + func (function): The callable whose attributes are to be copied. + injected (list): An optional list of argument names which + should not appear in the new wrapper's signature. + expected (list): An optional list of argument names (or (name, + default) pairs) representing new arguments introduced by + the wrapper (the opposite of *injected*). See + :meth:`FunctionBuilder.add_arg()` for more details. + build_from (function): The callable from which the new wrapper + is built. Defaults to *func*, unless *wrapper* is partial object + built from *func*, in which case it defaults to *wrapper*. + Useful in some specific cases where *wrapper* and *func* have the + same arguments but differ on which are keyword-only and positional-only. + update_dict (bool): Whether to copy other, non-standard + attributes of *func* over to the wrapper. Defaults to True. + inject_to_varkw (bool): Ignore missing arguments when a + ``**kwargs``-type catch-all is present. Defaults to True. + hide_wrapped (bool): Remove reference to the wrapped function(s) + in the updated function. + + In opposition to the built-in :func:`functools.update_wrapper` bolton's + version returns a copy of the function and does not modify anything in place. + For more in-depth wrapping of functions, see the + :class:`FunctionBuilder` type, on which update_wrapper was built. + """ + if injected is None: + injected = [] + elif isinstance(injected, str): + injected = [injected] + else: + injected = list(injected) + + expected_items = _parse_wraps_expected(expected) + + if isinstance(func, (classmethod, staticmethod)): + raise TypeError('wraps does not support wrapping classmethods and' + ' staticmethods, change the order of wrapping to' + ' wrap the underlying function: %r' + % (getattr(func, '__func__', None),)) + + update_dict = kw.pop('update_dict', True) + inject_to_varkw = kw.pop('inject_to_varkw', True) + hide_wrapped = kw.pop('hide_wrapped', False) + if kw: + raise TypeError('unexpected kwargs: %r' % kw.keys()) + + if isinstance(wrapper, functools.partial) and func is wrapper.func: + build_from = build_from or wrapper + + fb = FunctionBuilder.from_func(build_from or func) + + for arg in injected: + try: + fb.remove_arg(arg) + except MissingArgument: + if inject_to_varkw and fb.varkw is not None: + continue # keyword arg will be caught by the varkw + raise + + for arg, default in expected_items: + fb.add_arg(arg, default) # may raise ExistingArgument + + if fb.is_async: + fb.body = 'return await _call(%s)' % fb.get_invocation_str() + else: + fb.body = 'return _call(%s)' % fb.get_invocation_str() + + execdict = dict(_call=wrapper, _func=func) + fully_wrapped = fb.get_func(execdict, with_dict=update_dict) + + if hide_wrapped and hasattr(fully_wrapped, '__wrapped__'): + del fully_wrapped.__dict__['__wrapped__'] + elif not hide_wrapped: + fully_wrapped.__wrapped__ = func # ref to the original function (#115) + + return fully_wrapped + + +def _parse_wraps_expected(expected): + # expected takes a pretty powerful argument, it's processed + # here. admittedly this would be less trouble if I relied on + # OrderedDict (there's an impl of that in the commit history if + # you look + if expected is None: + expected = [] + elif isinstance(expected, str): + expected = [(expected, NO_DEFAULT)] + + expected_items = [] + try: + expected_iter = iter(expected) + except TypeError as e: + raise ValueError('"expected" takes string name, sequence of string names,' + ' iterable of (name, default) pairs, or a mapping of ' + ' {name: default}, not %r (got: %r)' % (expected, e)) + for argname in expected_iter: + if isinstance(argname, str): + # dict keys and bare strings + try: + default = expected[argname] + except TypeError: + default = NO_DEFAULT + else: + # pairs + try: + argname, default = argname + except (TypeError, ValueError): + raise ValueError('"expected" takes string name, sequence of string names,' + ' iterable of (name, default) pairs, or a mapping of ' + ' {name: default}, not %r') + if not isinstance(argname, str): + raise ValueError(f'all "expected" argnames must be strings, not {argname!r}') + + expected_items.append((argname, default)) + + return expected_items + + +class FunctionBuilder: + """The FunctionBuilder type provides an interface for programmatically + creating new functions, either based on existing functions or from + scratch. + + Values are passed in at construction or set as attributes on the + instance. For creating a new function based of an existing one, + see the :meth:`~FunctionBuilder.from_func` classmethod. At any + point, :meth:`~FunctionBuilder.get_func` can be called to get a + newly compiled function, based on the values configured. + + >>> fb = FunctionBuilder('return_five', doc='returns the integer 5', + ... body='return 5') + >>> f = fb.get_func() + >>> f() + 5 + >>> fb.varkw = 'kw' + >>> f_kw = fb.get_func() + >>> f_kw(ignored_arg='ignored_val') + 5 + + Note that function signatures themselves changed quite a bit in + Python 3, so several arguments are only applicable to + FunctionBuilder in Python 3. Except for *name*, all arguments to + the constructor are keyword arguments. + + Args: + name (str): Name of the function. + doc (str): `Docstring`_ for the function, defaults to empty. + module (str): Name of the module from which this function was + imported. Defaults to None. + body (str): String version of the code representing the body + of the function. Defaults to ``'pass'``, which will result + in a function which does nothing and returns ``None``. + args (list): List of argument names, defaults to empty list, + denoting no arguments. + varargs (str): Name of the catch-all variable for positional + arguments. E.g., "args" if the resultant function is to have + ``*args`` in the signature. Defaults to None. + varkw (str): Name of the catch-all variable for keyword + arguments. E.g., "kwargs" if the resultant function is to have + ``**kwargs`` in the signature. Defaults to None. + defaults (tuple): A tuple containing default argument values for + those arguments that have defaults. + kwonlyargs (list): Argument names which are only valid as + keyword arguments. **Python 3 only.** + kwonlydefaults (dict): A mapping, same as normal *defaults*, + but only for the *kwonlyargs*. **Python 3 only.** + annotations (dict): Mapping of type hints and so + forth. **Python 3 only.** + filename (str): The filename that will appear in + tracebacks. Defaults to "boltons.funcutils.FunctionBuilder". + indent (int): Number of spaces with which to indent the + function *body*. Values less than 1 will result in an error. + dict (dict): Any other attributes which should be added to the + functions compiled with this FunctionBuilder. + + All of these arguments are also made available as attributes which + can be mutated as necessary. + + .. _Docstring: https://en.wikipedia.org/wiki/Docstring#Python + + """ + + _argspec_defaults = {'args': list, + 'varargs': lambda: None, + 'varkw': lambda: None, + 'defaults': lambda: None, + 'kwonlyargs': list, + 'kwonlydefaults': dict, + 'annotations': dict} + + @classmethod + def _argspec_to_dict(cls, f): + argspec = inspect.getfullargspec(f) + return {attr: getattr(argspec, attr) + for attr in cls._argspec_defaults} + + _defaults = {'doc': str, + 'dict': dict, + 'is_async': lambda: False, + 'module': lambda: None, + 'body': lambda: 'pass', + 'indent': lambda: 4, + "annotations": dict, + 'filename': lambda: 'boltons.funcutils.FunctionBuilder'} + + _defaults.update(_argspec_defaults) + + _compile_count = itertools.count() + + def __init__(self, name, **kw): + self.name = name + for a, default_factory in self._defaults.items(): + val = kw.pop(a, None) + if val is None: + val = default_factory() + setattr(self, a, val) + + if kw: + raise TypeError('unexpected kwargs: %r' % kw.keys()) + return + + # def get_argspec(self): # TODO + + def get_sig_str(self, with_annotations=True): + """Return function signature as a string. + + with_annotations is ignored on Python 2. On Python 3 signature + will omit annotations if it is set to False. + """ + if with_annotations: + annotations = self.annotations + else: + annotations = {} + + return inspect_formatargspec(self.args, + self.varargs, + self.varkw, + [], + self.kwonlyargs, + {}, + annotations) + + _KWONLY_MARKER = re.compile(r""" + \* # a star + \s* # followed by any amount of whitespace + , # followed by a comma + \s* # followed by any amount of whitespace + """, re.VERBOSE) + + def get_invocation_str(self): + kwonly_pairs = None + formatters = {} + if self.kwonlyargs: + kwonly_pairs = {arg: arg + for arg in self.kwonlyargs} + formatters['formatvalue'] = lambda value: '=' + value + + sig = inspect_formatargspec(self.args, + self.varargs, + self.varkw, + [], + kwonly_pairs, + kwonly_pairs, + {}, + **formatters) + sig = self._KWONLY_MARKER.sub('', sig) + return sig[1:-1] + + @classmethod + def from_func(cls, func): + """Create a new FunctionBuilder instance based on an existing + function. The original function will not be stored or + modified. + """ + # TODO: copy_body? gonna need a good signature regex. + # TODO: might worry about __closure__? + if not callable(func): + raise TypeError(f'expected callable object, not {func!r}') + + if isinstance(func, functools.partial): + kwargs = {'name': func.func.__name__, + 'doc': func.func.__doc__, + 'module': getattr(func.func, '__module__', None), # e.g., method_descriptor + 'annotations': getattr(func.func, "__annotations__", {}), + 'dict': getattr(func.func, '__dict__', {})} + else: + kwargs = {'name': func.__name__, + 'doc': func.__doc__, + 'module': getattr(func, '__module__', None), # e.g., method_descriptor + 'annotations': getattr(func, "__annotations__", {}), + 'dict': getattr(func, '__dict__', {})} + + kwargs.update(cls._argspec_to_dict(func)) + + if inspect.iscoroutinefunction(func): + kwargs['is_async'] = True + + return cls(**kwargs) + + def get_func(self, execdict=None, add_source=True, with_dict=True): + """Compile and return a new function based on the current values of + the FunctionBuilder. + + Args: + execdict (dict): The dictionary representing the scope in + which the compilation should take place. Defaults to an empty + dict. + add_source (bool): Whether to add the source used to a + special ``__source__`` attribute on the resulting + function. Defaults to True. + with_dict (bool): Add any custom attributes, if + applicable. Defaults to True. + + To see an example of usage, see the implementation of + :func:`~boltons.funcutils.wraps`. + """ + execdict = execdict or {} + body = self.body or self._default_body + + tmpl = 'def {name}{sig_str}:' + tmpl += '\n{body}' + + if self.is_async: + tmpl = 'async ' + tmpl + + body = _indent(self.body, ' ' * self.indent) + + name = self.name.replace('<', '_').replace('>', '_') # lambdas + src = tmpl.format(name=name, sig_str=self.get_sig_str(with_annotations=False), + doc=self.doc, body=body) + self._compile(src, execdict) + func = execdict[name] + + func.__name__ = self.name + func.__doc__ = self.doc + func.__defaults__ = self.defaults + func.__kwdefaults__ = self.kwonlydefaults + func.__annotations__ = self.annotations + + if with_dict: + func.__dict__.update(self.dict) + func.__module__ = self.module + # TODO: caller module fallback? + + if add_source: + func.__source__ = src + + return func + + def get_defaults_dict(self): + """Get a dictionary of function arguments with defaults and the + respective values. + """ + ret = dict(reversed(list(zip(reversed(self.args), + reversed(self.defaults or []))))) + kwonlydefaults = getattr(self, 'kwonlydefaults', None) + if kwonlydefaults: + ret.update(kwonlydefaults) + return ret + + def get_arg_names(self, only_required=False): + arg_names = tuple(self.args) + tuple(getattr(self, 'kwonlyargs', ())) + if only_required: + defaults_dict = self.get_defaults_dict() + arg_names = tuple([an for an in arg_names if an not in defaults_dict]) + return arg_names + + def add_arg(self, arg_name, default=NO_DEFAULT, kwonly=False): + """Add an argument with optional *default* (defaults to + ``funcutils.NO_DEFAULT``). Pass *kwonly=True* to add a + keyword-only argument + """ + if arg_name in self.args: + raise ExistingArgument(f'arg {arg_name!r} already in func {self.name} arg list') + if arg_name in self.kwonlyargs: + raise ExistingArgument(f'arg {arg_name!r} already in func {self.name} kwonly arg list') + if not kwonly: + self.args.append(arg_name) + if default is not NO_DEFAULT: + self.defaults = (self.defaults or ()) + (default,) + else: + self.kwonlyargs.append(arg_name) + if default is not NO_DEFAULT: + self.kwonlydefaults[arg_name] = default + + def remove_arg(self, arg_name): + """Remove an argument from this FunctionBuilder's argument list. The + resulting function will have one less argument per call to + this function. + + Args: + arg_name (str): The name of the argument to remove. + + Raises a :exc:`ValueError` if the argument is not present. + + """ + args = self.args + d_dict = self.get_defaults_dict() + try: + args.remove(arg_name) + except ValueError: + try: + self.kwonlyargs.remove(arg_name) + except (AttributeError, ValueError): + # missing from both + exc = MissingArgument('arg %r not found in %s argument list:' + ' %r' % (arg_name, self.name, args)) + exc.arg_name = arg_name + raise exc + else: + self.kwonlydefaults.pop(arg_name, None) + else: + d_dict.pop(arg_name, None) + self.defaults = tuple([d_dict[a] for a in args if a in d_dict]) + return + + def _compile(self, src, execdict): + + filename = ('<%s-%d>' + % (self.filename, next(self._compile_count),)) + try: + code = compile(src, filename, 'single') + exec(code, execdict) + except Exception: + raise + return execdict + + +class MissingArgument(ValueError): + pass + + +class ExistingArgument(ValueError): + pass + + +def _indent(text, margin, newline='\n', key=bool): + "based on boltons.strutils.indent" + indented_lines = [(margin + line if key(line) else line) + for line in text.splitlines()] + return newline.join(indented_lines) + + +def noop(*args, **kwargs): + """ + Simple function that should be used when no effect is desired. + An alternative to checking for an optional function type parameter. + + e.g. + def decorate(func, pre_func=None, post_func=None): + if pre_func: + pre_func() + func() + if post_func: + post_func() + + vs + + def decorate(func, pre_func=noop, post_func=noop): + pre_func() + func() + post_func() + """ + return None + +# end funcutils.py diff --git a/miniconda3/lib/python3.13/site-packages/boltons/gcutils.py b/miniconda3/lib/python3.13/site-packages/boltons/gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1db18b462ae47ec4a53ba990634d539b1cfe1c8e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/gcutils.py @@ -0,0 +1,164 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""The Python Garbage Collector (`GC`_) doesn't usually get too much +attention, probably because: + + - Python's `reference counting`_ effectively handles the vast majority of + unused objects + - People are slowly learning to avoid implementing `object.__del__()`_ + - The collection itself strikes a good balance between simplicity and + power (`tunable generation sizes`_) + - The collector itself is fast and rarely the cause of long pauses + associated with GC in other runtimes + +Even so, for many applications, the time will come when the developer +will need to track down: + + - Circular references + - Misbehaving objects (locks, ``__del__()``) + - Memory leaks + - Or just ways to shave off a couple percent of execution time + +Thanks to the :mod:`gc` module, the GC is a well-instrumented entry +point for exactly these tasks, and ``gcutils`` aims to facilitate it +further. + +.. _GC: https://docs.python.org/2/glossary.html#term-garbage-collection +.. _reference counting: https://docs.python.org/2/glossary.html#term-reference-count +.. _object.__del__(): https://docs.python.org/2/glossary.html#term-reference-count +.. _tunable generation sizes: https://docs.python.org/2/library/gc.html#gc.set_threshold +""" +# TODO: type survey + + +import gc +import sys + +__all__ = ['get_all', 'GCToggler', 'toggle_gc', 'toggle_gc_postcollect'] + + +def get_all(type_obj, include_subtypes=True): + """Get a list containing all instances of a given type. This will + work for the vast majority of types out there. + + >>> class Ratking(object): pass + >>> wiki, hak, sport = Ratking(), Ratking(), Ratking() + >>> len(get_all(Ratking)) + 3 + + However, there are some exceptions. For example, ``get_all(bool)`` + returns an empty list because ``True`` and ``False`` are + themselves built-in and not tracked. + + >>> get_all(bool) + [] + + Still, it's not hard to see how this functionality can be used to + find all instances of a leaking type and track them down further + using :func:`gc.get_referrers` and :func:`gc.get_referents`. + + ``get_all()`` is optimized such that getting instances of + user-created types is quite fast. Setting *include_subtypes* to + ``False`` will further increase performance in cases where + instances of subtypes aren't required. + + .. note:: + + There are no guarantees about the state of objects returned by + ``get_all()``, especially in concurrent environments. For + instance, it is possible for an object to be in the middle of + executing its ``__init__()`` and be only partially constructed. + """ + # TODO: old-style classes + if not isinstance(type_obj, type): + raise TypeError('expected a type, not %r' % type_obj) + try: + type_is_tracked = gc.is_tracked(type_obj) + except AttributeError: + type_is_tracked = False # Python 2.6 and below don't get the speedup + if type_is_tracked: + to_check = gc.get_referrers(type_obj) + else: + to_check = gc.get_objects() + + if include_subtypes: + ret = [x for x in to_check if isinstance(x, type_obj)] + else: + ret = [x for x in to_check if type(x) is type_obj] + return ret + + +_IS_PYPY = '__pypy__' in sys.builtin_module_names +if _IS_PYPY: + # pypy's gc is just different, y'all + del get_all + + +class GCToggler: + """The ``GCToggler`` is a context-manager that allows one to safely + take more control of your garbage collection schedule. Anecdotal + experience says certain object-creation-heavy tasks see speedups + of around 10% by simply doing one explicit collection at the very + end, especially if most of the objects will stay resident. + + Two GCTogglers are already present in the ``gcutils`` module: + + - :data:`toggle_gc` simply turns off GC at context entrance, and + re-enables at exit + - :data:`toggle_gc_postcollect` does the same, but triggers an + explicit collection after re-enabling. + + >>> with toggle_gc: + ... x = [object() for i in range(1000)] + + Between those two instances, the ``GCToggler`` type probably won't + be used much directly, but is documented for inheritance purposes. + """ + def __init__(self, postcollect=False): + self.postcollect = postcollect + + def __enter__(self): + gc.disable() + + def __exit__(self, exc_type, exc_val, exc_tb): + gc.enable() + if self.postcollect: + gc.collect() + + +toggle_gc = GCToggler() +"""A context manager for disabling GC for a code block. See +:class:`GCToggler` for more details.""" + + +toggle_gc_postcollect = GCToggler(postcollect=True) +"""A context manager for disabling GC for a code block, and collecting +before re-enabling. See :class:`GCToggler` for more details.""" diff --git a/miniconda3/lib/python3.13/site-packages/boltons/ioutils.py b/miniconda3/lib/python3.13/site-packages/boltons/ioutils.py new file mode 100644 index 0000000000000000000000000000000000000000..bfcaf3fc1923eedf788b4fb403d699f7743d8d09 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/ioutils.py @@ -0,0 +1,587 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +# Coding decl above needed for rendering the emdash properly in the +# documentation. + +""" +Module ``ioutils`` implements a number of helper classes and functions which +are useful when dealing with input, output, and bytestreams in a variety of +ways. +""" +import os +from io import BytesIO, IOBase +from abc import ( + ABCMeta, + abstractmethod, + abstractproperty, +) +from errno import EINVAL +from codecs import EncodedFile +from tempfile import TemporaryFile +from itertools import zip_longest + +READ_CHUNK_SIZE = 21333 +""" +Number of bytes to read at a time. The value is ~ 1/3rd of 64k which means that +the value will easily fit in the L2 cache of most processors even if every +codepoint in a string is three bytes long which makes it a nice fast default +value. +""" + + +class SpooledIOBase(IOBase): + """ + A base class shared by the SpooledBytesIO and SpooledStringIO classes. + + The SpooledTemporaryFile class is missing several attributes and methods + present in the StringIO implementation. This brings the api as close to + parity as possible so that classes derived from SpooledIOBase can be used + as near drop-in replacements to save memory. + """ + __metaclass__ = ABCMeta + + def __init__(self, max_size=5000000, dir=None): + self._max_size = max_size + self._dir = dir + + def _checkClosed(self, msg=None): + """Raise a ValueError if file is closed""" + if self.closed: + raise ValueError('I/O operation on closed file.' + if msg is None else msg) + @abstractmethod + def read(self, n=-1): + """Read n characters from the buffer""" + + @abstractmethod + def write(self, s): + """Write into the buffer""" + + @abstractmethod + def seek(self, pos, mode=0): + """Seek to a specific point in a file""" + + @abstractmethod + def readline(self, length=None): + """Returns the next available line""" + + @abstractmethod + def readlines(self, sizehint=0): + """Returns a list of all lines from the current position forward""" + + def writelines(self, lines): + """ + Write lines to the file from an interable. + + NOTE: writelines() does NOT add line separators. + """ + self._checkClosed() + for line in lines: + self.write(line) + + @abstractmethod + def rollover(self): + """Roll file-like-object over into a real temporary file""" + + @abstractmethod + def tell(self): + """Return the current position""" + + @abstractproperty + def buffer(self): + """Should return a flo instance""" + + @abstractproperty + def _rolled(self): + """Returns whether the file has been rolled to a real file or not""" + + @abstractproperty + def len(self): + """Returns the length of the data""" + + def _get_softspace(self): + return self.buffer.softspace + + def _set_softspace(self, val): + self.buffer.softspace = val + + softspace = property(_get_softspace, _set_softspace) + + @property + def _file(self): + return self.buffer + + def close(self): + return self.buffer.close() + + def flush(self): + self._checkClosed() + return self.buffer.flush() + + def isatty(self): + self._checkClosed() + return self.buffer.isatty() + + @property + def closed(self): + return self.buffer.closed + + @property + def pos(self): + return self.tell() + + @property + def buf(self): + return self.getvalue() + + def fileno(self): + self.rollover() + return self.buffer.fileno() + + def truncate(self, size=None): + """ + Truncate the contents of the buffer. + + Custom version of truncate that takes either no arguments (like the + real SpooledTemporaryFile) or a single argument that truncates the + value to a certain index location. + """ + self._checkClosed() + if size is None: + return self.buffer.truncate() + + if size < 0: + raise OSError(EINVAL, "Negative size not allowed") + + # Emulate truncation to a particular location + pos = self.tell() + self.seek(size) + self.buffer.truncate() + if pos < size: + self.seek(pos) + + def getvalue(self): + """Return the entire files contents.""" + self._checkClosed() + pos = self.tell() + self.seek(0) + val = self.read() + self.seek(pos) + return val + + def seekable(self): + return True + + def readable(self): + return True + + def writable(self): + return True + + def __next__(self): + self._checkClosed() + line = self.readline() + if not line: + pos = self.buffer.tell() + self.buffer.seek(0, os.SEEK_END) + if pos == self.buffer.tell(): + raise StopIteration + else: + self.buffer.seek(pos) + return line + + next = __next__ + + def __len__(self): + return self.len + + def __iter__(self): + self._checkClosed() + return self + + def __enter__(self): + self._checkClosed() + return self + + def __exit__(self, *args): + self._file.close() + + def __eq__(self, other): + if isinstance(other, self.__class__): + self_pos = self.tell() + other_pos = other.tell() + try: + self.seek(0) + other.seek(0) + eq = True + for self_line, other_line in zip_longest(self, other): + if self_line != other_line: + eq = False + break + self.seek(self_pos) + other.seek(other_pos) + except Exception: + # Attempt to return files to original position if there were any errors + try: + self.seek(self_pos) + except Exception: + pass + try: + other.seek(other_pos) + except Exception: + pass + raise + else: + return eq + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __bool__(self): + return True + + def __del__(self): + """Can fail when called at program exit so suppress traceback.""" + try: + self.close() + except Exception: + pass + + +class SpooledBytesIO(SpooledIOBase): + """ + SpooledBytesIO is a spooled file-like-object that only accepts bytes. On + Python 2.x this means the 'str' type; on Python 3.x this means the 'bytes' + type. Bytes are written in and retrieved exactly as given, but it will + raise TypeErrors if something other than bytes are written. + + Example:: + + >>> from boltons import ioutils + >>> with ioutils.SpooledBytesIO() as f: + ... f.write(b"Happy IO") + ... _ = f.seek(0) + ... isinstance(f.getvalue(), bytes) + True + """ + + def read(self, n=-1): + self._checkClosed() + return self.buffer.read(n) + + def write(self, s): + self._checkClosed() + if not isinstance(s, bytes): + raise TypeError("bytes expected, got {}".format( + type(s).__name__ + )) + + if self.tell() + len(s) >= self._max_size: + self.rollover() + self.buffer.write(s) + + def seek(self, pos, mode=0): + self._checkClosed() + return self.buffer.seek(pos, mode) + + def readline(self, length=None): + self._checkClosed() + if length: + return self.buffer.readline(length) + else: + return self.buffer.readline() + + def readlines(self, sizehint=0): + return self.buffer.readlines(sizehint) + + def rollover(self): + """Roll the StringIO over to a TempFile""" + if not self._rolled: + tmp = TemporaryFile(dir=self._dir) + pos = self.buffer.tell() + tmp.write(self.buffer.getvalue()) + tmp.seek(pos) + self.buffer.close() + self._buffer = tmp + + @property + def _rolled(self): + return not isinstance(self.buffer, BytesIO) + + @property + def buffer(self): + try: + return self._buffer + except AttributeError: + self._buffer = BytesIO() + return self._buffer + + @property + def len(self): + """Determine the length of the file""" + pos = self.tell() + if self._rolled: + self.seek(0) + val = os.fstat(self.fileno()).st_size + else: + self.seek(0, os.SEEK_END) + val = self.tell() + self.seek(pos) + return val + + def tell(self): + self._checkClosed() + return self.buffer.tell() + + +class SpooledStringIO(SpooledIOBase): + """ + SpooledStringIO is a spooled file-like-object that only accepts unicode + values. On Python 2.x this means the 'unicode' type and on Python 3.x this + means the 'str' type. Values are accepted as unicode and then coerced into + utf-8 encoded bytes for storage. On retrieval, the values are returned as + unicode. + + Example:: + + >>> from boltons import ioutils + >>> with ioutils.SpooledStringIO() as f: + ... f.write(u"\u2014 Hey, an emdash!") + ... _ = f.seek(0) + ... isinstance(f.read(), str) + True + + """ + def __init__(self, *args, **kwargs): + self._tell = 0 + super().__init__(*args, **kwargs) + + def read(self, n=-1): + self._checkClosed() + ret = self.buffer.reader.read(n, n) + self._tell = self.tell() + len(ret) + return ret + + def write(self, s): + self._checkClosed() + if not isinstance(s, str): + raise TypeError("str expected, got {}".format( + type(s).__name__ + )) + current_pos = self.tell() + if self.buffer.tell() + len(s.encode('utf-8')) >= self._max_size: + self.rollover() + self.buffer.write(s.encode('utf-8')) + self._tell = current_pos + len(s) + + def _traverse_codepoints(self, current_position, n): + """Traverse from current position to the right n codepoints""" + dest = current_position + n + while True: + if current_position == dest: + # By chance we've landed on the right position, break + break + + # If the read would take us past the intended position then + # seek only enough to cover the offset + if current_position + READ_CHUNK_SIZE > dest: + self.read(dest - current_position) + break + else: + ret = self.read(READ_CHUNK_SIZE) + + # Increment our current position + current_position += READ_CHUNK_SIZE + + # If we kept reading but there was nothing here, break + # as we are at the end of the file + if not ret: + break + + return dest + + def seek(self, pos, mode=0): + """Traverse from offset to the specified codepoint""" + self._checkClosed() + # Seek to position from the start of the file + if mode == os.SEEK_SET: + self.buffer.seek(0) + self._traverse_codepoints(0, pos) + self._tell = pos + # Seek to new position relative to current position + elif mode == os.SEEK_CUR: + start_pos = self.tell() + self._traverse_codepoints(self.tell(), pos) + self._tell = start_pos + pos + elif mode == os.SEEK_END: + self.buffer.seek(0) + dest_position = self.len - pos + self._traverse_codepoints(0, dest_position) + self._tell = dest_position + else: + raise ValueError( + f"Invalid whence ({mode}, should be 0, 1, or 2)" + ) + return self.tell() + + def readline(self, length=None): + self._checkClosed() + ret = self.buffer.readline(length).decode('utf-8') + self._tell = self.tell() + len(ret) + return ret + + def readlines(self, sizehint=0): + ret = [x.decode('utf-8') for x in self.buffer.readlines(sizehint)] + self._tell = self.tell() + sum(len(x) for x in ret) + return ret + + @property + def buffer(self): + try: + return self._buffer + except AttributeError: + self._buffer = EncodedFile(BytesIO(), data_encoding='utf-8') + return self._buffer + + @property + def _rolled(self): + return not isinstance(self.buffer.stream, BytesIO) + + def rollover(self): + """Roll the buffer over to a TempFile""" + if not self._rolled: + tmp = EncodedFile(TemporaryFile(dir=self._dir), + data_encoding='utf-8') + pos = self.buffer.tell() + tmp.write(self.buffer.getvalue()) + tmp.seek(pos) + self.buffer.close() + self._buffer = tmp + + def tell(self): + """Return the codepoint position""" + self._checkClosed() + return self._tell + + @property + def len(self): + """Determine the number of codepoints in the file""" + pos = self.buffer.tell() + self.buffer.seek(0) + total = 0 + while True: + ret = self.read(READ_CHUNK_SIZE) + if not ret: + break + total += len(ret) + self.buffer.seek(pos) + return total + + +def is_text_fileobj(fileobj): + if getattr(fileobj, 'encoding', False): + # codecs.open and io.TextIOBase + return True + if getattr(fileobj, 'getvalue', False): + # StringIO.StringIO / io.StringIO + try: + if isinstance(fileobj.getvalue(), str): + return True + except Exception: + pass + return False + + +class MultiFileReader: + """Takes a list of open files or file-like objects and provides an + interface to read from them all contiguously. Like + :func:`itertools.chain()`, but for reading files. + + >>> mfr = MultiFileReader(BytesIO(b'ab'), BytesIO(b'cd'), BytesIO(b'e')) + >>> mfr.read(3).decode('ascii') + u'abc' + >>> mfr.read(3).decode('ascii') + u'de' + + The constructor takes as many fileobjs as you hand it, and will + raise a TypeError on non-file-like objects. A ValueError is raised + when file-like objects are a mix of bytes- and text-handling + objects (for instance, BytesIO and StringIO). + """ + + def __init__(self, *fileobjs): + if not all([callable(getattr(f, 'read', None)) and + callable(getattr(f, 'seek', None)) for f in fileobjs]): + raise TypeError('MultiFileReader expected file-like objects' + ' with .read() and .seek()') + if all([is_text_fileobj(f) for f in fileobjs]): + # codecs.open and io.TextIOBase + self._joiner = '' + elif any([is_text_fileobj(f) for f in fileobjs]): + raise ValueError('All arguments to MultiFileReader must handle' + ' bytes OR text, not a mix') + else: + # open/file and io.BytesIO + self._joiner = b'' + self._fileobjs = fileobjs + self._index = 0 + + def read(self, amt=None): + """Read up to the specified *amt*, seamlessly bridging across + files. Returns the appropriate type of string (bytes or text) + for the input, and returns an empty string when the files are + exhausted. + """ + if not amt: + return self._joiner.join(f.read() for f in self._fileobjs) + parts = [] + while amt > 0 and self._index < len(self._fileobjs): + parts.append(self._fileobjs[self._index].read(amt)) + got = len(parts[-1]) + if got < amt: + self._index += 1 + amt -= got + return self._joiner.join(parts) + + def seek(self, offset, whence=os.SEEK_SET): + """Enables setting position of the file cursor to a given + *offset*. Currently only supports ``offset=0``. + """ + if whence != os.SEEK_SET: + raise NotImplementedError( + 'MultiFileReader.seek() only supports os.SEEK_SET') + if offset != 0: + raise NotImplementedError( + 'MultiFileReader only supports seeking to start at this time') + for f in self._fileobjs: + f.seek(0) diff --git a/miniconda3/lib/python3.13/site-packages/boltons/iterutils.py b/miniconda3/lib/python3.13/site-packages/boltons/iterutils.py new file mode 100644 index 0000000000000000000000000000000000000000..e0a5b900173d93689acf0e6b09dd75d87924da5b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/iterutils.py @@ -0,0 +1,1609 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""":mod:`itertools` is full of great examples of Python generator +usage. However, there are still some critical gaps. ``iterutils`` +fills many of those gaps with featureful, tested, and Pythonic +solutions. + +Many of the functions below have two versions, one which +returns an iterator (denoted by the ``*_iter`` naming pattern), and a +shorter-named convenience form that returns a list. Some of the +following are based on examples in itertools docs. +""" + +import os +import math +import time +import codecs +import random +import itertools +from itertools import zip_longest +from collections.abc import Mapping, Sequence, Set, ItemsView, Iterable + + +try: + from .typeutils import make_sentinel + _UNSET = make_sentinel('_UNSET') + _REMAP_EXIT = make_sentinel('_REMAP_EXIT') +except ImportError: + _REMAP_EXIT = object() + _UNSET = object() + + +def is_iterable(obj): + """Similar in nature to :func:`callable`, ``is_iterable`` returns + ``True`` if an object is `iterable`_, ``False`` if not. + + >>> is_iterable([]) + True + >>> is_iterable(object()) + False + + .. _iterable: https://docs.python.org/2/glossary.html#term-iterable + """ + try: + iter(obj) + except TypeError: + return False + return True + + +def is_scalar(obj): + """A near-mirror of :func:`is_iterable`. Returns ``False`` if an + object is an iterable container type. Strings are considered + scalar as well, because strings are more often treated as whole + values as opposed to iterables of 1-character substrings. + + >>> is_scalar(object()) + True + >>> is_scalar(range(10)) + False + >>> is_scalar('hello') + True + """ + return not is_iterable(obj) or isinstance(obj, (str, bytes)) + + +def is_collection(obj): + """The opposite of :func:`is_scalar`. Returns ``True`` if an object + is an iterable other than a string. + + >>> is_collection(object()) + False + >>> is_collection(range(10)) + True + >>> is_collection('hello') + False + """ + return is_iterable(obj) and not isinstance(obj, (str, bytes)) + + +def split(src, sep=None, maxsplit=None): + """Splits an iterable based on a separator. Like :meth:`str.split`, + but for all iterables. Returns a list of lists. + + >>> split(['hi', 'hello', None, None, 'sup', None, 'soap', None]) + [['hi', 'hello'], ['sup'], ['soap']] + + See :func:`split_iter` docs for more info. + """ + return list(split_iter(src, sep, maxsplit)) + + +def split_iter(src, sep=None, maxsplit=None): + """Splits an iterable based on a separator, *sep*, a max of + *maxsplit* times (no max by default). *sep* can be: + + * a single value + * an iterable of separators + * a single-argument callable that returns True when a separator is + encountered + + ``split_iter()`` yields lists of non-separator values. A separator will + never appear in the output. + + >>> list(split_iter(['hi', 'hello', None, None, 'sup', None, 'soap', None])) + [['hi', 'hello'], ['sup'], ['soap']] + + Note that ``split_iter`` is based on :func:`str.split`, so if + *sep* is ``None``, ``split()`` **groups** separators. If empty lists + are desired between two contiguous ``None`` values, simply use + ``sep=[None]``: + + >>> list(split_iter(['hi', 'hello', None, None, 'sup', None])) + [['hi', 'hello'], ['sup']] + >>> list(split_iter(['hi', 'hello', None, None, 'sup', None], sep=[None])) + [['hi', 'hello'], [], ['sup'], []] + + Using a callable separator: + + >>> falsy_sep = lambda x: not x + >>> list(split_iter(['hi', 'hello', None, '', 'sup', False], falsy_sep)) + [['hi', 'hello'], [], ['sup'], []] + + See :func:`split` for a list-returning version. + + """ + if not is_iterable(src): + raise TypeError('expected an iterable') + + if maxsplit is not None: + maxsplit = int(maxsplit) + if maxsplit == 0: + yield [src] + return + + if callable(sep): + sep_func = sep + elif not is_scalar(sep): + sep = frozenset(sep) + def sep_func(x): return x in sep + else: + def sep_func(x): return x == sep + + cur_group = [] + split_count = 0 + for s in src: + if maxsplit is not None and split_count >= maxsplit: + def sep_func(x): return False + if sep_func(s): + if sep is None and not cur_group: + # If sep is none, str.split() "groups" separators + # check the str.split() docs for more info + continue + split_count += 1 + yield cur_group + cur_group = [] + else: + cur_group.append(s) + + if cur_group or sep is not None: + yield cur_group + return + + +def lstrip(iterable, strip_value=None): + """Strips values from the beginning of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.lstrip. Returns a list. + + >>> lstrip(['Foo', 'Bar', 'Bam'], 'Foo') + ['Bar', 'Bam'] + + """ + return list(lstrip_iter(iterable, strip_value)) + + +def lstrip_iter(iterable, strip_value=None): + """Strips values from the beginning of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.lstrip. Returns a generator. + + >>> list(lstrip_iter(['Foo', 'Bar', 'Bam'], 'Foo')) + ['Bar', 'Bam'] + + """ + iterator = iter(iterable) + for i in iterator: + if i != strip_value: + yield i + break + for i in iterator: + yield i + + +def rstrip(iterable, strip_value=None): + """Strips values from the end of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.rstrip. Returns a list. + + >>> rstrip(['Foo', 'Bar', 'Bam'], 'Bam') + ['Foo', 'Bar'] + + """ + return list(rstrip_iter(iterable, strip_value)) + + +def rstrip_iter(iterable, strip_value=None): + """Strips values from the end of an iterable. Stripped items will + match the value of the argument strip_value. Functionality is analogous + to that of the method str.rstrip. Returns a generator. + + >>> list(rstrip_iter(['Foo', 'Bar', 'Bam'], 'Bam')) + ['Foo', 'Bar'] + + """ + iterator = iter(iterable) + for i in iterator: + if i == strip_value: + cache = list() + cache.append(i) + broken = False + for i in iterator: + if i == strip_value: + cache.append(i) + else: + broken = True + break + if not broken: # Return to caller here because the end of the + return # iterator has been reached + yield from cache + yield i + + +def strip(iterable, strip_value=None): + """Strips values from the beginning and end of an iterable. Stripped items + will match the value of the argument strip_value. Functionality is + analogous to that of the method str.strip. Returns a list. + + >>> strip(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu') + ['Foo', 'Bar', 'Bam'] + + """ + return list(strip_iter(iterable, strip_value)) + + +def strip_iter(iterable, strip_value=None): + """Strips values from the beginning and end of an iterable. Stripped items + will match the value of the argument strip_value. Functionality is + analogous to that of the method str.strip. Returns a generator. + + >>> list(strip_iter(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu')) + ['Foo', 'Bar', 'Bam'] + + """ + return rstrip_iter(lstrip_iter(iterable, strip_value), strip_value) + + +def chunked(src, size, count=None, **kw): + """Returns a list of *count* chunks, each with *size* elements, + generated from iterable *src*. If *src* is not evenly divisible by + *size*, the final chunk will have fewer than *size* elements. + Provide the *fill* keyword argument to provide a pad value and + enable padding, otherwise no padding will take place. + + >>> chunked(range(10), 3) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + >>> chunked(range(10), 3, fill=None) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]] + >>> chunked(range(10), 3, count=2) + [[0, 1, 2], [3, 4, 5]] + + See :func:`chunked_iter` for more info. + """ + chunk_iter = chunked_iter(src, size, **kw) + if count is None: + return list(chunk_iter) + else: + return list(itertools.islice(chunk_iter, count)) + + +def _validate_positive_int(value, name, strictly_positive=True): + value = int(value) + if value < 0 or (strictly_positive and value == 0): + raise ValueError('expected a positive integer ' + name) + return value + + +def chunked_iter(src, size, **kw): + """Generates *size*-sized chunks from *src* iterable. Unless the + optional *fill* keyword argument is provided, iterables not evenly + divisible by *size* will have a final chunk that is smaller than + *size*. + + >>> list(chunked_iter(range(10), 3)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + >>> list(chunked_iter(range(10), 3, fill=None)) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]] + + Note that ``fill=None`` in fact uses ``None`` as the fill value. + """ + # TODO: add count kwarg? + if not is_iterable(src): + raise TypeError('expected an iterable') + size = _validate_positive_int(size, 'chunk size') + do_fill = True + try: + fill_val = kw.pop('fill') + except KeyError: + do_fill = False + fill_val = None + if kw: + raise ValueError('got unexpected keyword arguments: %r' % kw.keys()) + if not src: + return + + def postprocess(chk): return chk + if isinstance(src, (str, bytes)): + def postprocess(chk, _sep=type(src)()): return _sep.join(chk) + if isinstance(src, bytes): + def postprocess(chk): return bytes(chk) + src_iter = iter(src) + while True: + cur_chunk = list(itertools.islice(src_iter, size)) + if not cur_chunk: + break + lc = len(cur_chunk) + if lc < size and do_fill: + cur_chunk[lc:] = [fill_val] * (size - lc) + yield postprocess(cur_chunk) + return + + +def chunk_ranges(input_size, chunk_size, input_offset=0, overlap_size=0, align=False): + """Generates *chunk_size*-sized chunk ranges for an input with length *input_size*. + Optionally, a start of the input can be set via *input_offset*, and + and overlap between the chunks may be specified via *overlap_size*. + Also, if *align* is set to *True*, any items with *i % (chunk_size-overlap_size) == 0* + are always at the beginning of the chunk. + + Returns an iterator of (start, end) tuples, one tuple per chunk. + + >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5)) + [(10, 15), (15, 20)] + >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=1)) + [(10, 15), (14, 19), (18, 20)] + >>> list(chunk_ranges(input_offset=10, input_size=10, chunk_size=5, overlap_size=2)) + [(10, 15), (13, 18), (16, 20)] + + >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=False)) + [(4, 9), (9, 14), (14, 19)] + >>> list(chunk_ranges(input_offset=4, input_size=15, chunk_size=5, align=True)) + [(4, 5), (5, 10), (10, 15), (15, 19)] + + >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=False)) + [(2, 7), (6, 11), (10, 15), (14, 17)] + >>> list(chunk_ranges(input_offset=2, input_size=15, chunk_size=5, overlap_size=1, align=True)) + [(2, 5), (4, 9), (8, 13), (12, 17)] + >>> list(chunk_ranges(input_offset=3, input_size=15, chunk_size=5, overlap_size=1, align=True)) + [(3, 5), (4, 9), (8, 13), (12, 17), (16, 18)] + """ + input_size = _validate_positive_int( + input_size, 'input_size', strictly_positive=False) + chunk_size = _validate_positive_int(chunk_size, 'chunk_size') + input_offset = _validate_positive_int( + input_offset, 'input_offset', strictly_positive=False) + overlap_size = _validate_positive_int( + overlap_size, 'overlap_size', strictly_positive=False) + + input_stop = input_offset + input_size + + if align: + initial_chunk_len = chunk_size - \ + input_offset % (chunk_size - overlap_size) + if initial_chunk_len != overlap_size: + yield (input_offset, min(input_offset + initial_chunk_len, input_stop)) + if input_offset + initial_chunk_len >= input_stop: + return + input_offset = input_offset + initial_chunk_len - overlap_size + + for i in range(input_offset, input_stop, chunk_size - overlap_size): + yield (i, min(i + chunk_size, input_stop)) + + if i + chunk_size >= input_stop: + return + + +def pairwise(src, end=_UNSET): + """Convenience function for calling :func:`windowed` on *src*, with + *size* set to 2. + + >>> pairwise(range(5)) + [(0, 1), (1, 2), (2, 3), (3, 4)] + >>> pairwise([]) + [] + + Unless *end* is set, the number of pairs is always one less than + the number of elements in the iterable passed in, except on an empty input, + which will return an empty list. + + With *end* set, a number of pairs equal to the length of *src* is returned, + with the last item of the last pair being equal to *end*. + + >>> list(pairwise(range(3), end=None)) + [(0, 1), (1, 2), (2, None)] + + This way, *end* values can be useful as sentinels to signal the end of the iterable. + """ + return windowed(src, 2, fill=end) + + +def pairwise_iter(src, end=_UNSET): + """Convenience function for calling :func:`windowed_iter` on *src*, + with *size* set to 2. + + >>> list(pairwise_iter(range(5))) + [(0, 1), (1, 2), (2, 3), (3, 4)] + >>> list(pairwise_iter([])) + [] + + Unless *end* is set, the number of pairs is always one less + than the number of elements in the iterable passed in, + or zero, when *src* is empty. + + With *end* set, a number of pairs equal to the length of *src* is returned, + with the last item of the last pair being equal to *end*. + + >>> list(pairwise_iter(range(3), end=None)) + [(0, 1), (1, 2), (2, None)] + + This way, *end* values can be useful as sentinels to signal the end + of the iterable. For infinite iterators, setting *end* has no effect. + """ + return windowed_iter(src, 2, fill=end) + + +def windowed(src, size, fill=_UNSET): + """Returns tuples with exactly length *size*. If *fill* is unset + and the iterable is too short to make a window of length *size*, + no tuples are returned. See :func:`windowed_iter` for more. + """ + return list(windowed_iter(src, size, fill=fill)) + + +def windowed_iter(src, size, fill=_UNSET): + """Returns tuples with length *size* which represent a sliding + window over iterable *src*. + + >>> list(windowed_iter(range(7), 3)) + [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)] + + If *fill* is unset, and the iterable is too short to make a window + of length *size*, then no window tuples are returned. + + >>> list(windowed_iter(range(3), 5)) + [] + + With *fill* set, the iterator always yields a number of windows + equal to the length of the *src* iterable. + + >>> windowed(range(4), 3, fill=None) + [(0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] + + This way, *fill* values can be useful to signal the end of the iterable. + For infinite iterators, setting *fill* has no effect. + """ + tees = itertools.tee(src, size) + if fill is _UNSET: + try: + for i, t in enumerate(tees): + for _ in range(i): + next(t) + except StopIteration: + return zip([]) + return zip(*tees) + + for i, t in enumerate(tees): + for _ in range(i): + try: + next(t) + except StopIteration: + continue + return zip_longest(*tees, fillvalue=fill) + + +def xfrange(stop, start=None, step=1.0): + """Same as :func:`frange`, but generator-based instead of returning a + list. + + >>> tuple(xfrange(1, 3, step=0.75)) + (1.0, 1.75, 2.5) + + See :func:`frange` for more details. + """ + if not step: + raise ValueError('step must be non-zero') + if start is None: + start, stop = 0.0, stop * 1.0 + else: + # swap when all args are used + stop, start = start * 1.0, stop * 1.0 + cur = start + while cur < stop: + yield cur + cur += step + + +def frange(stop, start=None, step=1.0): + """A :func:`range` clone for float-based ranges. + + >>> frange(5) + [0.0, 1.0, 2.0, 3.0, 4.0] + >>> frange(6, step=1.25) + [0.0, 1.25, 2.5, 3.75, 5.0] + >>> frange(100.5, 101.5, 0.25) + [100.5, 100.75, 101.0, 101.25] + >>> frange(5, 0) + [] + >>> frange(5, 0, step=-1.25) + [5.0, 3.75, 2.5, 1.25] + """ + if not step: + raise ValueError('step must be non-zero') + if start is None: + start, stop = 0.0, stop * 1.0 + else: + # swap when all args are used + stop, start = start * 1.0, stop * 1.0 + count = int(math.ceil((stop - start) / step)) + ret = [None] * count + if not ret: + return ret + ret[0] = start + for i in range(1, count): + ret[i] = ret[i - 1] + step + return ret + + +def backoff(start, stop, count=None, factor=2.0, jitter=False): + """Returns a list of geometrically-increasing floating-point numbers, + suitable for usage with `exponential backoff`_. Exactly like + :func:`backoff_iter`, but without the ``'repeat'`` option for + *count*. See :func:`backoff_iter` for more details. + + .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff + + >>> backoff(1, 10) + [1.0, 2.0, 4.0, 8.0, 10.0] + """ + if count == 'repeat': + raise ValueError("'repeat' supported in backoff_iter, not backoff") + return list(backoff_iter(start, stop, count=count, + factor=factor, jitter=jitter)) + + +def backoff_iter(start, stop, count=None, factor=2.0, jitter=False): + """Generates a sequence of geometrically-increasing floats, suitable + for usage with `exponential backoff`_. Starts with *start*, + increasing by *factor* until *stop* is reached, optionally + stopping iteration once *count* numbers are yielded. *factor* + defaults to 2. In general retrying with properly-configured + backoff creates a better-behaved component for a larger service + ecosystem. + + .. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff + + >>> list(backoff_iter(1.0, 10.0, count=5)) + [1.0, 2.0, 4.0, 8.0, 10.0] + >>> list(backoff_iter(1.0, 10.0, count=8)) + [1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0] + >>> list(backoff_iter(0.25, 100.0, factor=10)) + [0.25, 2.5, 25.0, 100.0] + + A simplified usage example: + + .. code-block:: python + + for timeout in backoff_iter(0.25, 5.0): + try: + res = network_call() + break + except Exception as e: + log(e) + time.sleep(timeout) + + An enhancement for large-scale systems would be to add variation, + or *jitter*, to timeout values. This is done to avoid a thundering + herd on the receiving end of the network call. + + Finally, for *count*, the special value ``'repeat'`` can be passed to + continue yielding indefinitely. + + Args: + + start (float): Positive number for baseline. + stop (float): Positive number for maximum. + count (int): Number of steps before stopping + iteration. Defaults to the number of steps between *start* and + *stop*. Pass the string, `'repeat'`, to continue iteration + indefinitely. + factor (float): Rate of exponential increase. Defaults to `2.0`, + e.g., `[1, 2, 4, 8, 16]`. + jitter (float): A factor between `-1.0` and `1.0`, used to + uniformly randomize and thus spread out timeouts in a distributed + system, avoiding rhythm effects. Positive values use the base + backoff curve as a maximum, negative values use the curve as a + minimum. Set to 1.0 or `True` for a jitter approximating + Ethernet's time-tested backoff solution. Defaults to `False`. + + """ + start = float(start) + stop = float(stop) + factor = float(factor) + if start < 0.0: + raise ValueError('expected start >= 0, not %r' % start) + if factor < 1.0: + raise ValueError('expected factor >= 1.0, not %r' % factor) + if stop == 0.0: + raise ValueError('expected stop >= 0') + if stop < start: + raise ValueError('expected stop >= start, not %r' % stop) + if count is None: + denom = start if start else 1 + count = 1 + math.ceil(math.log(stop/denom, factor)) + count = count if start else count + 1 + if count != 'repeat' and count < 0: + raise ValueError('count must be positive or "repeat", not %r' % count) + if jitter: + jitter = float(jitter) + if not (-1.0 <= jitter <= 1.0): + raise ValueError('expected jitter -1 <= j <= 1, not: %r' % jitter) + + cur, i = start, 0 + while count == 'repeat' or i < count: + if not jitter: + cur_ret = cur + elif jitter: + cur_ret = cur - (cur * jitter * random.random()) + yield cur_ret + i += 1 + if cur == 0: + cur = 1 + elif cur < stop: + cur *= factor + if cur > stop: + cur = stop + return + + +def bucketize(src, key=bool, value_transform=None, key_filter=None): + """Group values in the *src* iterable by the value returned by *key*. + + >>> bucketize(range(5)) + {False: [0], True: [1, 2, 3, 4]} + >>> is_odd = lambda x: x % 2 == 1 + >>> bucketize(range(5), is_odd) + {False: [0, 2, 4], True: [1, 3]} + + *key* is :class:`bool` by default, but can either be a callable or a string or a list + if it is a string, it is the name of the attribute on which to bucketize objects. + + >>> bucketize([1+1j, 2+2j, 1, 2], key='real') + {1.0: [(1+1j), 1], 2.0: [(2+2j), 2]} + + if *key* is a list, it contains the buckets where to put each object + + >>> bucketize([1,2,365,4,98],key=[0,1,2,0,2]) + {0: [1, 4], 1: [2], 2: [365, 98]} + + + Value lists are not deduplicated: + + >>> bucketize([None, None, None, 'hello']) + {False: [None, None, None], True: ['hello']} + + Bucketize into more than 3 groups + + >>> bucketize(range(10), lambda x: x % 3) + {0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]} + + ``bucketize`` has a couple of advanced options useful in certain + cases. *value_transform* can be used to modify values as they are + added to buckets, and *key_filter* will allow excluding certain + buckets from being collected. + + >>> bucketize(range(5), value_transform=lambda x: x*x) + {False: [0], True: [1, 4, 9, 16]} + + >>> bucketize(range(10), key=lambda x: x % 3, key_filter=lambda k: k % 3 != 1) + {0: [0, 3, 6, 9], 2: [2, 5, 8]} + + Note in some of these examples there were at most two keys, ``True`` and + ``False``, and each key present has a list with at least one + item. See :func:`partition` for a version specialized for binary + use cases. + + """ + if not is_iterable(src): + raise TypeError('expected an iterable') + elif isinstance(key, list): + if len(key) != len(src): + raise ValueError("key and src have to be the same length") + src = zip(key, src) + + if isinstance(key, str): + def key_func(x): return getattr(x, key, x) + elif callable(key): + key_func = key + elif isinstance(key, list): + def key_func(x): return x[0] + else: + raise TypeError('expected key to be callable or a string or a list') + + if value_transform is None: + def value_transform(x): return x + if not callable(value_transform): + raise TypeError('expected callable value transform function') + if isinstance(key, list): + f = value_transform + def value_transform(x): return f(x[1]) + + ret = {} + for val in src: + key_of_val = key_func(val) + if key_filter is None or key_filter(key_of_val): + ret.setdefault(key_of_val, []).append(value_transform(val)) + return ret + + +def partition(src, key=bool): + """No relation to :meth:`str.partition`, ``partition`` is like + :func:`bucketize`, but for added convenience returns a tuple of + ``(truthy_values, falsy_values)``. + + >>> nonempty, empty = partition(['', '', 'hi', '', 'bye']) + >>> nonempty + ['hi', 'bye'] + + *key* defaults to :class:`bool`, but can be carefully overridden to + use either a function that returns either ``True`` or ``False`` or + a string name of the attribute on which to partition objects. + + >>> import string + >>> is_digit = lambda x: x in string.digits + >>> decimal_digits, hexletters = partition(string.hexdigits, is_digit) + >>> ''.join(decimal_digits), ''.join(hexletters) + ('0123456789', 'abcdefABCDEF') + """ + bucketized = bucketize(src, key) + return bucketized.get(True, []), bucketized.get(False, []) + + +def unique(src, key=None): + """``unique()`` returns a list of unique values, as determined by + *key*, in the order they first appeared in the input iterable, + *src*. + + >>> ones_n_zeros = '11010110001010010101010' + >>> ''.join(unique(ones_n_zeros)) + '10' + + See :func:`unique_iter` docs for more details. + """ + return list(unique_iter(src, key)) + + +def unique_iter(src, key=None): + """Yield unique elements from the iterable, *src*, based on *key*, + in the order in which they first appeared in *src*. + + >>> repetitious = [1, 2, 3] * 10 + >>> list(unique_iter(repetitious)) + [1, 2, 3] + + By default, *key* is the object itself, but *key* can either be a + callable or, for convenience, a string name of the attribute on + which to uniqueify objects, falling back on identity when the + attribute is not present. + + >>> pleasantries = ['hi', 'hello', 'ok', 'bye', 'yes'] + >>> list(unique_iter(pleasantries, key=lambda x: len(x))) + ['hi', 'hello', 'bye'] + """ + if not is_iterable(src): + raise TypeError('expected an iterable, not %r' % type(src)) + if key is None: + def key_func(x): return x + elif callable(key): + key_func = key + elif isinstance(key, str): + def key_func(x): return getattr(x, key, x) + else: + raise TypeError('"key" expected a string or callable, not %r' % key) + seen = set() + for i in src: + k = key_func(i) + if k not in seen: + seen.add(k) + yield i + return + + +def redundant(src, key=None, groups=False): + """The complement of :func:`unique()`. + + By default returns non-unique/duplicate values as a list of the + *first* redundant value in *src*. Pass ``groups=True`` to get + groups of all values with redundancies, ordered by position of the + first redundant value. This is useful in conjunction with some + normalizing *key* function. + + >>> redundant([1, 2, 3, 4]) + [] + >>> redundant([1, 2, 3, 2, 3, 3, 4]) + [2, 3] + >>> redundant([1, 2, 3, 2, 3, 3, 4], groups=True) + [[2, 2], [3, 3, 3]] + + An example using a *key* function to do case-insensitive + redundancy detection. + + >>> redundant(['hi', 'Hi', 'HI', 'hello'], key=str.lower) + ['Hi'] + >>> redundant(['hi', 'Hi', 'HI', 'hello'], groups=True, key=str.lower) + [['hi', 'Hi', 'HI']] + + *key* should also be used when the values in *src* are not hashable. + + .. note:: + + This output of this function is designed for reporting + duplicates in contexts when a unique input is desired. Due to + the grouped return type, there is no streaming equivalent of + this function for the time being. + + """ + if key is None: + pass + elif callable(key): + key_func = key + elif isinstance(key, (str, bytes)): + def key_func(x): return getattr(x, key, x) + else: + raise TypeError('"key" expected a string or callable, not %r' % key) + seen = {} # key to first seen item + redundant_order = [] + redundant_groups = {} + for i in src: + k = key_func(i) if key else i + if k not in seen: + seen[k] = i + else: + if k in redundant_groups: + if groups: + redundant_groups[k].append(i) + else: + redundant_order.append(k) + redundant_groups[k] = [seen[k], i] + if not groups: + ret = [redundant_groups[k][1] for k in redundant_order] + else: + ret = [redundant_groups[k] for k in redundant_order] + return ret + + +def one(src, default=None, key=None): + """Along the same lines as builtins, :func:`all` and :func:`any`, and + similar to :func:`first`, ``one()`` returns the single object in + the given iterable *src* that evaluates to ``True``, as determined + by callable *key*. If unset, *key* defaults to :class:`bool`. If + no such objects are found, *default* is returned. If *default* is + not passed, ``None`` is returned. + + If *src* has more than one object that evaluates to ``True``, or + if there is no object that fulfills such condition, return + *default*. It's like an `XOR`_ over an iterable. + + >>> one((True, False, False)) + True + >>> one((True, False, True)) + >>> one((0, 0, 'a')) + 'a' + >>> one((0, False, None)) + >>> one((True, True), default=False) + False + >>> bool(one(('', 1))) + True + >>> one((10, 20, 30, 42), key=lambda i: i > 40) + 42 + + See `Martín Gaitán's original repo`_ for further use cases. + + .. _Martín Gaitán's original repo: https://github.com/mgaitan/one + .. _XOR: https://en.wikipedia.org/wiki/Exclusive_or + + """ + ones = list(itertools.islice(filter(key, src), 2)) + return ones[0] if len(ones) == 1 else default + + +def first(iterable, default=None, key=None): + """Return first element of *iterable* that evaluates to ``True``, else + return ``None`` or optional *default*. Similar to :func:`one`. + + >>> first([0, False, None, [], (), 42]) + 42 + >>> first([0, False, None, [], ()]) is None + True + >>> first([0, False, None, [], ()], default='ohai') + 'ohai' + >>> import re + >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) + >>> m.group(1) + 'bc' + + The optional *key* argument specifies a one-argument predicate function + like that used for *filter()*. The *key* argument, if supplied, should be + in keyword form. For example, finding the first even number in an iterable: + + >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) + 4 + + Contributed by Hynek Schlawack, author of `the original standalone module`_. + + .. _the original standalone module: https://github.com/hynek/first + """ + return next(filter(key, iterable), default) + + +def flatten_iter(iterable): + """``flatten_iter()`` yields all the elements from *iterable* while + collapsing any nested iterables. + + >>> nested = [[1, 2], [[3], [4, 5]]] + >>> list(flatten_iter(nested)) + [1, 2, 3, 4, 5] + """ + for item in iterable: + if isinstance(item, Iterable) and not isinstance(item, (str, bytes)): + yield from flatten_iter(item) + else: + yield item + + +def flatten(iterable): + """``flatten()`` returns a collapsed list of all the elements from + *iterable* while collapsing any nested iterables. + + >>> nested = [[1, 2], [[3], [4, 5]]] + >>> flatten(nested) + [1, 2, 3, 4, 5] + """ + return list(flatten_iter(iterable)) + + +def same(iterable, ref=_UNSET): + """``same()`` returns ``True`` when all values in *iterable* are + equal to one another, or optionally a reference value, + *ref*. Similar to :func:`all` and :func:`any` in that it evaluates + an iterable and returns a :class:`bool`. ``same()`` returns + ``True`` for empty iterables. + + >>> same([]) + True + >>> same([1]) + True + >>> same(['a', 'a', 'a']) + True + >>> same(range(20)) + False + >>> same([[], []]) + True + >>> same([[], []], ref='test') + False + + """ + iterator = iter(iterable) + if ref is _UNSET: + ref = next(iterator, ref) + return all(val == ref for val in iterator) + + +def default_visit(path, key, value): + # print('visit(%r, %r, %r)' % (path, key, value)) + return key, value + + +# enable the extreme: monkeypatching iterutils with a different default_visit +_orig_default_visit = default_visit + + +def default_enter(path, key, value): + # print('enter(%r, %r)' % (key, value)) + if isinstance(value, (str, bytes)): + return value, False + elif isinstance(value, Mapping): + return value.__class__(), ItemsView(value) + elif isinstance(value, Sequence): + return value.__class__(), enumerate(value) + elif isinstance(value, Set): + return value.__class__(), enumerate(value) + else: + # files, strings, other iterables, and scalars are not + # traversed + return value, False + + +def default_exit(path, key, old_parent, new_parent, new_items): + # print('exit(%r, %r, %r, %r, %r)' + # % (path, key, old_parent, new_parent, new_items)) + ret = new_parent + if isinstance(new_parent, Mapping): + new_parent.update(new_items) + elif isinstance(new_parent, Sequence): + vals = [v for i, v in new_items] + try: + new_parent.extend(vals) + except AttributeError: + ret = new_parent.__class__(vals) # tuples + elif isinstance(new_parent, Set): + vals = [v for i, v in new_items] + try: + new_parent.update(vals) + except AttributeError: + ret = new_parent.__class__(vals) # frozensets + else: + raise RuntimeError('unexpected iterable type: %r' % type(new_parent)) + return ret + + +def remap(root, visit=default_visit, enter=default_enter, exit=default_exit, + **kwargs): + """The remap ("recursive map") function is used to traverse and + transform nested structures. Lists, tuples, sets, and dictionaries + are just a few of the data structures nested into heterogeneous + tree-like structures that are so common in programming. + Unfortunately, Python's built-in ways to manipulate collections + are almost all flat. List comprehensions may be fast and succinct, + but they do not recurse, making it tedious to apply quick changes + or complex transforms to real-world data. + + remap goes where list comprehensions cannot. + + Here's an example of removing all Nones from some data: + + >>> from pprint import pprint + >>> reviews = {'Star Trek': {'TNG': 10, 'DS9': 8.5, 'ENT': None}, + ... 'Babylon 5': 6, 'Dr. Who': None} + >>> pprint(remap(reviews, lambda p, k, v: v is not None)) + {'Babylon 5': 6, 'Star Trek': {'DS9': 8.5, 'TNG': 10}} + + Notice how both Nones have been removed despite the nesting in the + dictionary. Not bad for a one-liner, and that's just the beginning. + See `this remap cookbook`_ for more delicious recipes. + + .. _this remap cookbook: http://sedimental.org/remap.html + + remap takes four main arguments: the object to traverse and three + optional callables which determine how the remapped object will be + created. + + Args: + + root: The target object to traverse. By default, remap + supports iterables like :class:`list`, :class:`tuple`, + :class:`dict`, and :class:`set`, but any object traversable by + *enter* will work. + visit (callable): This function is called on every item in + *root*. It must accept three positional arguments, *path*, + *key*, and *value*. *path* is simply a tuple of parents' + keys. *visit* should return the new key-value pair. It may + also return ``True`` as shorthand to keep the old item + unmodified, or ``False`` to drop the item from the new + structure. *visit* is called after *enter*, on the new parent. + + The *visit* function is called for every item in root, + including duplicate items. For traversable values, it is + called on the new parent object, after all its children + have been visited. The default visit behavior simply + returns the key-value pair unmodified. + enter (callable): This function controls which items in *root* + are traversed. It accepts the same arguments as *visit*: the + path, the key, and the value of the current item. It returns a + pair of the blank new parent, and an iterator over the items + which should be visited. If ``False`` is returned instead of + an iterator, the value will not be traversed. + + The *enter* function is only called once per unique value. The + default enter behavior support mappings, sequences, and + sets. Strings and all other iterables will not be traversed. + exit (callable): This function determines how to handle items + once they have been visited. It gets the same three + arguments as the other functions -- *path*, *key*, *value* + -- plus two more: the blank new parent object returned + from *enter*, and a list of the new items, as remapped by + *visit*. + + Like *enter*, the *exit* function is only called once per + unique value. The default exit behavior is to simply add + all new items to the new parent, e.g., using + :meth:`list.extend` and :meth:`dict.update` to add to the + new parent. Immutable objects, such as a :class:`tuple` or + :class:`namedtuple`, must be recreated from scratch, but + use the same type as the new parent passed back from the + *enter* function. + reraise_visit (bool): A pragmatic convenience for the *visit* + callable. When set to ``False``, remap ignores any errors + raised by the *visit* callback. Items causing exceptions + are kept. See examples for more details. + trace (bool): Pass ``trace=True`` to print out the entire + traversal. Or pass a tuple of ``'visit'``, ``'enter'``, + or ``'exit'`` to print only the selected events. + + remap is designed to cover the majority of cases with just the + *visit* callable. While passing in multiple callables is very + empowering, remap is designed so very few cases should require + passing more than one function. + + When passing *enter* and *exit*, it's common and easiest to build + on the default behavior. Simply add ``from boltons.iterutils import + default_enter`` (or ``default_exit``), and have your enter/exit + function call the default behavior before or after your custom + logic. See `this example`_. + + Duplicate and self-referential objects (aka reference loops) are + automatically handled internally, `as shown here`_. + + .. _this example: http://sedimental.org/remap.html#sort_all_lists + .. _as shown here: http://sedimental.org/remap.html#corner_cases + + """ + # TODO: improve argument formatting in sphinx doc + # TODO: enter() return (False, items) to continue traverse but cancel copy? + if not callable(visit): + raise TypeError('visit expected callable, not: %r' % visit) + if not callable(enter): + raise TypeError('enter expected callable, not: %r' % enter) + if not callable(exit): + raise TypeError('exit expected callable, not: %r' % exit) + reraise_visit = kwargs.pop('reraise_visit', True) + trace = kwargs.pop('trace', ()) + if trace is True: + trace = ('visit', 'enter', 'exit') + elif isinstance(trace, str): + trace = (trace,) + if not isinstance(trace, (tuple, list, set)): + raise TypeError('trace expected tuple of event names, not: %r' % trace) + trace_enter, trace_exit, trace_visit = 'enter' in trace, 'exit' in trace, 'visit' in trace + + if kwargs: + raise TypeError('unexpected keyword arguments: %r' % kwargs.keys()) + + path, registry, stack = (), {}, [(None, root)] + new_items_stack = [] + while stack: + key, value = stack.pop() + id_value = id(value) + if key is _REMAP_EXIT: + key, new_parent, old_parent = value + id_value = id(old_parent) + path, new_items = new_items_stack.pop() + if trace_exit: + print(' .. remap exit:', path, '-', key, '-', + old_parent, '-', new_parent, '-', new_items) + value = exit(path, key, old_parent, new_parent, new_items) + if trace_exit: + print(' .. remap exit result:', value) + registry[id_value] = value + if not new_items_stack: + continue + elif id_value in registry: + value = registry[id_value] + else: + if trace_enter: + print(' .. remap enter:', path, '-', key, '-', value) + res = enter(path, key, value) + if trace_enter: + print(' .. remap enter result:', res) + try: + new_parent, new_items = res + except TypeError: + # TODO: handle False? + raise TypeError('enter should return a tuple of (new_parent,' + ' items_iterator), not: %r' % res) + if new_items is not False: + # traverse unless False is explicitly passed + registry[id_value] = new_parent + new_items_stack.append((path, [])) + if value is not root: + path += (key,) + stack.append((_REMAP_EXIT, (key, new_parent, value))) + if new_items: + stack.extend(reversed(list(new_items))) + if trace_enter: + print(' .. remap stack size now:', len(stack)) + continue + if visit is _orig_default_visit: + # avoid function call overhead by inlining identity operation + visited_item = (key, value) + else: + try: + if trace_visit: + print(' .. remap visit:', path, '-', key, '-', value) + visited_item = visit(path, key, value) + except Exception: + if reraise_visit: + raise + visited_item = True + if visited_item is False: + if trace_visit: + print(' .. remap visit result: ') + continue # drop + elif visited_item is True: + visited_item = (key, value) + if trace_visit: + print(' .. remap visit result:', visited_item) + # TODO: typecheck? + # raise TypeError('expected (key, value) from visit(),' + # ' not: %r' % visited_item) + try: + new_items_stack[-1][1].append(visited_item) + except IndexError: + raise TypeError('expected remappable root, not: %r' % root) + return value + + +class PathAccessError(KeyError, IndexError, TypeError): + """An amalgamation of KeyError, IndexError, and TypeError, + representing what can occur when looking up a path in a nested + object. + """ + + def __init__(self, exc, seg, path): + self.exc = exc + self.seg = seg + self.path = path + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.exc!r}, {self.seg!r}, {self.path!r})' + + def __str__(self): + return ('could not access %r from path %r, got error: %r' + % (self.seg, self.path, self.exc)) + + +def get_path(root, path, default=_UNSET): + """Retrieve a value from a nested object via a tuple representing the + lookup path. + + >>> root = {'a': {'b': {'c': [[1], [2], [3]]}}} + >>> get_path(root, ('a', 'b', 'c', 2, 0)) + 3 + + The path tuple format is intentionally consistent with that of + :func:`remap`, but a single dotted string can also be passed. + + One of get_path's chief aims is improved error messaging. EAFP is + great, but the error messages are not. + + For instance, ``root['a']['b']['c'][2][1]`` gives back + ``IndexError: list index out of range`` + + What went out of range where? get_path currently raises + ``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2, + 1), got error: IndexError('list index out of range',)``, a + subclass of IndexError and KeyError. + + You can also pass a default that covers the entire operation, + should the lookup fail at any level. + + Args: + root: The target nesting of dictionaries, lists, or other + objects supporting ``__getitem__``. + path (tuple): A sequence of strings and integers to be successively + looked up within *root*. A dot-separated (``a.b``) string may + also be passed. + default: The value to be returned should any + ``PathAccessError`` exceptions be raised. + """ + if isinstance(path, str): + path = path.split('.') + cur = root + try: + for seg in path: + try: + cur = cur[seg] + except (KeyError, IndexError) as exc: + raise PathAccessError(exc, seg, path) + except TypeError as exc: + # either string index in a list, or a parent that + # doesn't support indexing + try: + seg = int(seg) + cur = cur[seg] + except (ValueError, KeyError, IndexError, TypeError): + if not is_iterable(cur): + exc = TypeError('%r object is not indexable' + % type(cur).__name__) + raise PathAccessError(exc, seg, path) + except PathAccessError: + if default is _UNSET: + raise + return default + return cur + + +def research(root, query=lambda p, k, v: True, reraise=False, enter=default_enter): + """The :func:`research` function uses :func:`remap` to recurse over + any data nested in *root*, and find values which match a given + criterion, specified by the *query* callable. + + Results are returned as a list of ``(path, value)`` pairs. The + paths are tuples in the same format accepted by + :func:`get_path`. This can be useful for comparing values nested + in two or more different structures. + + Here's a simple example that finds all integers: + + >>> root = {'a': {'b': 1, 'c': (2, 'd', 3)}, 'e': None} + >>> res = research(root, query=lambda p, k, v: isinstance(v, int)) + >>> print(sorted(res)) + [(('a', 'b'), 1), (('a', 'c', 0), 2), (('a', 'c', 2), 3)] + + Note how *query* follows the same, familiar ``path, key, value`` + signature as the ``visit`` and ``enter`` functions on + :func:`remap`, and returns a :class:`bool`. + + Args: + root: The target object to search. Supports the same types of + objects as :func:`remap`, including :class:`list`, + :class:`tuple`, :class:`dict`, and :class:`set`. + query (callable): The function called on every object to + determine whether to include it in the search results. The + callable must accept three arguments, *path*, *key*, and + *value*, commonly abbreviated *p*, *k*, and *v*, same as + *enter* and *visit* from :func:`remap`. + reraise (bool): Whether to reraise exceptions raised by *query* + or to simply drop the result that caused the error. + + + With :func:`research` it's easy to inspect the details of a data + structure, like finding values that are at a certain depth (using + ``len(p)``) and much more. If more advanced functionality is + needed, check out the code and make your own :func:`remap` + wrapper, and consider `submitting a patch`_! + + .. _submitting a patch: https://github.com/mahmoud/boltons/pulls + """ + ret = [] + + if not callable(query): + raise TypeError('query expected callable, not: %r' % query) + + def _enter(path, key, value): + try: + if query(path, key, value): + ret.append((path + (key,), value)) + except Exception: + if reraise: + raise + return enter(path, key, value) + + remap(root, enter=_enter) + return ret + + +# TODO: recollect() +# TODO: refilter() +# TODO: reiter() + + +# GUID iterators: 10x faster and somewhat more compact than uuid. + +class GUIDerator: + """The GUIDerator is an iterator that yields a globally-unique + identifier (GUID) on every iteration. The GUIDs produced are + hexadecimal strings. + + Testing shows it to be around 12x faster than the uuid module. By + default it is also more compact, partly due to its default 96-bit + (24-hexdigit) length. 96 bits of randomness means that there is a + 1 in 2 ^ 32 chance of collision after 2 ^ 64 iterations. If more + or less uniqueness is desired, the *size* argument can be adjusted + accordingly. + + Args: + size (int): character length of the GUID, defaults to 24. Lengths + between 20 and 36 are considered valid. + + The GUIDerator has built-in fork protection that causes it to + detect a fork on next iteration and reseed accordingly. + + """ + + def __init__(self, size=24): + self.size = size + if size < 20 or size > 36: + raise ValueError('expected 20 < size <= 36') + import hashlib + self._sha1 = hashlib.sha1 + self.count = itertools.count() + self.reseed() + + def reseed(self): + import socket + self.pid = os.getpid() + self.salt = '-'.join([str(self.pid), + socket.gethostname() or '', + str(time.time()), + os.urandom(6).hex()]) + return + + def __iter__(self): + return self + + def __next__(self): + if os.getpid() != self.pid: + self.reseed() + target_bytes = (self.salt + str(next(self.count))).encode('utf8') + hash_text = self._sha1(target_bytes).hexdigest()[:self.size] + return hash_text + + next = __next__ + + +class SequentialGUIDerator(GUIDerator): + """Much like the standard GUIDerator, the SequentialGUIDerator is an + iterator that yields a globally-unique identifier (GUID) on every + iteration. The GUIDs produced are hexadecimal strings. + + The SequentialGUIDerator differs in that it picks a starting GUID + value and increments every iteration. This yields GUIDs which are + of course unique, but also ordered and lexicographically sortable. + + The SequentialGUIDerator is around 50% faster than the normal + GUIDerator, making it almost 20x as fast as the built-in uuid + module. By default it is also more compact, partly due to its + 96-bit (24-hexdigit) default length. 96 bits of randomness means that + there is a 1 in 2 ^ 32 chance of collision after 2 ^ 64 + iterations. If more or less uniqueness is desired, the *size* + argument can be adjusted accordingly. + + Args: + size (int): character length of the GUID, defaults to 24. + + Note that with SequentialGUIDerator there is a chance of GUIDs + growing larger than the size configured. The SequentialGUIDerator + has built-in fork protection that causes it to detect a fork on + next iteration and reseed accordingly. + + """ + + def reseed(self): + super().reseed() + start_str = self._sha1(self.salt.encode('utf8')).hexdigest() + self.start = int(start_str[:self.size], 16) + self.start |= (1 << ((self.size * 4) - 2)) + + def __next__(self): + if os.getpid() != self.pid: + self.reseed() + return '%x' % (next(self.count) + self.start) + + next = __next__ + + +guid_iter = GUIDerator() +seq_guid_iter = SequentialGUIDerator() + + +def soft_sorted(iterable, first=None, last=None, key=None, reverse=False): + """For when you care about the order of some elements, but not about + others. + + Use this to float to the top and/or sink to the bottom a specific + ordering, while sorting the rest of the elements according to + normal :func:`sorted` rules. + + >>> soft_sorted(['two', 'b', 'one', 'a'], first=['one', 'two']) + ['one', 'two', 'a', 'b'] + >>> soft_sorted(range(7), first=[6, 15], last=[2, 4], reverse=True) + [6, 5, 3, 1, 0, 2, 4] + >>> import string + >>> ''.join(soft_sorted(string.hexdigits, first='za1', last='b', key=str.lower)) + 'aA1023456789cCdDeEfFbB' + + Args: + iterable (list): A list or other iterable to sort. + first (list): A sequence to enforce for elements which should + appear at the beginning of the returned list. + last (list): A sequence to enforce for elements which should + appear at the end of the returned list. + key (callable): Callable used to generate a comparable key for + each item to be sorted, same as the key in + :func:`sorted`. Note that entries in *first* and *last* + should be the keys for the items. Defaults to + passthrough/the identity function. + reverse (bool): Whether or not elements not explicitly ordered + by *first* and *last* should be in reverse order or not. + + Returns a new list in sorted order. + """ + first = first or [] + last = last or [] + key = key or (lambda x: x) + seq = list(iterable) + other = [x for x in seq if not ( + (first and key(x) in first) or (last and key(x) in last))] + other.sort(key=key, reverse=reverse) + + if first: + first = sorted([x for x in seq if key(x) in first], + key=lambda x: first.index(key(x))) + if last: + last = sorted([x for x in seq if key(x) in last], + key=lambda x: last.index(key(x))) + return first + other + last + + +def untyped_sorted(iterable, key=None, reverse=False): + """A version of :func:`sorted` which will happily sort an iterable of + heterogeneous types and return a new list, similar to legacy Python's + behavior. + + >>> untyped_sorted(['abc', 2.0, 1, 2, 'def']) + [1, 2.0, 2, 'abc', 'def'] + + Note how mutually orderable types are sorted as expected, as in + the case of the integers and floats above. + + .. note:: + + Results may vary across Python versions and builds, but the + function will produce a sorted list, except in the case of + explicitly unorderable objects. + + """ + class _Wrapper: + slots = ('obj',) + + def __init__(self, obj): + self.obj = obj + + def __lt__(self, other): + obj = key(self.obj) if key is not None else self.obj + other = key(other.obj) if key is not None else other.obj + try: + ret = obj < other + except TypeError: + ret = ((type(obj).__name__, id(type(obj)), obj) + < (type(other).__name__, id(type(other)), other)) + return ret + + if key is not None and not callable(key): + raise TypeError('expected function or callable object for key, not: %r' + % key) + + return sorted(iterable, key=_Wrapper, reverse=reverse) + + +""" +May actually be faster to do an isinstance check for a str path + +$ python -m timeit -s "x = [1]" "x[0]" +10000000 loops, best of 3: 0.0207 usec per loop +$ python -m timeit -s "x = [1]" "try: x[0] \nexcept: pass" +10000000 loops, best of 3: 0.029 usec per loop +$ python -m timeit -s "x = [1]" "try: x[1] \nexcept: pass" +1000000 loops, best of 3: 0.315 usec per loop +# setting up try/except is fast, only around 0.01us +# actually triggering the exception takes almost 10x as long + +$ python -m timeit -s "x = [1]" "isinstance(x, basestring)" +10000000 loops, best of 3: 0.141 usec per loop +$ python -m timeit -s "x = [1]" "isinstance(x, str)" +10000000 loops, best of 3: 0.131 usec per loop +$ python -m timeit -s "x = [1]" "try: x.split('.')\n except: pass" +1000000 loops, best of 3: 0.443 usec per loop +$ python -m timeit -s "x = [1]" "try: x.split('.') \nexcept AttributeError: pass" +1000000 loops, best of 3: 0.544 usec per loop +""" diff --git a/miniconda3/lib/python3.13/site-packages/boltons/jsonutils.py b/miniconda3/lib/python3.13/site-packages/boltons/jsonutils.py new file mode 100644 index 0000000000000000000000000000000000000000..bf61b03a3b1d43e534f268f6dec577781c53eab3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/jsonutils.py @@ -0,0 +1,267 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""``jsonutils`` aims to provide various helpers for working with +JSON. Currently it focuses on providing a reliable and intuitive means +of working with `JSON Lines`_-formatted files. + +.. _JSON Lines: http://jsonlines.org/ + +""" + + +import io +import os +import json + + +DEFAULT_BLOCKSIZE = 4096 + + +__all__ = ['JSONLIterator', 'reverse_iter_lines'] + + +def reverse_iter_lines(file_obj, blocksize=DEFAULT_BLOCKSIZE, preseek=True, encoding=None): + """Returns an iterator over the lines from a file object, in + reverse order, i.e., last line first, first line last. Uses the + :meth:`file.seek` method of file objects, and is tested compatible with + :class:`file` objects, as well as :class:`StringIO.StringIO`. + + Args: + file_obj (file): An open file object. Note that + ``reverse_iter_lines`` mutably reads from the file and + other functions should not mutably interact with the file + object after being passed. Files can be opened in bytes or + text mode. + blocksize (int): The block size to pass to + :meth:`file.read()`. Warning: keep this a fairly large + multiple of 2, defaults to 4096. + preseek (bool): Tells the function whether or not to automatically + seek to the end of the file. Defaults to ``True``. + ``preseek=False`` is useful in cases when the + file cursor is already in position, either at the end of + the file or in the middle for relative reverse line + generation. + + """ + # This function is a bit of a pain because it attempts to be byte/text agnostic + try: + encoding = encoding or file_obj.encoding + except AttributeError: + # BytesIO + encoding = None + else: + encoding = 'utf-8' + + # need orig_obj to keep alive otherwise __del__ on the TextWrapper will close the file + orig_obj = file_obj + try: + file_obj = orig_obj.detach() + except (AttributeError, io.UnsupportedOperation): + pass + + empty_bytes, newline_bytes, empty_text = b'', b'\n', '' + + if preseek: + file_obj.seek(0, os.SEEK_END) + buff = empty_bytes + cur_pos = file_obj.tell() + while 0 < cur_pos: + read_size = min(blocksize, cur_pos) + cur_pos -= read_size + file_obj.seek(cur_pos, os.SEEK_SET) + cur = file_obj.read(read_size) + buff = cur + buff + lines = buff.splitlines() + + if len(lines) < 2 or lines[0] == empty_bytes: + continue + if buff[-1:] == newline_bytes: + yield empty_text if encoding else empty_bytes + for line in lines[:0:-1]: + yield line.decode(encoding) if encoding else line + buff = lines[0] + if buff: + yield buff.decode(encoding) if encoding else buff + + + +""" +TODO: allow passthroughs for: + +json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]]) +""" + + +class JSONLIterator: + """The ``JSONLIterator`` is used to iterate over JSON-encoded objects + stored in the `JSON Lines format`_ (one object per line). + + Most notably it has the ability to efficiently read from the + bottom of files, making it very effective for reading in simple + append-only JSONL use cases. It also has the ability to start from + anywhere in the file and ignore corrupted lines. + + Args: + file_obj (file): An open file object. + ignore_errors (bool): Whether to skip over lines that raise an error on + deserialization (:func:`json.loads`). + reverse (bool): Controls the direction of the iteration. + Defaults to ``False``. If set to ``True`` and *rel_seek* + is unset, seeks to the end of the file before iteration + begins. + rel_seek (float): Used to preseek the start position of + iteration. Set to 0.0 for the start of the file, 1.0 for the + end, and anything in between. + + .. _JSON Lines format: http://jsonlines.org/ + """ + def __init__(self, file_obj, + ignore_errors=False, reverse=False, rel_seek=None): + self._reverse = bool(reverse) + self._file_obj = file_obj + self.ignore_errors = ignore_errors + + if rel_seek is None: + if reverse: + rel_seek = 1.0 + elif not -1.0 < rel_seek < 1.0: + raise ValueError("'rel_seek' expected a float between" + " -1.0 and 1.0, not %r" % rel_seek) + elif rel_seek < 0: + rel_seek = 1.0 - rel_seek + self._rel_seek = rel_seek + self._blocksize = 4096 + if rel_seek is not None: + self._init_rel_seek() + if self._reverse: + self._line_iter = reverse_iter_lines(self._file_obj, + blocksize=self._blocksize, + preseek=False) + else: + self._line_iter = iter(self._file_obj) + + @property + def cur_byte_pos(self): + "A property representing where in the file the iterator is reading." + return self._file_obj.tell() + + def _align_to_newline(self): + "Aligns the file object's position to the next newline." + fo, bsize = self._file_obj, self._blocksize + cur, total_read = '', 0 + cur_pos = fo.tell() + while '\n' not in cur: + cur = fo.read(bsize) + total_read += bsize + try: + newline_offset = cur.index('\n') + total_read - bsize + except ValueError: + raise # TODO: seek to end? + fo.seek(cur_pos + newline_offset) + + def _init_rel_seek(self): + "Sets the file object's position to the relative location set above." + rs, fo = self._rel_seek, self._file_obj + if rs == 0.0: + fo.seek(0, os.SEEK_SET) + else: + fo.seek(0, os.SEEK_END) + size = fo.tell() + if rs == 1.0: + self._cur_pos = size + else: + target = int(size * rs) + fo.seek(target, os.SEEK_SET) + self._align_to_newline() + self._cur_pos = fo.tell() + + def __iter__(self): + return self + + def next(self): + """Yields one :class:`dict` loaded with :func:`json.loads`, advancing + the file object by one line. Raises :exc:`StopIteration` upon reaching + the end of the file (or beginning, if ``reverse`` was set to ``True``. + """ + while 1: + line = next(self._line_iter).lstrip() + if not line: + continue + try: + obj = json.loads(line) + except Exception: + if not self.ignore_errors: + raise + continue + return obj + + __next__ = next + + +if __name__ == '__main__': + def _main(): + import sys + if '-h' in sys.argv or '--help' in sys.argv: + print('loads one or more JSON Line files for basic validation.') + return + verbose = False + if '-v' in sys.argv or '--verbose' in sys.argv: + verbose = True + file_count, obj_count = 0, 0 + filenames = sys.argv[1:] + for filename in filenames: + if filename in ('-h', '--help', '-v', '--verbose'): + continue + file_count += 1 + with open(filename, 'rb') as file_obj: + iterator = JSONLIterator(file_obj) + cur_obj_count = 0 + while 1: + try: + next(iterator) + except ValueError: + print('error reading object #%s around byte %s in %s' + % (cur_obj_count + 1, iterator.cur_byte_pos, filename)) + return + except StopIteration: + break + obj_count += 1 + cur_obj_count += 1 + if verbose and obj_count and obj_count % 100 == 0: + sys.stdout.write('.') + if obj_count % 10000: + sys.stdout.write('%s\n' % obj_count) + if verbose: + print('files checked: %s' % file_count) + print('objects loaded: %s' % obj_count) + return + + _main() diff --git a/miniconda3/lib/python3.13/site-packages/boltons/listutils.py b/miniconda3/lib/python3.13/site-packages/boltons/listutils.py new file mode 100644 index 0000000000000000000000000000000000000000..06b9da28f74488d45b98a8f949d7e34cfd930160 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/listutils.py @@ -0,0 +1,350 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's builtin :class:`list` is a very fast and efficient +sequence type, but it could be better for certain access patterns, +such as non-sequential insertion into a large lists. ``listutils`` +provides a pure-Python solution to this problem. + +For utilities for working with iterables and lists, check out +:mod:`iterutils`. For the a :class:`list`-based version of +:class:`collections.namedtuple`, check out :mod:`namedutils`. +""" + + +import operator +from math import log as math_log +from itertools import chain, islice + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + +# TODO: expose splaylist? +__all__ = ['BList', 'BarrelList'] + + +# TODO: comparators +# TODO: keep track of list lengths and bisect to the right list for +# faster getitem (and slightly slower setitem and delitem ops) + +class BarrelList(list): + """The ``BarrelList`` is a :class:`list` subtype backed by many + dynamically-scaled sublists, to provide better scaling and random + insertion/deletion characteristics. It is a subtype of the builtin + :class:`list` and has an identical API, supporting indexing, + slicing, sorting, etc. If application requirements call for + something more performant, consider the `blist module available on + PyPI`_. + + The name comes by way of Kurt Rose, who said it reminded him of + barrel shifters. Not sure how, but it's BList-like, so the name + stuck. BList is of course a reference to `B-trees`_. + + Args: + iterable: An optional iterable of initial values for the list. + + >>> blist = BList(range(100000)) + >>> blist.pop(50000) + 50000 + >>> len(blist) + 99999 + >>> len(blist.lists) # how many underlying lists + 8 + >>> slice_idx = blist.lists[0][-1] + >>> blist[slice_idx:slice_idx + 2] + BarrelList([11637, 11638]) + + Slicing is supported and works just fine across list borders, + returning another instance of the BarrelList. + + .. _blist module available on PyPI: https://pypi.python.org/pypi/blist + .. _B-trees: https://en.wikipedia.org/wiki/B-tree + + """ + + _size_factor = 1520 + "This size factor is the result of tuning using the tune() function below." + + def __init__(self, iterable=None): + self.lists = [[]] + if iterable: + self.extend(iterable) + + @property + def _cur_size_limit(self): + len_self, size_factor = len(self), self._size_factor + return int(round(size_factor * math_log(len_self + 2, 2))) + + def _translate_index(self, index): + if index < 0: + index += len(self) + rel_idx, lists = index, self.lists + for list_idx in range(len(lists)): + len_list = len(lists[list_idx]) + if rel_idx < len_list: + break + rel_idx -= len_list + if rel_idx < 0: + return None, None + return list_idx, rel_idx + + def _balance_list(self, list_idx): + if list_idx < 0: + list_idx += len(self.lists) + cur_list, len_self = self.lists[list_idx], len(self) + size_limit = self._cur_size_limit + if len(cur_list) > size_limit: + half_limit = size_limit // 2 + while len(cur_list) > half_limit: + next_list_idx = list_idx + 1 + self.lists.insert(next_list_idx, cur_list[-half_limit:]) + del cur_list[-half_limit:] + return True + return False + + def insert(self, index, item): + if len(self.lists) == 1: + self.lists[0].insert(index, item) + self._balance_list(0) + else: + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + self.lists[list_idx].insert(rel_idx, item) + self._balance_list(list_idx) + return + + def append(self, item): + self.lists[-1].append(item) + + def extend(self, iterable): + self.lists[-1].extend(iterable) + + def pop(self, *a): + lists = self.lists + if len(lists) == 1 and not a: + return self.lists[0].pop() + index = a and a[0] + if index == () or index is None or index == -1: + ret = lists[-1].pop() + if len(lists) > 1 and not lists[-1]: + lists.pop() + else: + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + ret = lists[list_idx].pop(rel_idx) + self._balance_list(list_idx) + return ret + + def iter_slice(self, start, stop, step=None): + iterable = self # TODO: optimization opportunities abound + # start_list_idx, stop_list_idx = 0, len(self.lists) + if start is None: + start = 0 + if stop is None: + stop = len(self) + if step is not None and step < 0: + step = -step + start, stop = -start, -stop - 1 + iterable = reversed(self) + if start < 0: + start += len(self) + # start_list_idx, start_rel_idx = self._translate_index(start) + if stop < 0: + stop += len(self) + # stop_list_idx, stop_rel_idx = self._translate_index(stop) + return islice(iterable, start, stop, step) + + def del_slice(self, start, stop, step=None): + if step is not None and abs(step) > 1: # punt + new_list = chain(self.iter_slice(0, start, step), + self.iter_slice(stop, None, step)) + self.lists[0][:] = new_list + self._balance_list(0) + return + if start is None: + start = 0 + if stop is None: + stop = len(self) + start_list_idx, start_rel_idx = self._translate_index(start) + stop_list_idx, stop_rel_idx = self._translate_index(stop) + if start_list_idx is None: + raise IndexError() + if stop_list_idx is None: + raise IndexError() + + if start_list_idx == stop_list_idx: + del self.lists[start_list_idx][start_rel_idx:stop_rel_idx] + elif start_list_idx < stop_list_idx: + del self.lists[start_list_idx + 1:stop_list_idx] + del self.lists[start_list_idx][start_rel_idx:] + del self.lists[stop_list_idx][:stop_rel_idx] + else: + assert False, ('start list index should never translate to' + ' greater than stop list index') + + __delslice__ = del_slice + + @classmethod + def from_iterable(cls, it): + return cls(it) + + def __iter__(self): + return chain.from_iterable(self.lists) + + def __reversed__(self): + return chain.from_iterable(reversed(l) for l in reversed(self.lists)) + + def __len__(self): + return sum([len(l) for l in self.lists]) + + def __contains__(self, item): + for cur in self.lists: + if item in cur: + return True + return False + + def __getitem__(self, index): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + iter_slice = self.iter_slice(start, stop, step) + ret = self.from_iterable(iter_slice) + return ret + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + return self.lists[list_idx][rel_idx] + + def __delitem__(self, index): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + self.del_slice(start, stop, step) + return + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + del self.lists[list_idx][rel_idx] + + def __setitem__(self, index, item): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + if len(self.lists) == 1: + self.lists[0][index] = item + else: + tmp = list(self) + tmp[index] = item + self.lists[:] = [tmp] + self._balance_list(0) + return + list_idx, rel_idx = self._translate_index(index) + if list_idx is None: + raise IndexError() + self.lists[list_idx][rel_idx] = item + + def __getslice__(self, start, stop): + iter_slice = self.iter_slice(start, stop, 1) + return self.from_iterable(iter_slice) + + def __setslice__(self, start, stop, sequence): + if len(self.lists) == 1: + self.lists[0][start:stop] = sequence + else: + tmp = list(self) + tmp[start:stop] = sequence + self.lists[:] = [tmp] + self._balance_list(0) + return + + def __repr__(self): + return f'{self.__class__.__name__}({list(self)!r})' + + def sort(self): + # poor pythonist's mergesort, it's faster than sorted(self) + # when the lists' average length is greater than 512. + if len(self.lists) == 1: + self.lists[0].sort() + else: + for li in self.lists: + li.sort() + tmp_sorted = sorted(chain.from_iterable(self.lists)) + del self.lists[:] + self.lists[0] = tmp_sorted + self._balance_list(0) + + def reverse(self): + for cur in self.lists: + cur.reverse() + self.lists.reverse() + + def count(self, item): + return sum([cur.count(item) for cur in self.lists]) + + def index(self, item): + len_accum = 0 + for cur in self.lists: + try: + rel_idx = cur.index(item) + return len_accum + rel_idx + except ValueError: + len_accum += len(cur) + raise ValueError(f'{item!r} is not in list') + + +BList = BarrelList + + +class SplayList(list): + """Like a `splay tree`_, the SplayList facilitates moving higher + utility items closer to the front of the list for faster access. + + .. _splay tree: https://en.wikipedia.org/wiki/Splay_tree + """ + + def shift(self, item_index, dest_index=0): + if item_index == dest_index: + return + item = self.pop(item_index) + self.insert(dest_index, item) + + def swap(self, item_index, dest_index): + self[dest_index], self[item_index] = self[item_index], self[dest_index] diff --git a/miniconda3/lib/python3.13/site-packages/boltons/mathutils.py b/miniconda3/lib/python3.13/site-packages/boltons/mathutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1367a5413bbb9c6f3754da50c33b073641ac40df --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/mathutils.py @@ -0,0 +1,249 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""This module provides useful math functions on top of Python's +built-in :mod:`math` module. +""" + +from math import ceil as _ceil, floor as _floor +import bisect +import binascii + + +def clamp(x, lower=float('-inf'), upper=float('inf')): + """Limit a value to a given range. + + Args: + x (int or float): Number to be clamped. + lower (int or float): Minimum value for x. + upper (int or float): Maximum value for x. + + The returned value is guaranteed to be between *lower* and + *upper*. Integers, floats, and other comparable types can be + mixed. + + >>> clamp(1.0, 0, 5) + 1.0 + >>> clamp(-1.0, 0, 5) + 0 + >>> clamp(101.0, 0, 5) + 5 + >>> clamp(123, upper=5) + 5 + + Similar to `numpy's clip`_ function. + + .. _numpy's clip: http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html + + """ + if upper < lower: + raise ValueError('expected upper bound (%r) >= lower bound (%r)' + % (upper, lower)) + return min(max(x, lower), upper) + + +def ceil(x, options=None): + """Return the ceiling of *x*. If *options* is set, return the smallest + integer or float from *options* that is greater than or equal to + *x*. + + Args: + x (int or float): Number to be tested. + options (iterable): Optional iterable of arbitrary numbers + (ints or floats). + + >>> VALID_CABLE_CSA = [1.5, 2.5, 4, 6, 10, 25, 35, 50] + >>> ceil(3.5, options=VALID_CABLE_CSA) + 4 + >>> ceil(4, options=VALID_CABLE_CSA) + 4 + """ + if options is None: + return _ceil(x) + options = sorted(options) + i = bisect.bisect_left(options, x) + if i == len(options): + raise ValueError("no ceil options greater than or equal to: %r" % x) + return options[i] + + +def floor(x, options=None): + """Return the floor of *x*. If *options* is set, return the largest + integer or float from *options* that is less than or equal to + *x*. + + Args: + x (int or float): Number to be tested. + options (iterable): Optional iterable of arbitrary numbers + (ints or floats). + + >>> VALID_CABLE_CSA = [1.5, 2.5, 4, 6, 10, 25, 35, 50] + >>> floor(3.5, options=VALID_CABLE_CSA) + 2.5 + >>> floor(2.5, options=VALID_CABLE_CSA) + 2.5 + + """ + if options is None: + return _floor(x) + options = sorted(options) + + i = bisect.bisect_right(options, x) + if not i: + raise ValueError("no floor options less than or equal to: %r" % x) + return options[i - 1] + + +class Bits: + ''' + An immutable bit-string or bit-array object. + Provides list-like access to bits as bools, + as well as bitwise masking and shifting operators. + Bits also make it easy to convert between many + different useful representations: + + * bytes -- good for serializing raw binary data + * int -- good for incrementing (e.g. to try all possible values) + * list of bools -- good for iterating over or treating as flags + * hex/bin string -- good for human readability + + ''' + __slots__ = ('val', 'len') + + def __init__(self, val=0, len_=None): + if type(val) is not int: + if type(val) is list: + val = ''.join(['1' if e else '0' for e in val]) + if type(val) is bytes: + val = val.decode('ascii') + if type(val) is str: + if len_ is None: + len_ = len(val) + if val.startswith('0x'): + len_ = (len_ - 2) * 4 + if val.startswith('0x'): + val = int(val, 16) + else: + if val: + val = int(val, 2) + else: + val = 0 + if type(val) is not int: + raise TypeError(f'initialized with bad type: {type(val).__name__}') + if val < 0: + raise ValueError('Bits cannot represent negative values') + if len_ is None: + len_ = len(f'{val:b}') + if val > 2 ** len_: + raise ValueError(f'value {val} cannot be represented with {len_} bits') + self.val = val # data is stored internally as integer + self.len = len_ + + def __getitem__(self, k): + if type(k) is slice: + return Bits(self.as_bin()[k]) + if type(k) is int: + if k >= self.len: + raise IndexError(k) + return bool((1 << (self.len - k - 1)) & self.val) + raise TypeError(type(k)) + + def __len__(self): + return self.len + + def __eq__(self, other): + if type(self) is not type(other): + return NotImplemented + return self.val == other.val and self.len == other.len + + def __or__(self, other): + if type(self) is not type(other): + return NotImplemented + return Bits(self.val | other.val, max(self.len, other.len)) + + def __and__(self, other): + if type(self) is not type(other): + return NotImplemented + return Bits(self.val & other.val, max(self.len, other.len)) + + def __lshift__(self, other): + return Bits(self.val << other, self.len + other) + + def __rshift__(self, other): + return Bits(self.val >> other, self.len - other) + + def __hash__(self): + return hash(self.val) + + def as_list(self): + return [c == '1' for c in self.as_bin()] + + def as_bin(self): + return f'{{0:0{self.len}b}}'.format(self.val) + + def as_hex(self): + # make template to pad out to number of bytes necessary to represent bits + tmpl = f'%0{2 * (self.len // 8 + ((self.len % 8) != 0))}X' + ret = tmpl % self.val + return ret + + def as_int(self): + return self.val + + def as_bytes(self): + return binascii.unhexlify(self.as_hex()) + + @classmethod + def from_list(cls, list_): + return cls(list_) + + @classmethod + def from_bin(cls, bin): + return cls(bin) + + @classmethod + def from_hex(cls, hex): + if isinstance(hex, bytes): + hex = hex.decode('ascii') + if not hex.startswith('0x'): + hex = '0x' + hex + return cls(hex) + + @classmethod + def from_int(cls, int_, len_=None): + return cls(int_, len_) + + @classmethod + def from_bytes(cls, bytes_): + return cls.from_hex(binascii.hexlify(bytes_)) + + def __repr__(self): + cn = self.__class__.__name__ + return f"{cn}('{self.as_bin()}')" diff --git a/miniconda3/lib/python3.13/site-packages/boltons/mboxutils.py b/miniconda3/lib/python3.13/site-packages/boltons/mboxutils.py new file mode 100644 index 0000000000000000000000000000000000000000..299d105955a2f303190f2e52b75d8e81b590852c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/mboxutils.py @@ -0,0 +1,150 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Useful utilities for working with the `mbox`_-formatted +mailboxes. Credit to Mark Williams for these. + +.. _mbox: https://en.wikipedia.org/wiki/Mbox +""" + +import mailbox +import tempfile + + +DEFAULT_MAXMEM = 4 * 1024 * 1024 # 4MB + + +class mbox_readonlydir(mailbox.mbox): + """A subclass of :class:`mailbox.mbox` suitable for use with mboxs + insides a read-only mail directory, e.g., ``/var/mail``. Otherwise + the API is exactly the same as the built-in mbox. + + Deletes messages via truncation, in the manner of `Heirloom mailx`_. + + Args: + path (str): Path to the mbox file. + factory (type): Message type (defaults to :class:`rfc822.Message`) + create (bool): Create mailbox if it does not exist. (defaults + to ``True``) + maxmem (int): Specifies, in bytes, the largest sized mailbox + to attempt to copy into memory. Larger mailboxes + will be copied incrementally which is more + hazardous. (defaults to 4MB) + + .. note:: + + Because this truncates and rewrites parts of the mbox file, + this class can corrupt your mailbox. Only use this if you know + the built-in :class:`mailbox.mbox` does not work for your use + case. + + .. _Heirloom mailx: http://heirloom.sourceforge.net/mailx.html + """ + def __init__(self, path, factory=None, create=True, maxmem=1024 * 1024): + mailbox.mbox.__init__(self, path, factory, create) + self.maxmem = maxmem + + def flush(self): + """Write any pending changes to disk. This is called on mailbox + close and is usually not called explicitly. + + .. note:: + + This deletes messages via truncation. Interruptions may + corrupt your mailbox. + """ + + # Appending and basic assertions are the same as in mailbox.mbox.flush. + if not self._pending: + if self._pending_sync: + # Messages have only been added, so syncing the file + # is enough. + mailbox._sync_flush(self._file) + self._pending_sync = False + return + + # In order to be writing anything out at all, self._toc must + # already have been generated (and presumably has been modified + # by adding or deleting an item). + assert self._toc is not None + + # Check length of self._file; if it's changed, some other process + # has modified the mailbox since we scanned it. + self._file.seek(0, 2) + cur_len = self._file.tell() + if cur_len != self._file_length: + raise mailbox.ExternalClashError('Size of mailbox file changed ' + '(expected %i, found %i)' % + (self._file_length, cur_len)) + + self._file.seek(0) + + # Truncation logic begins here. Mostly the same except we + # can use tempfile because we're not doing rename(2). + with tempfile.TemporaryFile() as new_file: + new_toc = {} + self._pre_mailbox_hook(new_file) + for key in sorted(self._toc.keys()): + start, stop = self._toc[key] + self._file.seek(start) + self._pre_message_hook(new_file) + new_start = new_file.tell() + while True: + buffer = self._file.read(min(4096, + stop - self._file.tell())) + if buffer == '': + break + new_file.write(buffer) + new_toc[key] = (new_start, new_file.tell()) + self._post_message_hook(new_file) + self._file_length = new_file.tell() + + self._file.seek(0) + new_file.seek(0) + + # Copy back our messages + if self._file_length <= self.maxmem: + self._file.write(new_file.read()) + else: + while True: + buffer = new_file.read(4096) + if not buffer: + break + self._file.write(buffer) + + # Delete the rest. + self._file.truncate() + + # Same wrap up. + self._toc = new_toc + self._pending = False + self._pending_sync = False + if self._locked: + mailbox._lock_file(self._file, dotlock=False) diff --git a/miniconda3/lib/python3.13/site-packages/boltons/namedutils.py b/miniconda3/lib/python3.13/site-packages/boltons/namedutils.py new file mode 100644 index 0000000000000000000000000000000000000000..0311f81468b69822335e0c3299c431a28d17aa9e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/namedutils.py @@ -0,0 +1,385 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""\ +The ``namedutils`` module defines two lightweight container types: +:class:`namedtuple` and :class:`namedlist`. Both are subtypes of built-in +sequence types, which are very fast and efficient. They simply add +named attribute accessors for specific indexes within themselves. + +The :class:`namedtuple` is identical to the built-in +:class:`collections.namedtuple`, with a couple of enhancements, +including a ``__repr__`` more suitable to inheritance. + +The :class:`namedlist` is the mutable counterpart to the +:class:`namedtuple`, and is much faster and lighter-weight than +full-blown :class:`object`. Consider this if you're implementing nodes +in a tree, graph, or other mutable data structure. If you want an even +skinnier approach, you'll probably have to look to C. +""" + + +import sys as _sys +from collections import OrderedDict +from keyword import iskeyword as _iskeyword +from operator import itemgetter as _itemgetter + + +__all__ = ['namedlist', 'namedtuple'] + +# Tiny templates + +_repr_tmpl = '{name}=%r' + +_imm_field_tmpl = '''\ + {name} = _property(_itemgetter({index:d}), doc='Alias for field {index:d}') +''' + +_m_field_tmpl = '''\ + {name} = _property(_itemgetter({index:d}), _itemsetter({index:d}), doc='Alias for field {index:d}') +''' + +################################################################# +### namedtuple +################################################################# + +_namedtuple_tmpl = '''\ +class {typename}(tuple): + '{typename}({arg_list})' + + __slots__ = () + + _fields = {field_names!r} + + def __new__(_cls, {arg_list}): # TODO: tweak sig to make more extensible + 'Create new instance of {typename}({arg_list})' + return _tuple.__new__(_cls, ({arg_list})) + + @classmethod + def _make(cls, iterable, new=_tuple.__new__, len=len): + 'Make a new {typename} object from a sequence or iterable' + result = new(cls, iterable) + if len(result) != {num_fields:d}: + raise TypeError('Expected {num_fields:d}' + ' arguments, got %d' % len(result)) + return result + + def __repr__(self): + 'Return a nicely formatted representation string' + tmpl = self.__class__.__name__ + '({repr_fmt})' + return tmpl % self + + def _asdict(self): + 'Return a new OrderedDict which maps field names to their values' + return OrderedDict(zip(self._fields, self)) + + def _replace(_self, **kwds): + 'Return a new {typename} object replacing field(s) with new values' + result = _self._make(map(kwds.pop, {field_names!r}, _self)) + if kwds: + raise ValueError('Got unexpected field names: %r' % kwds.keys()) + return result + + def __getnewargs__(self): + 'Return self as a plain tuple. Used by copy and pickle.' + return tuple(self) + + __dict__ = _property(_asdict) + + def __getstate__(self): + 'Exclude the OrderedDict from pickling' # wat + pass + +{field_defs} +''' + +def namedtuple(typename, field_names, verbose=False, rename=False): + """Returns a new subclass of tuple with named fields. + + >>> Point = namedtuple('Point', ['x', 'y']) + >>> Point.__doc__ # docstring for the new class + 'Point(x, y)' + >>> p = Point(11, y=22) # instantiate with pos args or keywords + >>> p[0] + p[1] # indexable like a plain tuple + 33 + >>> x, y = p # unpack like a regular tuple + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessible by name + 33 + >>> d = p._asdict() # convert to a dictionary + >>> d['x'] + 11 + >>> Point(**d) # convert from a dictionary + Point(x=11, y=22) + >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields + Point(x=100, y=22) + """ + + # Validate the field names. At the user's option, either generate an error + # message or automatically replace the field name with a valid name. + if isinstance(field_names, str): + field_names = field_names.replace(',', ' ').split() + field_names = [str(x) for x in field_names] + if rename: + seen = set() + for index, name in enumerate(field_names): + if (not all(c.isalnum() or c == '_' for c in name) + or _iskeyword(name) + or not name + or name[0].isdigit() + or name.startswith('_') + or name in seen): + field_names[index] = '_%d' % index + seen.add(name) + for name in [typename] + field_names: + if not all(c.isalnum() or c == '_' for c in name): + raise ValueError('Type names and field names can only contain ' + 'alphanumeric characters and underscores: %r' + % name) + if _iskeyword(name): + raise ValueError('Type names and field names cannot be a ' + 'keyword: %r' % name) + if name[0].isdigit(): + raise ValueError('Type names and field names cannot start with ' + 'a number: %r' % name) + seen = set() + for name in field_names: + if name.startswith('_') and not rename: + raise ValueError('Field names cannot start with an underscore: ' + '%r' % name) + if name in seen: + raise ValueError('Encountered duplicate field name: %r' % name) + seen.add(name) + + # Fill-in the class template + fmt_kw = {'typename': typename} + fmt_kw['field_names'] = tuple(field_names) + fmt_kw['num_fields'] = len(field_names) + fmt_kw['arg_list'] = repr(tuple(field_names)).replace("'", "")[1:-1] + fmt_kw['repr_fmt'] = ', '.join(_repr_tmpl.format(name=name) + for name in field_names) + fmt_kw['field_defs'] = '\n'.join(_imm_field_tmpl.format(index=index, name=name) + for index, name in enumerate(field_names)) + class_definition = _namedtuple_tmpl.format(**fmt_kw) + + if verbose: + print(class_definition) + + # Execute the template string in a temporary namespace and support + # tracing utilities by setting a value for frame.f_globals['__name__'] + namespace = dict(_itemgetter=_itemgetter, + __name__='namedtuple_%s' % typename, + OrderedDict=OrderedDict, + _property=property, + _tuple=tuple) + try: + exec(class_definition, namespace) + except SyntaxError as e: + raise SyntaxError(e.msg + ':\n' + class_definition) + result = namespace[typename] + + # For pickling to work, the __module__ variable needs to be set to the frame + # where the named tuple is created. Bypass this step in environments where + # sys._getframe is not defined (Jython for example) or sys._getframe is not + # defined for arguments greater than 0 (IronPython). + try: + frame = _sys._getframe(1) + result.__module__ = frame.f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + + return result + + +################################################################# +### namedlist +################################################################# + +_namedlist_tmpl = '''\ +class {typename}(list): + '{typename}({arg_list})' + + __slots__ = () + + _fields = {field_names!r} + + def __new__(_cls, {arg_list}): # TODO: tweak sig to make more extensible + 'Create new instance of {typename}({arg_list})' + return _list.__new__(_cls, ({arg_list})) + + def __init__(self, {arg_list}): # tuple didn't need this but list does + return _list.__init__(self, ({arg_list})) + + @classmethod + def _make(cls, iterable, new=_list, len=len): + 'Make a new {typename} object from a sequence or iterable' + # why did this function exist? why not just star the + # iterable like below? + result = cls(*iterable) + if len(result) != {num_fields:d}: + raise TypeError('Expected {num_fields:d} arguments,' + ' got %d' % len(result)) + return result + + def __repr__(self): + 'Return a nicely formatted representation string' + tmpl = self.__class__.__name__ + '({repr_fmt})' + return tmpl % tuple(self) + + def _asdict(self): + 'Return a new OrderedDict which maps field names to their values' + return OrderedDict(zip(self._fields, self)) + + def _replace(_self, **kwds): + 'Return a new {typename} object replacing field(s) with new values' + result = _self._make(map(kwds.pop, {field_names!r}, _self)) + if kwds: + raise ValueError('Got unexpected field names: %r' % kwds.keys()) + return result + + def __getnewargs__(self): + 'Return self as a plain list. Used by copy and pickle.' + return tuple(self) + + __dict__ = _property(_asdict) + + def __getstate__(self): + 'Exclude the OrderedDict from pickling' # wat + pass + +{field_defs} +''' + + +def namedlist(typename, field_names, verbose=False, rename=False): + """Returns a new subclass of list with named fields. + + >>> Point = namedlist('Point', ['x', 'y']) + >>> Point.__doc__ # docstring for the new class + 'Point(x, y)' + >>> p = Point(11, y=22) # instantiate with pos args or keywords + >>> p[0] + p[1] # indexable like a plain list + 33 + >>> x, y = p # unpack like a regular list + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessible by name + 33 + >>> d = p._asdict() # convert to a dictionary + >>> d['x'] + 11 + >>> Point(**d) # convert from a dictionary + Point(x=11, y=22) + >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields + Point(x=100, y=22) + """ + + # Validate the field names. At the user's option, either generate an error + # message or automatically replace the field name with a valid name. + if isinstance(field_names, str): + field_names = field_names.replace(',', ' ').split() + field_names = [str(x) for x in field_names] + if rename: + seen = set() + for index, name in enumerate(field_names): + if (not all(c.isalnum() or c == '_' for c in name) + or _iskeyword(name) + or not name + or name[0].isdigit() + or name.startswith('_') + or name in seen): + field_names[index] = '_%d' % index + seen.add(name) + for name in [typename] + field_names: + if not all(c.isalnum() or c == '_' for c in name): + raise ValueError('Type names and field names can only contain ' + 'alphanumeric characters and underscores: %r' + % name) + if _iskeyword(name): + raise ValueError('Type names and field names cannot be a ' + 'keyword: %r' % name) + if name[0].isdigit(): + raise ValueError('Type names and field names cannot start with ' + 'a number: %r' % name) + seen = set() + for name in field_names: + if name.startswith('_') and not rename: + raise ValueError('Field names cannot start with an underscore: ' + '%r' % name) + if name in seen: + raise ValueError('Encountered duplicate field name: %r' % name) + seen.add(name) + + # Fill-in the class template + fmt_kw = {'typename': typename} + fmt_kw['field_names'] = tuple(field_names) + fmt_kw['num_fields'] = len(field_names) + fmt_kw['arg_list'] = repr(tuple(field_names)).replace("'", "")[1:-1] + fmt_kw['repr_fmt'] = ', '.join(_repr_tmpl.format(name=name) + for name in field_names) + fmt_kw['field_defs'] = '\n'.join(_m_field_tmpl.format(index=index, name=name) + for index, name in enumerate(field_names)) + class_definition = _namedlist_tmpl.format(**fmt_kw) + + if verbose: + print(class_definition) + + def _itemsetter(key): + def _itemsetter(obj, value): + obj[key] = value + return _itemsetter + + # Execute the template string in a temporary namespace and support + # tracing utilities by setting a value for frame.f_globals['__name__'] + namespace = dict(_itemgetter=_itemgetter, + _itemsetter=_itemsetter, + __name__='namedlist_%s' % typename, + OrderedDict=OrderedDict, + _property=property, + _list=list) + try: + exec(class_definition, namespace) + except SyntaxError as e: + raise SyntaxError(e.msg + ':\n' + class_definition) + result = namespace[typename] + + # For pickling to work, the __module__ variable needs to be set to + # the frame where the named list is created. Bypass this step in + # environments where sys._getframe is not defined (Jython for + # example) or sys._getframe is not defined for arguments greater + # than 0 (IronPython). + try: + frame = _sys._getframe(1) + result.__module__ = frame.f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + + return result diff --git a/miniconda3/lib/python3.13/site-packages/boltons/pathutils.py b/miniconda3/lib/python3.13/site-packages/boltons/pathutils.py new file mode 100644 index 0000000000000000000000000000000000000000..a8cb2602f31b5920c67c03027684b01c22bf371c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/pathutils.py @@ -0,0 +1,183 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +Functions for working with filesystem paths. + +The :func:`expandpath` function expands the tilde to $HOME and environment +variables to their values. + +The :func:`augpath` function creates variants of an existing path without +having to spend multiple lines of code splitting it up and stitching it back +together. + +The :func:`shrinkuser` function replaces your home directory with a tilde. +""" + +from os.path import (expanduser, expandvars, join, normpath, split, splitext) +import os + + +__all__ = [ + 'augpath', 'shrinkuser', 'expandpath', +] + + +def augpath(path, suffix='', prefix='', ext=None, base=None, dpath=None, + multidot=False): + """ + Augment a path by modifying its components. + + Creates a new path with a different extension, basename, directory, prefix, + and/or suffix. + + A prefix is inserted before the basename. A suffix is inserted + between the basename and the extension. The basename and extension can be + replaced with a new one. Essentially a path is broken down into components + (dpath, base, ext), and then recombined as (dpath, prefix, base, suffix, + ext) after replacing any specified component. + + Args: + path (str | PathLike): a path to augment + suffix (str, default=''): placed between the basename and extension + prefix (str, default=''): placed in front of the basename + ext (str, default=None): if specified, replaces the extension + base (str, default=None): if specified, replaces the basename without + extension + dpath (str | PathLike, default=None): if specified, replaces the + directory + multidot (bool, default=False): Allows extensions to contain multiple + dots. Specifically, if False, everything after the last dot in the + basename is the extension. If True, everything after the first dot + in the basename is the extension. + + Returns: + str: augmented path + + Example: + >>> path = 'foo.bar' + >>> suffix = '_suff' + >>> prefix = 'pref_' + >>> ext = '.baz' + >>> newpath = augpath(path, suffix, prefix, ext=ext, base='bar') + >>> print('newpath = %s' % (newpath,)) + newpath = pref_bar_suff.baz + + Example: + >>> augpath('foo.bar') + 'foo.bar' + >>> augpath('foo.bar', ext='.BAZ') + 'foo.BAZ' + >>> augpath('foo.bar', suffix='_') + 'foo_.bar' + >>> augpath('foo.bar', prefix='_') + '_foo.bar' + >>> augpath('foo.bar', base='baz') + 'baz.bar' + >>> augpath('foo.tar.gz', ext='.zip', multidot=True) + 'foo.zip' + >>> augpath('foo.tar.gz', ext='.zip', multidot=False) + 'foo.tar.zip' + >>> augpath('foo.tar.gz', suffix='_new', multidot=True) + 'foo_new.tar.gz' + """ + # Breakup path + orig_dpath, fname = split(path) + if multidot: + # The first dot defines the extension + parts = fname.split('.', 1) + orig_base = parts[0] + orig_ext = '' if len(parts) == 1 else '.' + parts[1] + else: + # The last dot defines the extension + orig_base, orig_ext = splitext(fname) + # Replace parts with specified augmentations + if dpath is None: + dpath = orig_dpath + if ext is None: + ext = orig_ext + if base is None: + base = orig_base + # Recombine into new path + new_fname = ''.join((prefix, base, suffix, ext)) + newpath = join(dpath, new_fname) + return newpath + + +def shrinkuser(path, home='~'): + """ + Inverse of :func:`os.path.expanduser`. + + Args: + path (str | PathLike): path in system file structure + home (str, default='~'): symbol used to replace the home path. + Defaults to '~', but you might want to use '$HOME' or + '%USERPROFILE%' instead. + + Returns: + str: path: shortened path replacing the home directory with a tilde + + Example: + >>> path = expanduser('~') + >>> assert path != '~' + >>> assert shrinkuser(path) == '~' + >>> assert shrinkuser(path + '1') == path + '1' + >>> assert shrinkuser(path + '/1') == join('~', '1') + >>> assert shrinkuser(path + '/1', '$HOME') == join('$HOME', '1') + """ + path = normpath(path) + userhome_dpath = expanduser('~') + if path.startswith(userhome_dpath): + if len(path) == len(userhome_dpath): + path = home + elif path[len(userhome_dpath)] == os.path.sep: + path = home + path[len(userhome_dpath):] + return path + + +def expandpath(path): + """ + Shell-like expansion of environment variables and tilde home directory. + + Args: + path (str | PathLike): the path to expand + + Returns: + str : expanded path + + Example: + >>> import os + >>> os.environ['SPAM'] = 'eggs' + >>> assert expandpath('~/$SPAM') == expanduser('~/eggs') + >>> assert expandpath('foo') == 'foo' + """ + path = expanduser(path) + path = expandvars(path) + return path diff --git a/miniconda3/lib/python3.13/site-packages/boltons/queueutils.py b/miniconda3/lib/python3.13/site-packages/boltons/queueutils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6e4e4c28d0f0a394eb6deba7fec1f92b1344059 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/queueutils.py @@ -0,0 +1,223 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python comes with a many great data structures, from :class:`dict` +to :class:`collections.deque`, and no shortage of serviceable +algorithm implementations, from :func:`sorted` to :mod:`bisect`. But +priority queues are curiously relegated to an example documented in +:mod:`heapq`. Even there, the approach presented is not full-featured +and object-oriented. There is a built-in priority queue, +:class:`Queue.PriorityQueue`, but in addition to its austere API, it +carries the double-edged sword of threadsafety, making it fine for +multi-threaded, multi-consumer applications, but high-overhead for +cooperative/single-threaded use cases. + +The ``queueutils`` module currently provides two Queue +implementations: :class:`HeapPriorityQueue`, based on a heap, and +:class:`SortedPriorityQueue`, based on a sorted list. Both use a +unified API based on :class:`BasePriorityQueue` to facilitate testing +the slightly different performance characteristics on various +application use cases. + +>>> pq = PriorityQueue() +>>> pq.add('low priority task', 0) +>>> pq.add('high priority task', 2) +>>> pq.add('medium priority task 1', 1) +>>> pq.add('medium priority task 2', 1) +>>> len(pq) +4 +>>> pq.pop() +'high priority task' +>>> pq.peek() +'medium priority task 1' +>>> len(pq) +3 + +""" + + +from heapq import heappush, heappop +from bisect import insort +import itertools + +try: + from .typeutils import make_sentinel + _REMOVED = make_sentinel(var_name='_REMOVED') +except ImportError: + _REMOVED = object() + +try: + from .listutils import BList + # see BarrelList docstring for notes +except ImportError: + BList = list + + +__all__ = ['PriorityQueue', 'BasePriorityQueue', + 'HeapPriorityQueue', 'SortedPriorityQueue'] + + +# TODO: make Base a real abstract class +# TODO: add uniqueification + + +class BasePriorityQueue: + """The abstract base class for the other PriorityQueues in this + module. Override the ``_backend_type`` class attribute, as well as + the :meth:`_push_entry` and :meth:`_pop_entry` staticmethods for + custom subclass behavior. (Don't forget to use + :func:`staticmethod`). + + Args: + priority_key (callable): A function that takes *priority* as + passed in by :meth:`add` and returns a real number + representing the effective priority. + + """ + # negating priority means larger numbers = higher priority + _default_priority_key = staticmethod(lambda p: -float(p or 0)) + _backend_type = list + + def __init__(self, **kw): + self._pq = self._backend_type() + self._entry_map = {} + self._counter = itertools.count() + self._get_priority = kw.pop('priority_key', self._default_priority_key) + if kw: + raise TypeError('unexpected keyword arguments: %r' % kw.keys()) + + @staticmethod + def _push_entry(backend, entry): + pass # abstract + + @staticmethod + def _pop_entry(backend): + pass # abstract + + def add(self, task, priority=None): + """ + Add a task to the queue, or change the *task*'s priority if *task* + is already in the queue. *task* can be any hashable object, + and *priority* defaults to ``0``. Higher values representing + higher priority, but this behavior can be controlled by + setting *priority_key* in the constructor. + """ + priority = self._get_priority(priority) + if task in self._entry_map: + self.remove(task) + count = next(self._counter) + entry = [priority, count, task] + self._entry_map[task] = entry + self._push_entry(self._pq, entry) + + def remove(self, task): + """Remove a task from the priority queue. Raises :exc:`KeyError` if + the *task* is absent. + """ + entry = self._entry_map.pop(task) + entry[-1] = _REMOVED + + def _cull(self, raise_exc=True): + "Remove entries marked as removed by previous :meth:`remove` calls." + while self._pq: + priority, count, task = self._pq[0] + if task is _REMOVED: + self._pop_entry(self._pq) + continue + return + if raise_exc: + raise IndexError('empty priority queue') + + def peek(self, default=_REMOVED): + """Read the next value in the queue without removing it. Returns + *default* on an empty queue, or raises :exc:`KeyError` if + *default* is not set. + """ + try: + self._cull() + _, _, task = self._pq[0] + except IndexError: + if default is not _REMOVED: + return default + raise IndexError('peek on empty queue') + return task + + def pop(self, default=_REMOVED): + """Remove and return the next value in the queue. Returns *default* on + an empty queue, or raises :exc:`KeyError` if *default* is not + set. + """ + try: + self._cull() + _, _, task = self._pop_entry(self._pq) + del self._entry_map[task] + except IndexError: + if default is not _REMOVED: + return default + raise IndexError('pop on empty queue') + return task + + def __len__(self): + "Return the number of tasks in the queue." + return len(self._entry_map) + + +class HeapPriorityQueue(BasePriorityQueue): + """A priority queue inherited from :class:`BasePriorityQueue`, + backed by a list and based on the :func:`heapq.heappop` and + :func:`heapq.heappush` functions in the built-in :mod:`heapq` + module. + """ + @staticmethod + def _pop_entry(backend): + return heappop(backend) + + @staticmethod + def _push_entry(backend, entry): + heappush(backend, entry) + + +class SortedPriorityQueue(BasePriorityQueue): + """A priority queue inherited from :class:`BasePriorityQueue`, based + on the :func:`bisect.insort` approach for in-order insertion into + a sorted list. + """ + _backend_type = BList + + @staticmethod + def _pop_entry(backend): + return backend.pop(0) + + @staticmethod + def _push_entry(backend, entry): + insort(backend, entry) + + +PriorityQueue = SortedPriorityQueue diff --git a/miniconda3/lib/python3.13/site-packages/boltons/setutils.py b/miniconda3/lib/python3.13/site-packages/boltons/setutils.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed5ab32052ebb2750f90a2bc07eab40b2249525 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/setutils.py @@ -0,0 +1,969 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""\ + +The :class:`set` type brings the practical expressiveness of +set theory to Python. It has a very rich API overall, but lacks a +couple of fundamental features. For one, sets are not ordered. On top +of this, sets are not indexable, i.e, ``my_set[8]`` will raise an +:exc:`TypeError`. The :class:`IndexedSet` type remedies both of these +issues without compromising on the excellent complexity +characteristics of Python's built-in set implementation. +""" + + +from bisect import bisect_left +from collections.abc import MutableSet +from itertools import chain, islice +import operator + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + + +__all__ = ['IndexedSet', 'complement'] + + +_COMPACTION_FACTOR = 8 + +# TODO: inherit from set() +# TODO: .discard_many(), .remove_many() +# TODO: raise exception on non-set params? +# TODO: technically reverse operators should probably reverse the +# order of the 'other' inputs and put self last (to try and maintain +# insertion order) + + +class IndexedSet(MutableSet): + """``IndexedSet`` is a :class:`collections.MutableSet` that maintains + insertion order and uniqueness of inserted elements. It's a hybrid + type, mostly like an OrderedSet, but also :class:`list`-like, in + that it supports indexing and slicing. + + Args: + other (iterable): An optional iterable used to initialize the set. + + >>> x = IndexedSet(list(range(4)) + list(range(8))) + >>> x + IndexedSet([0, 1, 2, 3, 4, 5, 6, 7]) + >>> x - set(range(2)) + IndexedSet([2, 3, 4, 5, 6, 7]) + >>> x[-1] + 7 + >>> fcr = IndexedSet('freecreditreport.com') + >>> ''.join(fcr[:fcr.index('.')]) + 'frecditpo' + + Standard set operators and interoperation with :class:`set` are + all supported: + + >>> fcr & set('cash4gold.com') + IndexedSet(['c', 'd', 'o', '.', 'm']) + + As you can see, the ``IndexedSet`` is almost like a ``UniqueList``, + retaining only one copy of a given value, in the order it was + first added. For the curious, the reason why IndexedSet does not + support setting items based on index (i.e, ``__setitem__()``), + consider the following dilemma:: + + my_indexed_set = [A, B, C, D] + my_indexed_set[2] = A + + At this point, a set requires only one *A*, but a :class:`list` would + overwrite *C*. Overwriting *C* would change the length of the list, + meaning that ``my_indexed_set[2]`` would not be *A*, as expected with a + list, but rather *D*. So, no ``__setitem__()``. + + Otherwise, the API strives to be as complete a union of the + :class:`list` and :class:`set` APIs as possible. + """ + def __init__(self, other=None): + self.item_index_map = dict() + self.item_list = [] + self.dead_indices = [] + self._compactions = 0 + self._c_max_size = 0 + if other: + self.update(other) + + # internal functions + @property + def _dead_index_count(self): + return len(self.item_list) - len(self.item_index_map) + + def _compact(self): + if not self.dead_indices: + return + self._compactions += 1 + dead_index_count = self._dead_index_count + items, index_map = self.item_list, self.item_index_map + self._c_max_size = max(self._c_max_size, len(items)) + for i, item in enumerate(self): + items[i] = item + index_map[item] = i + del items[-dead_index_count:] + del self.dead_indices[:] + + def _cull(self): + ded = self.dead_indices + if not ded: + return + items, ii_map = self.item_list, self.item_index_map + if not ii_map: + del items[:] + del ded[:] + elif len(ded) > 384: + self._compact() + elif self._dead_index_count > (len(items) / _COMPACTION_FACTOR): + self._compact() + elif items[-1] is _MISSING: # get rid of dead right hand side + num_dead = 1 + while items[-(num_dead + 1)] is _MISSING: + num_dead += 1 + if ded and ded[-1][1] == len(items): + del ded[-1] + del items[-num_dead:] + + def _get_real_index(self, index): + if index < 0: + index += len(self) + if not self.dead_indices: + return index + real_index = index + for d_start, d_stop in self.dead_indices: + if real_index < d_start: + break + real_index += d_stop - d_start + return real_index + + def _get_apparent_index(self, index): + if index < 0: + index += len(self) + if not self.dead_indices: + return index + apparent_index = index + for d_start, d_stop in self.dead_indices: + if index < d_start: + break + apparent_index -= d_stop - d_start + return apparent_index + + def _add_dead(self, start, stop=None): + # TODO: does not handle when the new interval subsumes + # multiple existing intervals + dints = self.dead_indices + if stop is None: + stop = start + 1 + cand_int = [start, stop] + if not dints: + dints.append(cand_int) + return + int_idx = bisect_left(dints, cand_int) + dint = dints[int_idx - 1] + d_start, d_stop = dint + if start <= d_start <= stop: + dint[0] = start + elif start <= d_stop <= stop: + dint[1] = stop + else: + dints.insert(int_idx, cand_int) + return + + # common operations (shared by set and list) + def __len__(self): + return len(self.item_index_map) + + def __contains__(self, item): + return item in self.item_index_map + + def __iter__(self): + return (item for item in self.item_list if item is not _MISSING) + + def __reversed__(self): + item_list = self.item_list + return (item for item in reversed(item_list) if item is not _MISSING) + + def __repr__(self): + return f'{self.__class__.__name__}({list(self)!r})' + + def __eq__(self, other): + if isinstance(other, IndexedSet): + return len(self) == len(other) and list(self) == list(other) + try: + return set(self) == set(other) + except TypeError: + return False + + @classmethod + def from_iterable(cls, it): + "from_iterable(it) -> create a set from an iterable" + return cls(it) + + # set operations + def add(self, item): + "add(item) -> add item to the set" + if item not in self.item_index_map: + self.item_index_map[item] = len(self.item_list) + self.item_list.append(item) + + def remove(self, item): + "remove(item) -> remove item from the set, raises if not present" + try: + didx = self.item_index_map.pop(item) + except KeyError: + raise KeyError(item) + self.item_list[didx] = _MISSING + self._add_dead(didx) + self._cull() + + def discard(self, item): + "discard(item) -> discard item from the set (does not raise)" + try: + self.remove(item) + except KeyError: + pass + + def clear(self): + "clear() -> empty the set" + del self.item_list[:] + del self.dead_indices[:] + self.item_index_map.clear() + + def isdisjoint(self, other): + "isdisjoint(other) -> return True if no overlap with other" + iim = self.item_index_map + for k in other: + if k in iim: + return False + return True + + def issubset(self, other): + "issubset(other) -> return True if other contains this set" + if len(other) < len(self): + return False + for k in self.item_index_map: + if k not in other: + return False + return True + + def issuperset(self, other): + "issuperset(other) -> return True if set contains other" + if len(other) > len(self): + return False + iim = self.item_index_map + for k in other: + if k not in iim: + return False + return True + + def union(self, *others): + "union(*others) -> return a new set containing this set and others" + return self.from_iterable(chain(self, *others)) + + def iter_intersection(self, *others): + "iter_intersection(*others) -> iterate over elements also in others" + for k in self: + for other in others: + if k not in other: + break + else: + yield k + return + + def intersection(self, *others): + "intersection(*others) -> get a set with overlap of this and others" + if len(others) == 1: + other = others[0] + return self.from_iterable(k for k in self if k in other) + return self.from_iterable(self.iter_intersection(*others)) + + def iter_difference(self, *others): + "iter_difference(*others) -> iterate over elements not in others" + for k in self: + for other in others: + if k in other: + break + else: + yield k + return + + def difference(self, *others): + "difference(*others) -> get a new set with elements not in others" + if len(others) == 1: + other = others[0] + return self.from_iterable(k for k in self if k not in other) + return self.from_iterable(self.iter_difference(*others)) + + def symmetric_difference(self, *others): + "symmetric_difference(*others) -> XOR set of this and others" + ret = self.union(*others) + return ret.difference(self.intersection(*others)) + + __or__ = __ror__ = union + __and__ = __rand__ = intersection + __sub__ = difference + __xor__ = __rxor__ = symmetric_difference + + def __rsub__(self, other): + vals = [x for x in other if x not in self] + return type(other)(vals) + + # in-place set operations + def update(self, *others): + "update(*others) -> add values from one or more iterables" + if not others: + return # raise? + elif len(others) == 1: + other = others[0] + else: + other = chain(others) + for o in other: + self.add(o) + + def intersection_update(self, *others): + "intersection_update(*others) -> discard self.difference(*others)" + for val in self.difference(*others): + self.discard(val) + + def difference_update(self, *others): + "difference_update(*others) -> discard self.intersection(*others)" + if self in others: + self.clear() + for val in self.intersection(*others): + self.discard(val) + + def symmetric_difference_update(self, other): # note singular 'other' + "symmetric_difference_update(other) -> in-place XOR with other" + if self is other: + self.clear() + for val in other: + if val in self: + self.discard(val) + else: + self.add(val) + + def __ior__(self, *others): + self.update(*others) + return self + + def __iand__(self, *others): + self.intersection_update(*others) + return self + + def __isub__(self, *others): + self.difference_update(*others) + return self + + def __ixor__(self, *others): + self.symmetric_difference_update(*others) + return self + + def iter_slice(self, start, stop, step=None): + "iterate over a slice of the set" + iterable = self + if start is not None: + start = self._get_real_index(start) + if stop is not None: + stop = self._get_real_index(stop) + if step is not None and step < 0: + step = -step + iterable = reversed(self) + return islice(iterable, start, stop, step) + + # list operations + def __getitem__(self, index): + try: + start, stop, step = index.start, index.stop, index.step + except AttributeError: + index = operator.index(index) + else: + iter_slice = self.iter_slice(start, stop, step) + return self.from_iterable(iter_slice) + if index < 0: + index += len(self) + real_index = self._get_real_index(index) + try: + ret = self.item_list[real_index] + except IndexError: + raise IndexError('IndexedSet index out of range') + return ret + + def pop(self, index=None): + "pop(index) -> remove the item at a given index (-1 by default)" + item_index_map = self.item_index_map + len_self = len(item_index_map) + if index is None or index == -1 or index == len_self - 1: + ret = self.item_list.pop() + del item_index_map[ret] + else: + real_index = self._get_real_index(index) + ret = self.item_list[real_index] + self.item_list[real_index] = _MISSING + del item_index_map[ret] + self._add_dead(real_index) + self._cull() + return ret + + def count(self, val): + "count(val) -> count number of instances of value (0 or 1)" + if val in self.item_index_map: + return 1 + return 0 + + def reverse(self): + "reverse() -> reverse the contents of the set in-place" + reversed_list = list(reversed(self)) + self.item_list[:] = reversed_list + for i, item in enumerate(self.item_list): + self.item_index_map[item] = i + del self.dead_indices[:] + + def sort(self, **kwargs): + "sort() -> sort the contents of the set in-place" + sorted_list = sorted(self, **kwargs) + if sorted_list == self.item_list: + return + self.item_list[:] = sorted_list + for i, item in enumerate(self.item_list): + self.item_index_map[item] = i + del self.dead_indices[:] + + def index(self, val): + "index(val) -> get the index of a value, raises if not present" + try: + return self._get_apparent_index(self.item_index_map[val]) + except KeyError: + cn = self.__class__.__name__ + raise ValueError(f'{val!r} is not in {cn}') + + +def complement(wrapped): + """Given a :class:`set`, convert it to a **complement set**. + + Whereas a :class:`set` keeps track of what it contains, a + `complement set + `_ keeps + track of what it does *not* contain. For example, look what + happens when we intersect a normal set with a complement set:: + + >>> list(set(range(5)) & complement(set([2, 3]))) + [0, 1, 4] + + We get the everything in the left that wasn't in the right, + because intersecting with a complement is the same as subtracting + a normal set. + + Args: + wrapped (set): A set or any other iterable which should be + turned into a complement set. + + All set methods and operators are supported by complement sets, + between other :func:`complement`-wrapped sets and/or regular + :class:`set` objects. + + Because a complement set only tracks what elements are *not* in + the set, functionality based on set contents is unavailable: + :func:`len`, :func:`iter` (and for loops), and ``.pop()``. But a + complement set can always be turned back into a regular set by + complementing it again: + + >>> s = set(range(5)) + >>> complement(complement(s)) == s + True + + .. note:: + + An empty complement set corresponds to the concept of a + `universal set `_ + from mathematics. + + Complement sets by example + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + + Many uses of sets can be expressed more simply by using a + complement. Rather than trying to work out in your head the proper + way to invert an expression, you can just throw a complement on + the set. Consider this example of a name filter:: + + >>> class NamesFilter(object): + ... def __init__(self, allowed): + ... self._allowed = allowed + ... + ... def filter(self, names): + ... return [name for name in names if name in self._allowed] + >>> NamesFilter(set(['alice', 'bob'])).filter(['alice', 'bob', 'carol']) + ['alice', 'bob'] + + What if we want to just express "let all the names through"? + + We could try to enumerate all of the expected names:: + + ``NamesFilter({'alice', 'bob', 'carol'})`` + + But this is very brittle -- what if at some point over this + object is changed to filter ``['alice', 'bob', 'carol', 'dan']``? + + Even worse, what about the poor programmer who next works + on this piece of code? They cannot tell whether the purpose + of the large allowed set was "allow everything", or if 'dan' + was excluded for some subtle reason. + + A complement set lets the programmer intention be expressed + succinctly and directly:: + + NamesFilter(complement(set())) + + Not only is this code short and robust, it is easy to understand + the intention. + + """ + if type(wrapped) is _ComplementSet: + return wrapped.complemented() + if type(wrapped) is frozenset: + return _ComplementSet(excluded=wrapped) + return _ComplementSet(excluded=set(wrapped)) + + +def _norm_args_typeerror(other): + '''normalize args and raise type-error if there is a problem''' + if type(other) in (set, frozenset): + inc, exc = other, None + elif type(other) is _ComplementSet: + inc, exc = other._included, other._excluded + else: + raise TypeError('argument must be another set or complement(set)') + return inc, exc + + +def _norm_args_notimplemented(other): + '''normalize args and return NotImplemented (for overloaded operators)''' + if type(other) in (set, frozenset): + inc, exc = other, None + elif type(other) is _ComplementSet: + inc, exc = other._included, other._excluded + else: + return NotImplemented, None + return inc, exc + + +class _ComplementSet: + """ + helper class for complement() that implements the set methods + """ + __slots__ = ('_included', '_excluded') + + def __init__(self, included=None, excluded=None): + if included is None: + assert type(excluded) in (set, frozenset) + elif excluded is None: + assert type(included) in (set, frozenset) + else: + raise ValueError('one of included or excluded must be a set') + self._included, self._excluded = included, excluded + + def __repr__(self): + if self._included is None: + return f'complement({repr(self._excluded)})' + return f'complement(complement({repr(self._included)}))' + + def complemented(self): + '''return a complement of the current set''' + if type(self._included) is frozenset or type(self._excluded) is frozenset: + return _ComplementSet(included=self._excluded, excluded=self._included) + return _ComplementSet( + included=None if self._excluded is None else set(self._excluded), + excluded=None if self._included is None else set(self._included)) + + __invert__ = complemented + + def complement(self): + '''convert the current set to its complement in-place''' + self._included, self._excluded = self._excluded, self._included + + def __contains__(self, item): + if self._included is None: + return not item in self._excluded + return item in self._included + + def add(self, item): + if self._included is None: + if item in self._excluded: + self._excluded.remove(item) + else: + self._included.add(item) + + def remove(self, item): + if self._included is None: + self._excluded.add(item) + else: + self._included.remove(item) + + def pop(self): + if self._included is None: + raise NotImplementedError # self.missing.add(random.choice(gc.objects())) + return self._included.pop() + + def intersection(self, other): + try: + return self & other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __and__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(included=inc - self._excluded) + else: # - - + return _ComplementSet(excluded=self._excluded.union(other._excluded)) + else: + if inc is None: # + - + return _ComplementSet(included=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.intersection(inc)) + + __rand__ = __and__ + + def __iand__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded = inc - self._excluded # TODO: do this in place? + else: # - - + self._excluded |= exc + else: + if inc is None: # + - + self._included -= exc + self._included, self._excluded = None, self._included + else: # + + + self._included &= inc + return self + + def union(self, other): + try: + return self | other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __or__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded - inc) + else: # - - + return _ComplementSet(excluded=self._excluded.intersection(exc)) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.union(inc)) + + __ror__ = __or__ + + def __ior__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded -= inc + else: # - - + self._excluded &= exc + else: + if inc is None: # + - + self._included, self._excluded = None, exc - self._included # TODO: do this in place? + else: # + + + self._included |= inc + return self + + def update(self, items): + if type(items) in (set, frozenset): + inc, exc = items, None + elif type(items) is _ComplementSet: + inc, exc = items._included, items._excluded + else: + inc, exc = frozenset(items), None + if self._included is None: + if exc is None: # - + + self._excluded &= inc + else: # - - + self._excluded.discard(exc) + else: + if inc is None: # + - + self._included &= exc + self._included, self._excluded = None, self._excluded + else: # + + + self._included.update(inc) + + def discard(self, items): + if type(items) in (set, frozenset): + inc, exc = items, None + elif type(items) is _ComplementSet: + inc, exc = items._included, items._excluded + else: + inc, exc = frozenset(items), None + if self._included is None: + if exc is None: # - + + self._excluded.update(inc) + else: # - - + self._included, self._excluded = exc - self._excluded, None + else: + if inc is None: # + - + self._included &= exc + else: # + + + self._included.discard(inc) + + def symmetric_difference(self, other): + try: + return self ^ other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __xor__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded - inc) + else: # - - + return _ComplementSet(included=self._excluded.symmetric_difference(exc)) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc - self._included) + else: # + + + return _ComplementSet(included=self._included.symmetric_difference(inc)) + + __rxor__ = __xor__ + + def symmetric_difference_update(self, other): + inc, exc = _norm_args_typeerror(other) + if self._included is None: + if exc is None: # - + + self._excluded |= inc + else: # - - + self._excluded.symmetric_difference_update(exc) + self._included, self._excluded = self._excluded, None + else: + if inc is None: # + - + self._included |= exc + self._included, self._excluded = None, self._included + else: # + + + self._included.symmetric_difference_update(inc) + + def isdisjoint(self, other): + inc, exc = _norm_args_typeerror(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return inc.issubset(self._excluded) + else: # - - + return False + else: + if inc is None: # + - + return self._included.issubset(exc) + else: # + + + return self._included.isdisjoint(inc) + + def issubset(self, other): + '''everything missing from other is also missing from self''' + try: + return self <= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __le__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return False + else: # - - + return self._excluded.issupserset(exc) + else: + if inc is None: # + - + return self._included.isdisjoint(exc) + else: # + + + return self._included.issubset(inc) + + def __lt__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return False + else: # - - + return self._excluded > exc + else: + if inc is None: # + - + return self._included.isdisjoint(exc) + else: # + + + return self._included < inc + + def issuperset(self, other): + '''everything missing from self is also missing from super''' + try: + return self >= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __ge__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return not self._excluded.intersection(inc) + else: # - - + return self._excluded.issubset(exc) + else: + if inc is None: # + - + return False + else: # + + + return self._included.issupserset(inc) + + def __gt__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return not self._excluded.intersection(inc) + else: # - - + return self._excluded < exc + else: + if inc is None: # + - + return False + else: # + + + return self._included > inc + + def difference(self, other): + try: + return self - other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __sub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + return _ComplementSet(excluded=self._excluded | inc) + else: # - - + return _ComplementSet(included=exc - self._excluded) + else: + if inc is None: # + - + return _ComplementSet(included=self._included & exc) + else: # + + + return _ComplementSet(included=self._included.difference(inc)) + + def __rsub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + # rsub, so the expression being evaluated is "other - self" + if self._included is None: + if exc is None: # - + + return _ComplementSet(included=inc & self._excluded) + else: # - - + return _ComplementSet(included=self._excluded - exc) + else: + if inc is None: # + - + return _ComplementSet(excluded=exc | self._included) + else: # + + + return _ComplementSet(included=inc.difference(self._included)) + + def difference_update(self, other): + try: + self -= other + except NotImplementedError: + raise TypeError('argument must be another set or complement(set)') + + def __isub__(self, other): + inc, exc = _norm_args_notimplemented(other) + if inc is NotImplemented: + return NotImplemented + if self._included is None: + if exc is None: # - + + self._excluded |= inc + else: # - - + self._included, self._excluded = exc - self._excluded, None + else: + if inc is None: # + - + self._included &= exc + else: # + + + self._included.difference_update(inc) + return self + + def __eq__(self, other): + return ( + type(self) is type(other) + and self._included == other._included + and self._excluded == other._excluded) or ( + type(other) in (set, frozenset) and self._included == other) + + def __hash__(self): + return hash(self._included) ^ hash(self._excluded) + + def __len__(self): + if self._included is not None: + return len(self._included) + raise NotImplementedError('complemented sets have undefined length') + + def __iter__(self): + if self._included is not None: + return iter(self._included) + raise NotImplementedError('complemented sets have undefined contents') + + def __bool__(self): + if self._included is not None: + return bool(self._included) + return True + diff --git a/miniconda3/lib/python3.13/site-packages/boltons/socketutils.py b/miniconda3/lib/python3.13/site-packages/boltons/socketutils.py new file mode 100644 index 0000000000000000000000000000000000000000..387f84f0dde1e0d6a80a7c0518e39be4c6949855 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/socketutils.py @@ -0,0 +1,766 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""At its heart, Python can be viewed as an extension of the C +programming language. Springing from the most popular systems +programming language has made Python itself a great language for +systems programming. One key to success in this domain is Python's +very serviceable :mod:`socket` module and its :class:`socket.socket` +type. + +The ``socketutils`` module provides natural next steps to the ``socket`` +builtin: straightforward, tested building blocks for higher-level +protocols. + +The :class:`BufferedSocket` wraps an ordinary socket, providing a +layer of intuitive buffering for both sending and receiving. This +facilitates parsing messages from streams, i.e., all sockets with type +``SOCK_STREAM``. The BufferedSocket enables receiving until the next +relevant token, up to a certain size, or until the connection is +closed. For all of these, it provides consistent APIs to size +limiting, as well as timeouts that are compatible with multiple +concurrency paradigms. Use it to parse the next one-off text or binary +socket protocol you encounter. + +This module also provides the :class:`NetstringSocket`, a pure-Python +implementation of `the Netstring protocol`_, built on top of the +:class:`BufferedSocket`, serving as a ready-made, production-grade example. + +Special thanks to `Kurt Rose`_ for his original authorship and all his +contributions on this module. Also thanks to `Daniel J. Bernstein`_, the +original author of `Netstring`_. + +.. _the Netstring protocol: https://en.wikipedia.org/wiki/Netstring +.. _Kurt Rose: https://github.com/doublereedkurt +.. _Daniel J. Bernstein: https://cr.yp.to/ +.. _Netstring: https://cr.yp.to/proto/netstrings.txt + +""" + +import time +import socket + +try: + from threading import RLock +except Exception: + class RLock: + 'Dummy reentrant lock for builds without threads' + def __enter__(self): + pass + + def __exit__(self, exctype, excinst, exctb): + pass + + +try: + from .typeutils import make_sentinel + _UNSET = make_sentinel(var_name='_UNSET') +except ImportError: + _UNSET = object() + + +DEFAULT_TIMEOUT = 10 # 10 seconds +DEFAULT_MAXSIZE = 32 * 1024 # 32kb +_RECV_LARGE_MAXSIZE = 1024 ** 5 # 1PB + + +class BufferedSocket: + """Mainly provides recv_until and recv_size. recv, send, sendall, and + peek all function as similarly as possible to the built-in socket + API. + + This type has been tested against both the built-in socket type as + well as those from gevent and eventlet. It also features support + for sockets with timeouts set to 0 (aka nonblocking), provided the + caller is prepared to handle the EWOULDBLOCK exceptions. + + Args: + sock (socket): The connected socket to be wrapped. + timeout (float): The default timeout for sends and recvs, in + seconds. Set to ``None`` for no timeout, and 0 for + nonblocking. Defaults to *sock*'s own timeout if already set, + and 10 seconds otherwise. + maxsize (int): The default maximum number of bytes to be received + into the buffer before it is considered full and raises an + exception. Defaults to 32 kilobytes. + recvsize (int): The number of bytes to recv for every + lower-level :meth:`socket.recv` call. Defaults to *maxsize*. + + *timeout* and *maxsize* can both be overridden on individual socket + operations. + + All ``recv`` methods return bytestrings (:class:`bytes`) and can + raise :exc:`socket.error`. :exc:`Timeout`, + :exc:`ConnectionClosed`, and :exc:`MessageTooLong` all inherit + from :exc:`socket.error` and exist to provide better error + messages. Received bytes are always buffered, even if an exception + is raised. Use :meth:`BufferedSocket.getrecvbuffer` to retrieve + partial recvs. + + BufferedSocket does not replace the built-in socket by any + means. While the overlapping parts of the API are kept parallel to + the built-in :class:`socket.socket`, BufferedSocket does not + inherit from socket, and most socket functionality is only + available on the underlying socket. :meth:`socket.getpeername`, + :meth:`socket.getsockname`, :meth:`socket.fileno`, and others are + only available on the underlying socket that is wrapped. Use the + ``BufferedSocket.sock`` attribute to access it. See the examples + for more information on how to use BufferedSockets with built-in + sockets. + + The BufferedSocket is threadsafe, but consider the semantics of + your protocol before accessing a single socket from multiple + threads. Similarly, once the BufferedSocket is constructed, avoid + using the underlying socket directly. Only use it for operations + unrelated to messages, e.g., :meth:`socket.getpeername`. + + """ + def __init__(self, sock, timeout=_UNSET, + maxsize=DEFAULT_MAXSIZE, recvsize=_UNSET): + self.sock = sock + self.rbuf = b'' + self.sbuf = [] + self.maxsize = int(maxsize) + + if timeout is _UNSET: + if self.sock.gettimeout() is None: + self.timeout = DEFAULT_TIMEOUT + else: + self.timeout = self.sock.gettimeout() + else: + if timeout is None: + self.timeout = timeout + else: + self.timeout = float(timeout) + + if recvsize is _UNSET: + self._recvsize = self.maxsize + else: + self._recvsize = int(recvsize) + + self._send_lock = RLock() + self._recv_lock = RLock() + + def settimeout(self, timeout): + "Set the default *timeout* for future operations, in seconds." + self.timeout = timeout + + def gettimeout(self): + return self.timeout + + def setblocking(self, blocking): + self.timeout = None if blocking else 0.0 + + def setmaxsize(self, maxsize): + """Set the default maximum buffer size *maxsize* for future + operations, in bytes. Does not truncate the current buffer. + """ + self.maxsize = maxsize + + def getrecvbuffer(self): + "Returns the receive buffer bytestring (rbuf)." + with self._recv_lock: + return self.rbuf + + def getsendbuffer(self): + "Returns a copy of the send buffer list." + with self._send_lock: + return b''.join(self.sbuf) + + def recv(self, size, flags=0, timeout=_UNSET): + """Returns **up to** *size* bytes, using the internal buffer before + performing a single :meth:`socket.recv` operation. + + Args: + size (int): The maximum number of bytes to receive. + flags (int): Kept for API compatibility with sockets. Only + the default, ``0``, is valid. + timeout (float): The timeout for this operation. Can be + ``0`` for nonblocking and ``None`` for no + timeout. Defaults to the value set in the constructor + of BufferedSocket. + + If the operation does not complete in *timeout* seconds, a + :exc:`Timeout` is raised. Much like the built-in + :class:`socket.socket`, if this method returns an empty string, + then the socket is closed and recv buffer is empty. Further + calls to recv will raise :exc:`socket.error`. + + """ + with self._recv_lock: + if timeout is _UNSET: + timeout = self.timeout + if flags: + raise ValueError("non-zero flags not supported: %r" % flags) + if len(self.rbuf) >= size: + data, self.rbuf = self.rbuf[:size], self.rbuf[size:] + return data + if self.rbuf: + ret, self.rbuf = self.rbuf, b'' + return ret + self.sock.settimeout(timeout) + try: + data = self.sock.recv(self._recvsize) + except socket.timeout: + raise Timeout(timeout) # check the rbuf attr for more + if len(data) > size: + data, self.rbuf = data[:size], data[size:] + return data + + def peek(self, size, timeout=_UNSET): + """Returns *size* bytes from the socket and/or internal buffer. Bytes + are retained in BufferedSocket's internal recv buffer. To only + see bytes in the recv buffer, use :meth:`getrecvbuffer`. + + Args: + size (int): The exact number of bytes to peek at + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + + If the appropriate number of bytes cannot be fetched from the + buffer and socket before *timeout* expires, then a + :exc:`Timeout` will be raised. If the connection is closed, a + :exc:`ConnectionClosed` will be raised. + """ + with self._recv_lock: + if len(self.rbuf) >= size: + return self.rbuf[:size] + data = self.recv_size(size, timeout=timeout) + self.rbuf = data + self.rbuf + return data + + def recv_close(self, timeout=_UNSET, maxsize=_UNSET): + """Receive until the connection is closed, up to *maxsize* bytes. If + more than *maxsize* bytes are received, raises :exc:`MessageTooLong`. + """ + # recv_close works by using recv_size to request maxsize data, + # and ignoring ConnectionClose, returning and clearing the + # internal buffer instead. It raises an exception if + # ConnectionClosed isn't raised. + with self._recv_lock: + if maxsize is _UNSET: + maxsize = self.maxsize + if maxsize is None: + maxsize = _RECV_LARGE_MAXSIZE + try: + recvd = self.recv_size(maxsize + 1, timeout) + except ConnectionClosed: + ret, self.rbuf = self.rbuf, b'' + else: + # put extra received bytes (now in rbuf) after recvd + self.rbuf = recvd + self.rbuf + size_read = min(maxsize, len(self.rbuf)) + raise MessageTooLong(size_read) # check receive buffer + return ret + + def recv_until(self, delimiter, timeout=_UNSET, maxsize=_UNSET, + with_delimiter=False): + """Receive until *delimiter* is found, *maxsize* bytes have been read, + or *timeout* is exceeded. + + Args: + delimiter (bytes): One or more bytes to be searched for + in the socket stream. + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + maxsize (int): The maximum size for the internal buffer. + Defaults to the value set in the constructor. + with_delimiter (bool): Whether or not to include the + delimiter in the output. ``False`` by default, but + ``True`` is useful in cases where one is simply + forwarding the messages. + + ``recv_until`` will raise the following exceptions: + + * :exc:`Timeout` if more than *timeout* seconds expire. + * :exc:`ConnectionClosed` if the underlying socket is closed + by the sending end. + * :exc:`MessageTooLong` if the delimiter is not found in the + first *maxsize* bytes. + * :exc:`socket.error` if operating in nonblocking mode + (*timeout* equal to 0), or if some unexpected socket error + occurs, such as operating on a closed socket. + + """ + with self._recv_lock: + if maxsize is _UNSET: + maxsize = self.maxsize + if maxsize is None: + maxsize = _RECV_LARGE_MAXSIZE + if timeout is _UNSET: + timeout = self.timeout + len_delimiter = len(delimiter) + + sock = self.sock + recvd = bytearray(self.rbuf) + start = time.time() + find_offset_start = 0 # becomes a negative index below + + if not timeout: # covers None (no timeout) and 0 (nonblocking) + sock.settimeout(timeout) + try: + while 1: + offset = recvd.find(delimiter, find_offset_start, maxsize) + if offset != -1: # str.find returns -1 when no match found + if with_delimiter: # include delimiter in return + offset += len_delimiter + rbuf_offset = offset + else: + rbuf_offset = offset + len_delimiter + break + elif len(recvd) > maxsize: + raise MessageTooLong(maxsize, delimiter) # see rbuf + if timeout: + cur_timeout = timeout - (time.time() - start) + if cur_timeout <= 0.0: + raise socket.timeout() + sock.settimeout(cur_timeout) + nxt = sock.recv(self._recvsize) + if not nxt: + args = (len(recvd), delimiter) + msg = ('connection closed after reading %s bytes' + ' without finding symbol: %r' % args) + raise ConnectionClosed(msg) # check the recv buffer + recvd.extend(nxt) + find_offset_start = -len(nxt) - len_delimiter + 1 + except socket.timeout: + self.rbuf = bytes(recvd) + msg = ('read %s bytes without finding delimiter: %r' + % (len(recvd), delimiter)) + raise Timeout(timeout, msg) # check the recv buffer + except Exception: + self.rbuf = bytes(recvd) + raise + val, self.rbuf = bytes(recvd[:offset]), bytes(recvd[rbuf_offset:]) + return val + + def recv_size(self, size, timeout=_UNSET): + """Read off of the internal buffer, then off the socket, until + *size* bytes have been read. + + Args: + size (int): number of bytes to read before returning. + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + + If the appropriate number of bytes cannot be fetched from the + buffer and socket before *timeout* expires, then a + :exc:`Timeout` will be raised. If the connection is closed, a + :exc:`ConnectionClosed` will be raised. + """ + with self._recv_lock: + if timeout is _UNSET: + timeout = self.timeout + chunks = [] + total_bytes = 0 + try: + start = time.time() + self.sock.settimeout(timeout) + nxt = self.rbuf or self.sock.recv(self._recvsize) + while nxt: + total_bytes += len(nxt) + if total_bytes >= size: + break + chunks.append(nxt) + if timeout: + cur_timeout = timeout - (time.time() - start) + if cur_timeout <= 0.0: + raise socket.timeout() + self.sock.settimeout(cur_timeout) + nxt = self.sock.recv(self._recvsize) + else: + msg = ('connection closed after reading %s of %s requested' + ' bytes' % (total_bytes, size)) + raise ConnectionClosed(msg) # check recv buffer + except socket.timeout: + self.rbuf = b''.join(chunks) + msg = f'read {total_bytes} of {size} bytes' + raise Timeout(timeout, msg) # check recv buffer + except Exception: + # received data is still buffered in the case of errors + self.rbuf = b''.join(chunks) + raise + extra_bytes = total_bytes - size + if extra_bytes: + last, self.rbuf = nxt[:-extra_bytes], nxt[-extra_bytes:] + else: + last, self.rbuf = nxt, b'' + chunks.append(last) + return b''.join(chunks) + + def send(self, data, flags=0, timeout=_UNSET): + """Send the contents of the internal send buffer, as well as *data*, + to the receiving end of the connection. Returns the total + number of bytes sent. If no exception is raised, all of *data* was + sent and the internal send buffer is empty. + + Args: + data (bytes): The bytes to send. + flags (int): Kept for API compatibility with sockets. Only + the default 0 is valid. + timeout (float): The timeout for this operation. Can be 0 for + nonblocking and None for no timeout. Defaults to the value + set in the constructor of BufferedSocket. + + Will raise :exc:`Timeout` if the send operation fails to + complete before *timeout*. In the event of an exception, use + :meth:`BufferedSocket.getsendbuffer` to see which data was + unsent. + """ + with self._send_lock: + if timeout is _UNSET: + timeout = self.timeout + if flags: + raise ValueError("non-zero flags not supported") + sbuf = self.sbuf + sbuf.append(data) + if len(sbuf) > 1: + sbuf[:] = [b''.join([s for s in sbuf if s])] + self.sock.settimeout(timeout) + start, total_sent = time.time(), 0 + try: + while sbuf[0]: + sent = self.sock.send(sbuf[0]) + total_sent += sent + sbuf[0] = sbuf[0][sent:] + if timeout: + cur_timeout = timeout - (time.time() - start) + if cur_timeout <= 0.0: + raise socket.timeout() + self.sock.settimeout(cur_timeout) + except socket.timeout: + raise Timeout(timeout, '%s bytes unsent' % len(sbuf[0])) + return total_sent + + def sendall(self, data, flags=0, timeout=_UNSET): + """A passthrough to :meth:`~BufferedSocket.send`, retained for + parallelism to the :class:`socket.socket` API. + """ + return self.send(data, flags, timeout) + + def flush(self): + "Send the contents of the internal send buffer." + with self._send_lock: + self.send(b'') + return + + def buffer(self, data): + "Buffer *data* bytes for the next send operation." + with self._send_lock: + self.sbuf.append(data) + return + + # # # + # # # Passing through some socket basics + # # # + + def getsockname(self): + """Convenience function to return the wrapped socket's own address. + See :meth:`socket.getsockname` for more details. + """ + return self.sock.getsockname() + + def getpeername(self): + """Convenience function to return the remote address to which the + wrapped socket is connected. See :meth:`socket.getpeername` + for more details. + """ + return self.sock.getpeername() + + def getsockopt(self, level, optname, buflen=None): + """Convenience function passing through to the wrapped socket's + :meth:`socket.getsockopt`. + """ + args = (level, optname) + if buflen is not None: + args += (buflen,) + return self.sock.getsockopt(*args) + + def setsockopt(self, level, optname, value): + """Convenience function passing through to the wrapped socket's + :meth:`socket.setsockopt`. + """ + return self.sock.setsockopt(level, optname, value) + + @property + def type(self): + """A passthrough to the wrapped socket's type. Valid usages should + only ever see :data:`socket.SOCK_STREAM`. + """ + return self.sock.type + + @property + def family(self): + """A passthrough to the wrapped socket's family. BufferedSocket + supports all widely-used families, so this read-only attribute + can be one of :data:`socket.AF_INET` for IP, + :data:`socket.AF_INET6` for IPv6, and :data:`socket.AF_UNIX` + for UDS. + """ + return self.sock.family + + @property + def proto(self): + """A passthrough to the wrapped socket's protocol. The ``proto`` + attribute is very rarely used, so it's always 0, meaning "the + default" protocol. Pretty much all the practical information + is in :attr:`~BufferedSocket.type` and + :attr:`~BufferedSocket.family`, so you can go back to never + thinking about this. + """ + return self.sock.proto + + # # # + # # # Now for some more advanced interpretations of the builtin socket + # # # + + def fileno(self): + """Returns the file descriptor of the wrapped socket. -1 if it has + been closed on this end. + + Note that this makes the BufferedSocket selectable, i.e., + usable for operating system event loops without any external + libraries. Keep in mind that the operating system cannot know + about data in BufferedSocket's internal buffer. Exercise + discipline with calling ``recv*`` functions. + """ + return self.sock.fileno() + + def close(self): + """Closes the wrapped socket, and empties the internal buffers. The + send buffer is not flushed automatically, so if you have been + calling :meth:`~BufferedSocket.buffer`, be sure to call + :meth:`~BufferedSocket.flush` before calling this + method. After calling this method, future socket operations + will raise :exc:`socket.error`. + """ + with self._recv_lock: + with self._send_lock: + self.rbuf = b'' + self.rbuf_unconsumed = self.rbuf + self.sbuf[:] = [] + self.sock.close() + return + + def shutdown(self, how): + """Convenience method which passes through to the wrapped socket's + :meth:`~socket.shutdown`. Semantics vary by platform, so no + special internal handling is done with the buffers. This + method exists to facilitate the most common usage, wherein a + full ``shutdown`` is followed by a + :meth:`~BufferedSocket.close`. Developers requiring more + support, please open `an issue`_. + + .. _an issue: https://github.com/mahmoud/boltons/issues + """ + with self._recv_lock: + with self._send_lock: + self.sock.shutdown(how) + return + + # end BufferedSocket + + +class Error(socket.error): + """A subclass of :exc:`socket.error` from which all other + ``socketutils`` exceptions inherit. + + When using :class:`BufferedSocket` and other ``socketutils`` + types, generally you want to catch one of the specific exception + types below, or :exc:`socket.error`. + """ + pass + + +class ConnectionClosed(Error): + """Raised when receiving and the connection is unexpectedly closed + from the sending end. Raised from :class:`BufferedSocket`'s + :meth:`~BufferedSocket.peek`, :meth:`~BufferedSocket.recv_until`, + and :meth:`~BufferedSocket.recv_size`, and never from its + :meth:`~BufferedSocket.recv` or + :meth:`~BufferedSocket.recv_close`. + """ + pass + + +class MessageTooLong(Error): + """Raised from :meth:`BufferedSocket.recv_until` and + :meth:`BufferedSocket.recv_closed` when more than *maxsize* bytes are + read without encountering the delimiter or a closed connection, + respectively. + """ + def __init__(self, bytes_read=None, delimiter=None): + msg = 'message exceeded maximum size' + if bytes_read is not None: + msg += f'. {bytes_read} bytes read' + if delimiter is not None: + msg += f'. Delimiter not found: {delimiter!r}' + super().__init__(msg) + + +class Timeout(socket.timeout, Error): + """Inheriting from :exc:`socket.timeout`, Timeout is used to indicate + when a socket operation did not complete within the time + specified. Raised from any of :class:`BufferedSocket`'s ``recv`` + methods. + """ + def __init__(self, timeout, extra=""): + msg = 'socket operation timed out' + if timeout is not None: + msg += ' after %sms.' % (timeout * 1000) + if extra: + msg += ' ' + extra + super().__init__(msg) + + +class NetstringSocket: + """ + Reads and writes using the netstring protocol. + + More info: https://en.wikipedia.org/wiki/Netstring + Even more info: http://cr.yp.to/proto/netstrings.txt + """ + def __init__(self, sock, timeout=DEFAULT_TIMEOUT, maxsize=DEFAULT_MAXSIZE): + self.bsock = BufferedSocket(sock) + self.timeout = timeout + self.maxsize = maxsize + self._msgsize_maxsize = len(str(maxsize)) + 1 # len(str()) == log10 + + def fileno(self): + return self.bsock.fileno() + + def settimeout(self, timeout): + self.timeout = timeout + + def setmaxsize(self, maxsize): + self.maxsize = maxsize + self._msgsize_maxsize = self._calc_msgsize_maxsize(maxsize) + + def _calc_msgsize_maxsize(self, maxsize): + return len(str(maxsize)) + 1 # len(str()) == log10 + + def read_ns(self, timeout=_UNSET, maxsize=_UNSET): + if timeout is _UNSET: + timeout = self.timeout + + if maxsize is _UNSET: + maxsize = self.maxsize + msgsize_maxsize = self._msgsize_maxsize + else: + msgsize_maxsize = self._calc_msgsize_maxsize(maxsize) + + size_prefix = self.bsock.recv_until(b':', + timeout=timeout, + maxsize=msgsize_maxsize) + try: + size = int(size_prefix) + except ValueError: + raise NetstringInvalidSize('netstring message size must be valid' + ' integer, not %r' % size_prefix) + + if size > maxsize: + raise NetstringMessageTooLong(size, maxsize) + payload = self.bsock.recv_size(size) + if self.bsock.recv(1) != b',': + raise NetstringProtocolError("expected trailing ',' after message") + + return payload + + def write_ns(self, payload): + size = len(payload) + if size > self.maxsize: + raise NetstringMessageTooLong(size, self.maxsize) + data = str(size).encode('ascii') + b':' + payload + b',' + self.bsock.send(data) + + +class NetstringProtocolError(Error): + "Base class for all of socketutils' Netstring exception types." + pass + + +class NetstringInvalidSize(NetstringProtocolError): + """NetstringInvalidSize is raised when the ``:``-delimited size prefix + of the message does not contain a valid integer. + + Message showing valid size:: + + 5:hello, + + Here the ``5`` is the size. Anything in this prefix position that + is not parsable as a Python integer (i.e., :class:`int`) will raise + this exception. + """ + def __init__(self, msg): + super().__init__(msg) + + +class NetstringMessageTooLong(NetstringProtocolError): + """NetstringMessageTooLong is raised when the size prefix contains a + valid integer, but that integer is larger than the + :class:`NetstringSocket`'s configured *maxsize*. + + When this exception is raised, it's recommended to simply close + the connection instead of trying to recover. + """ + def __init__(self, size, maxsize): + msg = ('netstring message length exceeds configured maxsize: %s > %s' + % (size, maxsize)) + super().__init__(msg) + + +""" +attrs worth adding/passing through: + + +properties: type, proto + +For its main functionality, BufferedSocket can wrap any object that +has the following methods: + + - gettimeout() + - settimeout() + - recv(size) + - send(data) + +The following methods are passed through: + +... + +""" + +# TODO: buffered socket check socket.type == SOCK_STREAM? +# TODO: make recv_until support taking a regex +# TODO: including the delimiter in the recv_until return is not +# necessary, as ConnectionClosed differentiates empty messages +# from socket closes. diff --git a/miniconda3/lib/python3.13/site-packages/boltons/statsutils.py b/miniconda3/lib/python3.13/site-packages/boltons/statsutils.py new file mode 100644 index 0000000000000000000000000000000000000000..36a82230d80f2b6e32fcf07851da2aa2c4d7132b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/statsutils.py @@ -0,0 +1,814 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""``statsutils`` provides tools aimed primarily at descriptive +statistics for data analysis, such as :func:`mean` (average), +:func:`median`, :func:`variance`, and many others, + +The :class:`Stats` type provides all the main functionality of the +``statsutils`` module. A :class:`Stats` object wraps a given dataset, +providing all statistical measures as property attributes. These +attributes cache their results, which allows efficient computation of +multiple measures, as many measures rely on other measures. For +example, relative standard deviation (:attr:`Stats.rel_std_dev`) +relies on both the mean and standard deviation. The Stats object +caches those results so no rework is done. + +The :class:`Stats` type's attributes have module-level counterparts for +convenience when the computation reuse advantages do not apply. + +>>> stats = Stats(range(42)) +>>> stats.mean +20.5 +>>> mean(range(42)) +20.5 + +Statistics is a large field, and ``statsutils`` is focused on a few +basic techniques that are useful in software. The following is a brief +introduction to those techniques. For a more in-depth introduction, +`Statistics for Software +`_, +an article I wrote on the topic. It introduces key terminology vital +to effective usage of statistics. + +Statistical moments +------------------- + +Python programmers are probably familiar with the concept of the +*mean* or *average*, which gives a rough quantitiative middle value by +which a sample can be can be generalized. However, the mean is just +the first of four `moment`_-based measures by which a sample or +distribution can be measured. + +The four `Standardized moments`_ are: + + 1. `Mean`_ - :func:`mean` - theoretical middle value + 2. `Variance`_ - :func:`variance` - width of value dispersion + 3. `Skewness`_ - :func:`skewness` - symmetry of distribution + 4. `Kurtosis`_ - :func:`kurtosis` - "peakiness" or "long-tailed"-ness + +For more information check out `the Moment article on Wikipedia`_. + +.. _moment: https://en.wikipedia.org/wiki/Moment_(mathematics) +.. _Standardized moments: https://en.wikipedia.org/wiki/Standardized_moment +.. _Mean: https://en.wikipedia.org/wiki/Mean +.. _Variance: https://en.wikipedia.org/wiki/Variance +.. _Skewness: https://en.wikipedia.org/wiki/Skewness +.. _Kurtosis: https://en.wikipedia.org/wiki/Kurtosis +.. _the Moment article on Wikipedia: https://en.wikipedia.org/wiki/Moment_(mathematics) + +Keep in mind that while these moments can give a bit more insight into +the shape and distribution of data, they do not guarantee a complete +picture. Wildly different datasets can have the same values for all +four moments, so generalize wisely. + +Robust statistics +----------------- + +Moment-based statistics are notorious for being easily skewed by +outliers. The whole field of robust statistics aims to mitigate this +dilemma. ``statsutils`` also includes several robust statistical methods: + + * `Median`_ - The middle value of a sorted dataset + * `Trimean`_ - Another robust measure of the data's central tendency + * `Median Absolute Deviation`_ (MAD) - A robust measure of + variability, a natural counterpart to :func:`variance`. + * `Trimming`_ - Reducing a dataset to only the middle majority of + data is a simple way of making other estimators more robust. + +.. _Median: https://en.wikipedia.org/wiki/Median +.. _Trimean: https://en.wikipedia.org/wiki/Trimean +.. _Median Absolute Deviation: https://en.wikipedia.org/wiki/Median_absolute_deviation +.. _Trimming: https://en.wikipedia.org/wiki/Trimmed_estimator + + +Online and Offline Statistics +----------------------------- + +Unrelated to computer networking, `online`_ statistics involve +calculating statistics in a `streaming`_ fashion, without all the data +being available. The :class:`Stats` type is meant for the more +traditional offline statistics when all the data is available. For +pure-Python online statistics accumulators, look at the `Lithoxyl`_ +system instrumentation package. + +.. _Online: https://en.wikipedia.org/wiki/Online_algorithm +.. _streaming: https://en.wikipedia.org/wiki/Streaming_algorithm +.. _Lithoxyl: https://github.com/mahmoud/lithoxyl + +""" + + +import bisect +from math import floor, ceil +from collections import Counter + + +class _StatsProperty: + def __init__(self, name, func): + self.name = name + self.func = func + self.internal_name = '_' + name + + doc = func.__doc__ or '' + pre_doctest_doc, _, _ = doc.partition('>>>') + self.__doc__ = pre_doctest_doc + + def __get__(self, obj, objtype=None): + if obj is None: + return self + if not obj.data: + return obj.default + try: + return getattr(obj, self.internal_name) + except AttributeError: + setattr(obj, self.internal_name, self.func(obj)) + return getattr(obj, self.internal_name) + + +class Stats: + """The ``Stats`` type is used to represent a group of unordered + statistical datapoints for calculations such as mean, median, and + variance. + + Args: + + data (list): List or other iterable containing numeric values. + default (float): A value to be returned when a given + statistical measure is not defined. 0.0 by default, but + ``float('nan')`` is appropriate for stricter applications. + use_copy (bool): By default Stats objects copy the initial + data into a new list to avoid issues with + modifications. Pass ``False`` to disable this behavior. + is_sorted (bool): Presorted data can skip an extra sorting + step for a little speed boost. Defaults to False. + + """ + def __init__(self, data, default=0.0, use_copy=True, is_sorted=False): + self._use_copy = use_copy + self._is_sorted = is_sorted + if use_copy: + self.data = list(data) + else: + self.data = data + + self.default = default + cls = self.__class__ + self._prop_attr_names = [a for a in dir(self) + if isinstance(getattr(cls, a, None), + _StatsProperty)] + self._pearson_precision = 0 + + def __len__(self): + return len(self.data) + + def __iter__(self): + return iter(self.data) + + def _get_sorted_data(self): + """When using a copy of the data, it's better to have that copy be + sorted, but we do it lazily using this method, in case no + sorted measures are used. I.e., if median is never called, + sorting would be a waste. + + When not using a copy, it's presumed that all optimizations + are on the user. + """ + if not self._use_copy: + return sorted(self.data) + elif not self._is_sorted: + self.data.sort() + return self.data + + def clear_cache(self): + """``Stats`` objects automatically cache intermediary calculations + that can be reused. For instance, accessing the ``std_dev`` + attribute after the ``variance`` attribute will be + significantly faster for medium-to-large datasets. + + If you modify the object by adding additional data points, + call this function to have the cached statistics recomputed. + + """ + for attr_name in self._prop_attr_names: + attr_name = getattr(self.__class__, attr_name).internal_name + if not hasattr(self, attr_name): + continue + delattr(self, attr_name) + return + + def _calc_count(self): + """The number of items in this Stats object. Returns the same as + :func:`len` on a Stats object, but provided for pandas terminology + parallelism. + + >>> Stats(range(20)).count + 20 + """ + return len(self.data) + count = _StatsProperty('count', _calc_count) + + def _calc_mean(self): + """ + The arithmetic mean, or "average". Sum of the values divided by + the number of values. + + >>> mean(range(20)) + 9.5 + >>> mean(list(range(19)) + [949]) # 949 is an arbitrary outlier + 56.0 + """ + return sum(self.data, 0.0) / len(self.data) + mean = _StatsProperty('mean', _calc_mean) + + def _calc_max(self): + """ + The maximum value present in the data. + + >>> Stats([2, 1, 3]).max + 3 + """ + if self._is_sorted: + return self.data[-1] + return max(self.data) + max = _StatsProperty('max', _calc_max) + + def _calc_min(self): + """ + The minimum value present in the data. + + >>> Stats([2, 1, 3]).min + 1 + """ + if self._is_sorted: + return self.data[0] + return min(self.data) + min = _StatsProperty('min', _calc_min) + + def _calc_median(self): + """ + The median is either the middle value or the average of the two + middle values of a sample. Compared to the mean, it's generally + more resilient to the presence of outliers in the sample. + + >>> median([2, 1, 3]) + 2 + >>> median(range(97)) + 48 + >>> median(list(range(96)) + [1066]) # 1066 is an arbitrary outlier + 48 + """ + return self._get_quantile(self._get_sorted_data(), 0.5) + median = _StatsProperty('median', _calc_median) + + def _calc_iqr(self): + """Inter-quartile range (IQR) is the difference between the 75th + percentile and 25th percentile. IQR is a robust measure of + dispersion, like standard deviation, but safer to compare + between datasets, as it is less influenced by outliers. + + >>> iqr([1, 2, 3, 4, 5]) + 2 + >>> iqr(range(1001)) + 500 + """ + return self.get_quantile(0.75) - self.get_quantile(0.25) + iqr = _StatsProperty('iqr', _calc_iqr) + + def _calc_trimean(self): + """The trimean is a robust measure of central tendency, like the + median, that takes the weighted average of the median and the + upper and lower quartiles. + + >>> trimean([2, 1, 3]) + 2.0 + >>> trimean(range(97)) + 48.0 + >>> trimean(list(range(96)) + [1066]) # 1066 is an arbitrary outlier + 48.0 + + """ + sorted_data = self._get_sorted_data() + gq = lambda q: self._get_quantile(sorted_data, q) + return (gq(0.25) + (2 * gq(0.5)) + gq(0.75)) / 4.0 + trimean = _StatsProperty('trimean', _calc_trimean) + + def _calc_variance(self): + """\ + Variance is the average of the squares of the difference between + each value and the mean. + + >>> variance(range(97)) + 784.0 + """ + global mean # defined elsewhere in this file + return mean(self._get_pow_diffs(2)) + variance = _StatsProperty('variance', _calc_variance) + + def _calc_std_dev(self): + """\ + Standard deviation. Square root of the variance. + + >>> std_dev(range(97)) + 28.0 + """ + return self.variance ** 0.5 + std_dev = _StatsProperty('std_dev', _calc_std_dev) + + def _calc_median_abs_dev(self): + """\ + Median Absolute Deviation is a robust measure of statistical + dispersion: http://en.wikipedia.org/wiki/Median_absolute_deviation + + >>> median_abs_dev(range(97)) + 24.0 + """ + global median # defined elsewhere in this file + sorted_vals = sorted(self.data) + x = float(median(sorted_vals)) + return median([abs(x - v) for v in sorted_vals]) + median_abs_dev = _StatsProperty('median_abs_dev', _calc_median_abs_dev) + mad = median_abs_dev # convenience + + def _calc_rel_std_dev(self): + """\ + Standard deviation divided by the absolute value of the average. + + http://en.wikipedia.org/wiki/Relative_standard_deviation + + >>> print('%1.3f' % rel_std_dev(range(97))) + 0.583 + """ + abs_mean = abs(self.mean) + if abs_mean: + return self.std_dev / abs_mean + else: + return self.default + rel_std_dev = _StatsProperty('rel_std_dev', _calc_rel_std_dev) + + def _calc_skewness(self): + """\ + Indicates the asymmetry of a curve. Positive values mean the bulk + of the values are on the left side of the average and vice versa. + + http://en.wikipedia.org/wiki/Skewness + + See the module docstring for more about statistical moments. + + >>> skewness(range(97)) # symmetrical around 48.0 + 0.0 + >>> left_skewed = skewness(list(range(97)) + list(range(10))) + >>> right_skewed = skewness(list(range(97)) + list(range(87, 97))) + >>> round(left_skewed, 3), round(right_skewed, 3) + (0.114, -0.114) + """ + data, s_dev = self.data, self.std_dev + if len(data) > 1 and s_dev > 0: + return (sum(self._get_pow_diffs(3)) / + float((len(data) - 1) * (s_dev ** 3))) + else: + return self.default + skewness = _StatsProperty('skewness', _calc_skewness) + + def _calc_kurtosis(self): + """\ + Indicates how much data is in the tails of the distribution. The + result is always positive, with the normal "bell-curve" + distribution having a kurtosis of 3. + + http://en.wikipedia.org/wiki/Kurtosis + + See the module docstring for more about statistical moments. + + >>> kurtosis(range(9)) + 1.99125 + + With a kurtosis of 1.99125, [0, 1, 2, 3, 4, 5, 6, 7, 8] is more + centrally distributed than the normal curve. + """ + data, s_dev = self.data, self.std_dev + if len(data) > 1 and s_dev > 0: + return (sum(self._get_pow_diffs(4)) / + float((len(data) - 1) * (s_dev ** 4))) + else: + return 0.0 + kurtosis = _StatsProperty('kurtosis', _calc_kurtosis) + + def _calc_pearson_type(self): + precision = self._pearson_precision + skewness = self.skewness + kurtosis = self.kurtosis + beta1 = skewness ** 2.0 + beta2 = kurtosis * 1.0 + + # TODO: range checks? + + c0 = (4 * beta2) - (3 * beta1) + c1 = skewness * (beta2 + 3) + c2 = (2 * beta2) - (3 * beta1) - 6 + + if round(c1, precision) == 0: + if round(beta2, precision) == 3: + return 0 # Normal + else: + if beta2 < 3: + return 2 # Symmetric Beta + elif beta2 > 3: + return 7 + elif round(c2, precision) == 0: + return 3 # Gamma + else: + k = c1 ** 2 / (4 * c0 * c2) + if k < 0: + return 1 # Beta + raise RuntimeError('missed a spot') + pearson_type = _StatsProperty('pearson_type', _calc_pearson_type) + + @staticmethod + def _get_quantile(sorted_data, q): + data, n = sorted_data, len(sorted_data) + idx = q / 1.0 * (n - 1) + idx_f, idx_c = int(floor(idx)), int(ceil(idx)) + if idx_f == idx_c: + return data[idx_f] + return (data[idx_f] * (idx_c - idx)) + (data[idx_c] * (idx - idx_f)) + + def get_quantile(self, q): + """Get a quantile from the dataset. Quantiles are floating point + values between ``0.0`` and ``1.0``, with ``0.0`` representing + the minimum value in the dataset and ``1.0`` representing the + maximum. ``0.5`` represents the median: + + >>> Stats(range(100)).get_quantile(0.5) + 49.5 + """ + q = float(q) + if not 0.0 <= q <= 1.0: + raise ValueError('expected q between 0.0 and 1.0, not %r' % q) + elif not self.data: + return self.default + return self._get_quantile(self._get_sorted_data(), q) + + def get_zscore(self, value): + """Get the z-score for *value* in the group. If the standard deviation + is 0, 0 inf or -inf will be returned to indicate whether the value is + equal to, greater than or below the group's mean. + """ + mean = self.mean + if self.std_dev == 0: + if value == mean: + return 0 + if value > mean: + return float('inf') + if value < mean: + return float('-inf') + return (float(value) - mean) / self.std_dev + + def trim_relative(self, amount=0.15): + """A utility function used to cut a proportion of values off each end + of a list of values. This has the effect of limiting the + effect of outliers. + + Args: + amount (float): A value between 0.0 and 0.5 to trim off of + each side of the data. + + .. note: + + This operation modifies the data in-place. It does not + make or return a copy. + + """ + trim = float(amount) + if not 0.0 <= trim < 0.5: + raise ValueError('expected amount between 0.0 and 0.5, not %r' + % trim) + size = len(self.data) + size_diff = int(size * trim) + if size_diff == 0.0: + return + self.data = self._get_sorted_data()[size_diff:-size_diff] + self.clear_cache() + + def _get_pow_diffs(self, power): + """ + A utility function used for calculating statistical moments. + """ + m = self.mean + return [(v - m) ** power for v in self.data] + + def _get_bin_bounds(self, count=None, with_max=False): + if not self.data: + return [0.0] # TODO: raise? + + data = self.data + len_data, min_data, max_data = len(data), min(data), max(data) + + if len_data < 4: + if not count: + count = len_data + dx = (max_data - min_data) / float(count) + bins = [min_data + (dx * i) for i in range(count)] + elif count is None: + # freedman algorithm for fixed-width bin selection + q25, q75 = self.get_quantile(0.25), self.get_quantile(0.75) + dx = 2 * (q75 - q25) / (len_data ** (1 / 3.0)) + bin_count = max(1, int(ceil((max_data - min_data) / dx))) + bins = [min_data + (dx * i) for i in range(bin_count + 1)] + bins = [b for b in bins if b < max_data] + else: + dx = (max_data - min_data) / float(count) + bins = [min_data + (dx * i) for i in range(count)] + + if with_max: + bins.append(float(max_data)) + + return bins + + def get_histogram_counts(self, bins=None, **kw): + """Produces a list of ``(bin, count)`` pairs comprising a histogram of + the Stats object's data, using fixed-width bins. See + :meth:`Stats.format_histogram` for more details. + + Args: + bins (int): maximum number of bins, or list of + floating-point bin boundaries. Defaults to the output of + Freedman's algorithm. + bin_digits (int): Number of digits used to round down the + bin boundaries. Defaults to 1. + + The output of this method can be stored and/or modified, and + then passed to :func:`statsutils.format_histogram_counts` to + achieve the same text formatting as the + :meth:`~Stats.format_histogram` method. This can be useful for + snapshotting over time. + """ + bin_digits = int(kw.pop('bin_digits', 1)) + if kw: + raise TypeError('unexpected keyword arguments: %r' % kw.keys()) + + if not bins: + bins = self._get_bin_bounds() + else: + try: + bin_count = int(bins) + except TypeError: + try: + bins = [float(x) for x in bins] + except Exception: + raise ValueError('bins expected integer bin count or list' + ' of float bin boundaries, not %r' % bins) + if self.min < bins[0]: + bins = [self.min] + bins + else: + bins = self._get_bin_bounds(bin_count) + + # floor and ceil really should have taken ndigits, like round() + round_factor = 10.0 ** bin_digits + bins = [floor(b * round_factor) / round_factor for b in bins] + bins = sorted(set(bins)) + + idxs = [bisect.bisect(bins, d) - 1 for d in self.data] + count_map = Counter(idxs) + + bin_counts = [(b, count_map.get(i, 0)) for i, b in enumerate(bins)] + + return bin_counts + + def format_histogram(self, bins=None, **kw): + """Produces a textual histogram of the data, using fixed-width bins, + allowing for simple visualization, even in console environments. + + >>> data = list(range(20)) + list(range(5, 15)) + [10] + >>> print(Stats(data).format_histogram(width=30)) + 0.0: 5 ######### + 4.4: 8 ############### + 8.9: 11 #################### + 13.3: 5 ######### + 17.8: 2 #### + + In this histogram, five values are between 0.0 and 4.4, eight + are between 4.4 and 8.9, and two values lie between 17.8 and + the max. + + You can specify the number of bins, or provide a list of + bin boundaries themselves. If no bins are provided, as in the + example above, `Freedman's algorithm`_ for bin selection is + used. + + Args: + bins (int): Maximum number of bins for the + histogram. Also accepts a list of floating-point + bin boundaries. If the minimum boundary is still + greater than the minimum value in the data, that + boundary will be implicitly added. Defaults to the bin + boundaries returned by `Freedman's algorithm`_. + bin_digits (int): Number of digits to round each bin + to. Note that bins are always rounded down to avoid + clipping any data. Defaults to 1. + width (int): integer number of columns in the longest line + in the histogram. Defaults to console width on Python + 3.3+, or 80 if that is not available. + format_bin (callable): Called on each bin to create a + label for the final output. Use this function to add + units, such as "ms" for milliseconds. + + Should you want something more programmatically reusable, see + the :meth:`~Stats.get_histogram_counts` method, the output of + is used by format_histogram. The :meth:`~Stats.describe` + method is another useful summarization method, albeit less + visual. + + .. _Freedman's algorithm: https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule + """ + width = kw.pop('width', None) + format_bin = kw.pop('format_bin', None) + bin_counts = self.get_histogram_counts(bins=bins, **kw) + return format_histogram_counts(bin_counts, + width=width, + format_bin=format_bin) + + def describe(self, quantiles=None, format=None): + """Provides standard summary statistics for the data in the Stats + object, in one of several convenient formats. + + Args: + quantiles (list): A list of numeric values to use as + quantiles in the resulting summary. All values must be + 0.0-1.0, with 0.5 representing the median. Defaults to + ``[0.25, 0.5, 0.75]``, representing the standard + quartiles. + format (str): Controls the return type of the function, + with one of three valid values: ``"dict"`` gives back + a :class:`dict` with the appropriate keys and + values. ``"list"`` is a list of key-value pairs in an + order suitable to pass to an OrderedDict or HTML + table. ``"text"`` converts the values to text suitable + for printing, as seen below. + + Here is the information returned by a default ``describe``, as + presented in the ``"text"`` format: + + >>> stats = Stats(range(1, 8)) + >>> print(stats.describe(format='text')) + count: 7 + mean: 4.0 + std_dev: 2.0 + mad: 2.0 + min: 1 + 0.25: 2.5 + 0.5: 4 + 0.75: 5.5 + max: 7 + + For more advanced descriptive statistics, check out my blog + post on the topic `Statistics for Software + `_. + + """ + if format is None: + format = 'dict' + elif format not in ('dict', 'list', 'text'): + raise ValueError('invalid format for describe,' + ' expected one of "dict"/"list"/"text", not %r' + % format) + quantiles = quantiles or [0.25, 0.5, 0.75] + q_items = [] + for q in quantiles: + q_val = self.get_quantile(q) + q_items.append((str(q), q_val)) + + items = [('count', self.count), + ('mean', self.mean), + ('std_dev', self.std_dev), + ('mad', self.mad), + ('min', self.min)] + + items.extend(q_items) + items.append(('max', self.max)) + if format == 'dict': + ret = dict(items) + elif format == 'list': + ret = items + elif format == 'text': + ret = '\n'.join(['{}{}'.format((label + ':').ljust(10), val) + for label, val in items]) + return ret + + +def describe(data, quantiles=None, format=None): + """A convenience function to get standard summary statistics useful + for describing most data. See :meth:`Stats.describe` for more + details. + + >>> print(describe(range(7), format='text')) + count: 7 + mean: 3.0 + std_dev: 2.0 + mad: 2.0 + min: 0 + 0.25: 1.5 + 0.5: 3 + 0.75: 4.5 + max: 6 + + See :meth:`Stats.format_histogram` for another very useful + summarization that uses textual visualization. + """ + return Stats(data).describe(quantiles=quantiles, format=format) + + +def _get_conv_func(attr_name): + def stats_helper(data, default=0.0): + return getattr(Stats(data, default=default, use_copy=False), + attr_name) + return stats_helper + + +for attr_name, attr in list(Stats.__dict__.items()): + if isinstance(attr, _StatsProperty): + if attr_name in ('max', 'min', 'count'): # don't shadow builtins + continue + if attr_name in ('mad',): # convenience aliases + continue + func = _get_conv_func(attr_name) + func.__doc__ = attr.func.__doc__ + globals()[attr_name] = func + delattr(Stats, '_calc_' + attr_name) +# cleanup +del attr +del attr_name +del func + + +def format_histogram_counts(bin_counts, width=None, format_bin=None): + """The formatting logic behind :meth:`Stats.format_histogram`, which + takes the output of :meth:`Stats.get_histogram_counts`, and passes + them to this function. + + Args: + bin_counts (list): A list of bin values to counts. + width (int): Number of character columns in the text output, + defaults to 80 or console width in Python 3.3+. + format_bin (callable): Used to convert bin values into string + labels. + """ + lines = [] + if not format_bin: + format_bin = lambda v: v + if not width: + try: + import shutil # python 3 convenience + width = shutil.get_terminal_size()[0] + except Exception: + width = 80 + + bins = [b for b, _ in bin_counts] + count_max = max([count for _, count in bin_counts]) + count_cols = len(str(count_max)) + + labels = ['%s' % format_bin(b) for b in bins] + label_cols = max([len(l) for l in labels]) + tmp_line = '{}: {} #'.format('x' * label_cols, count_max) + + bar_cols = max(width - len(tmp_line), 3) + line_k = float(bar_cols) / count_max + tmpl = "{label:>{label_cols}}: {count:>{count_cols}} {bar}" + for label, (bin_val, count) in zip(labels, bin_counts): + bar_len = int(round(count * line_k)) + bar = ('#' * bar_len) or '|' + line = tmpl.format(label=label, + label_cols=label_cols, + count=count, + count_cols=count_cols, + bar=bar) + lines.append(line) + + return '\n'.join(lines) diff --git a/miniconda3/lib/python3.13/site-packages/boltons/strutils.py b/miniconda3/lib/python3.13/site-packages/boltons/strutils.py new file mode 100644 index 0000000000000000000000000000000000000000..1d43f2b0a1441a487a42e1885545a9fe531d5764 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/strutils.py @@ -0,0 +1,1289 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""So much practical programming involves string manipulation, which +Python readily accommodates. Still, there are dozens of basic and +common capabilities missing from the standard library, several of them +provided by ``strutils``. +""" + + +import builtins +import re +import sys +import uuid +import zlib +import string +import unicodedata +import collections +from collections.abc import Mapping +from gzip import GzipFile +from html.parser import HTMLParser +from html import entities as htmlentitydefs +from io import BytesIO as StringIO + + +__all__ = ['camel2under', 'under2camel', 'slugify', 'split_punct_ws', + 'unit_len', 'ordinalize', 'cardinalize', 'pluralize', 'singularize', + 'asciify', 'is_ascii', 'is_uuid', 'html2text', 'strip_ansi', + 'bytes2human', 'find_hashtags', 'a10n', 'gzip_bytes', 'gunzip_bytes', + 'iter_splitlines', 'indent', 'escape_shell_args', + 'args2cmd', 'args2sh', 'parse_int_list', 'format_int_list', + 'complement_int_list', 'int_ranges_from_int_list', 'MultiReplace', + 'multi_replace', 'unwrap_text', 'removeprefix'] + + +_punct_ws_str = string.punctuation + string.whitespace +_punct_re = re.compile('[' + _punct_ws_str + ']+') +_camel2under_re = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))') + + +def camel2under(camel_string): + """Converts a camelcased string to underscores. Useful for turning a + class name into a function name. + + >>> camel2under('BasicParseTest') + 'basic_parse_test' + """ + return _camel2under_re.sub(r'_\1', camel_string).lower() + + +def under2camel(under_string): + """Converts an underscored string to camelcased. Useful for turning a + function name into a class name. + + >>> under2camel('complex_tokenizer') + 'ComplexTokenizer' + """ + return ''.join(w.capitalize() or '_' for w in under_string.split('_')) + + +def slugify(text, delim='_', lower=True, ascii=False): + """ + A basic function that turns text full of scary characters + (i.e., punctuation and whitespace), into a relatively safe + lowercased string separated only by the delimiter specified + by *delim*, which defaults to ``_``. + + The *ascii* convenience flag will :func:`asciify` the slug if + you require ascii-only slugs. + + >>> slugify('First post! Hi!!!!~1 ') + 'first_post_hi_1' + + >>> slugify("Kurt Gödel's pretty cool.", ascii=True) == \ + b'kurt_goedel_s_pretty_cool' + True + + """ + ret = delim.join(split_punct_ws(text)) or delim if text else '' + if ascii: + ret = asciify(ret) + if lower: + ret = ret.lower() + return ret + + +def split_punct_ws(text): + """While :meth:`str.split` will split on whitespace, + :func:`split_punct_ws` will split on punctuation and + whitespace. This used internally by :func:`slugify`, above. + + >>> split_punct_ws('First post! Hi!!!!~1 ') + ['First', 'post', 'Hi', '1'] + """ + return [w for w in _punct_re.split(text) if w] + + +def unit_len(sized_iterable, unit_noun='item'): # TODO: len_units()/unitize()? + """Returns a plain-English description of an iterable's + :func:`len()`, conditionally pluralized with :func:`cardinalize`, + detailed below. + + >>> print(unit_len(range(10), 'number')) + 10 numbers + >>> print(unit_len('aeiou', 'vowel')) + 5 vowels + >>> print(unit_len([], 'worry')) + No worries + """ + count = len(sized_iterable) + units = cardinalize(unit_noun, count) + if count: + return f'{count} {units}' + return f'No {units}' + + +_ORDINAL_MAP = {'1': 'st', + '2': 'nd', + '3': 'rd'} # 'th' is the default + + +def ordinalize(number, ext_only=False): + """Turns *number* into its cardinal form, i.e., 1st, 2nd, + 3rd, 4th, etc. If the last character isn't a digit, it returns the + string value unchanged. + + Args: + number (int or str): Number to be cardinalized. + ext_only (bool): Whether to return only the suffix. Default ``False``. + + >>> print(ordinalize(1)) + 1st + >>> print(ordinalize(3694839230)) + 3694839230th + >>> print(ordinalize('hi')) + hi + >>> print(ordinalize(1515)) + 1515th + """ + numstr, ext = str(number), '' + if numstr and numstr[-1] in string.digits: + try: + # first check for teens + if numstr[-2] == '1': + ext = 'th' + else: + # all other cases + ext = _ORDINAL_MAP.get(numstr[-1], 'th') + except IndexError: + # single digit numbers (will reach here based on [-2] above) + ext = _ORDINAL_MAP.get(numstr[-1], 'th') + if ext_only: + return ext + else: + return numstr + ext + + +def cardinalize(unit_noun, count): + """Conditionally pluralizes a singular word *unit_noun* if + *count* is not one, preserving case when possible. + + >>> vowels = 'aeiou' + >>> print(len(vowels), cardinalize('vowel', len(vowels))) + 5 vowels + >>> print(3, cardinalize('Wish', 3)) + 3 Wishes + """ + if count == 1: + return unit_noun + return pluralize(unit_noun) + + +def singularize(word): + """Semi-intelligently converts an English plural *word* to its + singular form, preserving case pattern. + + >>> singularize('chances') + 'chance' + >>> singularize('Activities') + 'Activity' + >>> singularize('Glasses') + 'Glass' + >>> singularize('FEET') + 'FOOT' + + """ + orig_word, word = word, word.strip().lower() + if not word or word in _IRR_S2P: + return orig_word + + irr_singular = _IRR_P2S.get(word) + if irr_singular: + singular = irr_singular + elif not word.endswith('s'): + return orig_word + elif len(word) == 2: + singular = word[:-1] # or just return word? + elif word.endswith('ies') and word[-4:-3] not in 'aeiou': + singular = word[:-3] + 'y' + elif word.endswith('es') and word[-3] == 's': + singular = word[:-2] + else: + singular = word[:-1] + return _match_case(orig_word, singular) + + +def pluralize(word): + """Semi-intelligently converts an English *word* from singular form to + plural, preserving case pattern. + + >>> pluralize('friend') + 'friends' + >>> pluralize('enemy') + 'enemies' + >>> pluralize('Sheep') + 'Sheep' + """ + orig_word, word = word, word.strip().lower() + if not word or word in _IRR_P2S: + return orig_word + irr_plural = _IRR_S2P.get(word) + if irr_plural: + plural = irr_plural + elif word.endswith('y') and word[-2:-1] not in 'aeiou': + plural = word[:-1] + 'ies' + elif word[-1] == 's' or word.endswith('ch') or word.endswith('sh'): + plural = word if word.endswith('es') else word + 'es' + else: + plural = word + 's' + return _match_case(orig_word, plural) + + +def _match_case(master, disciple): + if not master.strip(): + return disciple + if master.lower() == master: + return disciple.lower() + elif master.upper() == master: + return disciple.upper() + elif master.title() == master: + return disciple.title() + return disciple + + +# Singular to plural map of irregular pluralizations +_IRR_S2P = {'addendum': 'addenda', 'alga': 'algae', 'alumna': 'alumnae', + 'alumnus': 'alumni', 'analysis': 'analyses', 'antenna': 'antennae', + 'appendix': 'appendices', 'axis': 'axes', 'bacillus': 'bacilli', + 'bacterium': 'bacteria', 'basis': 'bases', 'beau': 'beaux', + 'bison': 'bison', 'bureau': 'bureaus', 'cactus': 'cacti', + 'calf': 'calves', 'child': 'children', 'corps': 'corps', + 'corpus': 'corpora', 'crisis': 'crises', 'criterion': 'criteria', + 'curriculum': 'curricula', 'datum': 'data', 'deer': 'deer', + 'diagnosis': 'diagnoses', 'die': 'dice', 'dwarf': 'dwarves', + 'echo': 'echoes', 'elf': 'elves', 'ellipsis': 'ellipses', + 'embargo': 'embargoes', 'emphasis': 'emphases', 'erratum': 'errata', + 'fireman': 'firemen', 'fish': 'fish', 'focus': 'foci', + 'foot': 'feet', 'formula': 'formulae', 'formula': 'formulas', + 'fungus': 'fungi', 'genus': 'genera', 'goose': 'geese', + 'half': 'halves', 'hero': 'heroes', 'hippopotamus': 'hippopotami', + 'hoof': 'hooves', 'hypothesis': 'hypotheses', 'index': 'indices', + 'knife': 'knives', 'leaf': 'leaves', 'life': 'lives', + 'loaf': 'loaves', 'louse': 'lice', 'man': 'men', + 'matrix': 'matrices', 'means': 'means', 'medium': 'media', + 'memorandum': 'memoranda', 'millennium': 'milennia', 'moose': 'moose', + 'mosquito': 'mosquitoes', 'mouse': 'mice', 'nebula': 'nebulae', + 'neurosis': 'neuroses', 'nucleus': 'nuclei', 'oasis': 'oases', + 'octopus': 'octopi', 'offspring': 'offspring', 'ovum': 'ova', + 'ox': 'oxen', 'paralysis': 'paralyses', 'parenthesis': 'parentheses', + 'person': 'people', 'phenomenon': 'phenomena', 'potato': 'potatoes', + 'radius': 'radii', 'scarf': 'scarves', 'scissors': 'scissors', + 'self': 'selves', 'sense': 'senses', 'series': 'series', 'sheep': + 'sheep', 'shelf': 'shelves', 'species': 'species', 'stimulus': + 'stimuli', 'stratum': 'strata', 'syllabus': 'syllabi', 'symposium': + 'symposia', 'synopsis': 'synopses', 'synthesis': 'syntheses', + 'tableau': 'tableaux', 'that': 'those', 'thesis': 'theses', + 'thief': 'thieves', 'this': 'these', 'tomato': 'tomatoes', 'tooth': + 'teeth', 'torpedo': 'torpedoes', 'vertebra': 'vertebrae', 'veto': + 'vetoes', 'vita': 'vitae', 'watch': 'watches', 'wife': 'wives', + 'wolf': 'wolves', 'woman': 'women'} + + +# Reverse index of the above +_IRR_P2S = {v: k for k, v in _IRR_S2P.items()} + +HASHTAG_RE = re.compile(r"(?:^|\s)[##]{1}(\w+)", re.UNICODE) + + +def find_hashtags(string): + """Finds and returns all hashtags in a string, with the hashmark + removed. Supports full-width hashmarks for Asian languages and + does not false-positive on URL anchors. + + >>> find_hashtags('#atag http://asite/#ananchor') + ['atag'] + + ``find_hashtags`` also works with unicode hashtags. + """ + + # the following works, doctest just struggles with it + # >>> find_hashtags(u"can't get enough of that dignity chicken #肯德基 woo") + # [u'\u80af\u5fb7\u57fa'] + return HASHTAG_RE.findall(string) + + +def a10n(string): + """That thing where "internationalization" becomes "i18n", what's it + called? Abbreviation? Oh wait, no: ``a10n``. (It's actually a form + of `numeronym`_.) + + >>> a10n('abbreviation') + 'a10n' + >>> a10n('internationalization') + 'i18n' + >>> a10n('') + '' + + .. _numeronym: http://en.wikipedia.org/wiki/Numeronym + """ + if len(string) < 3: + return string + return f'{string[0]}{len(string[1:-1])}{string[-1]}' + + +# Based on https://en.wikipedia.org/wiki/ANSI_escape_code#Escape_sequences +ANSI_SEQUENCES = re.compile(r''' + \x1B # Sequence starts with ESC, i.e. hex 0x1B + (?: + [@-Z\\-_] # Second byte: + # all 0x40–0x5F range but CSI char, i.e ASCII @A–Z\]^_ + | # Or + \[ # CSI sequences, starting with [ + [0-?]* # Parameter bytes: + # range 0x30–0x3F, ASCII 0–9:;<=>? + [ -/]* # Intermediate bytes: + # range 0x20–0x2F, ASCII space and !"#$%&'()*+,-./ + [@-~] # Final byte + # range 0x40–0x7E, ASCII @A–Z[\]^_`a–z{|}~ + ) +''', re.VERBOSE) + + +def strip_ansi(text): + """Strips ANSI escape codes from *text*. Useful for the occasional + time when a log or redirected output accidentally captures console + color codes and the like. + + >>> strip_ansi('\x1b[0m\x1b[1;36mart\x1b[46;34m') + 'art' + + Supports str, bytes and bytearray content as input. Returns the + same type as the input. + + There's a lot of ANSI art available for testing on `sixteencolors.net`_. + This function does not interpret or render ANSI art, but you can do so with + `ansi2img`_ or `escapes.js`_. + + .. _sixteencolors.net: http://sixteencolors.net + .. _ansi2img: http://www.bedroomlan.org/projects/ansi2img + .. _escapes.js: https://github.com/atdt/escapes.js + """ + # TODO: move to cliutils.py + + # Transform any ASCII-like content to unicode to allow regex to match, and + # save input type for later. + target_type = None + # Unicode type aliased to str is code-smell for Boltons in Python 3 env. + if isinstance(text, (bytes, bytearray)): + target_type = type(text) + text = text.decode('utf-8') + + cleaned = ANSI_SEQUENCES.sub('', text) + + # Transform back the result to the same bytearray type provided by the user. + if target_type and target_type != type(cleaned): + cleaned = target_type(cleaned, 'utf-8') + + return cleaned + + +def asciify(text, ignore=False): + """Converts a unicode or bytestring, *text*, into a bytestring with + just ascii characters. Performs basic deaccenting for all you + Europhiles out there. + + Also, a gentle reminder that this is a **utility**, primarily meant + for slugification. Whenever possible, make your application work + **with** unicode, not against it. + + Args: + text (str): The string to be asciified. + ignore (bool): Configures final encoding to ignore remaining + unasciified string instead of replacing it. + + >>> asciify('Beyoncé') == b'Beyonce' + True + """ + try: + try: + return text.encode('ascii') + except UnicodeDecodeError: + # this usually means you passed in a non-unicode string + text = text.decode('utf-8') + return text.encode('ascii') + except UnicodeEncodeError: + mode = 'replace' + if ignore: + mode = 'ignore' + transd = unicodedata.normalize('NFKD', text.translate(DEACCENT_MAP)) + ret = transd.encode('ascii', mode) + return ret + + +def is_ascii(text): + """Check if a string or bytestring, *text*, is composed of ascii + characters only. Raises :exc:`ValueError` if argument is not text. + + Args: + text (str): The string to be checked. + + >>> is_ascii('Beyoncé') + False + >>> is_ascii('Beyonce') + True + """ + if isinstance(text, str): + try: + text.encode('ascii') + except UnicodeEncodeError: + return False + elif isinstance(text, bytes): + try: + text.decode('ascii') + except UnicodeDecodeError: + return False + else: + raise ValueError('expected text or bytes, not %r' % type(text)) + return True + + +class DeaccenterDict(dict): + "A small caching dictionary for deaccenting." + def __missing__(self, key): + ch = self.get(key) + if ch is not None: + return ch + try: + de = unicodedata.decomposition(chr(key)) + p1, _, p2 = de.rpartition(' ') + if int(p2, 16) == 0x308: + ch = self.get(key) + else: + ch = int(p1, 16) + except (IndexError, ValueError): + ch = self.get(key, key) + self[key] = ch + return ch + + +# http://chmullig.com/2009/12/python-unicode-ascii-ifier/ +# For something more complete, investigate the unidecode +# or isounidecode packages, which are capable of performing +# crude transliteration. +_BASE_DEACCENT_MAP = { + 0xc6: "AE", # Æ LATIN CAPITAL LETTER AE + 0xd0: "D", # Ð LATIN CAPITAL LETTER ETH + 0xd8: "OE", # Ø LATIN CAPITAL LETTER O WITH STROKE + 0xde: "Th", # Þ LATIN CAPITAL LETTER THORN + 0xc4: 'Ae', # Ä LATIN CAPITAL LETTER A WITH DIAERESIS + 0xd6: 'Oe', # Ö LATIN CAPITAL LETTER O WITH DIAERESIS + 0xdc: 'Ue', # Ü LATIN CAPITAL LETTER U WITH DIAERESIS + 0xc0: "A", # À LATIN CAPITAL LETTER A WITH GRAVE + 0xc1: "A", # Á LATIN CAPITAL LETTER A WITH ACUTE + 0xc3: "A", # Ã LATIN CAPITAL LETTER A WITH TILDE + 0xc7: "C", # Ç LATIN CAPITAL LETTER C WITH CEDILLA + 0xc8: "E", # È LATIN CAPITAL LETTER E WITH GRAVE + 0xc9: "E", # É LATIN CAPITAL LETTER E WITH ACUTE + 0xca: "E", # Ê LATIN CAPITAL LETTER E WITH CIRCUMFLEX + 0xcc: "I", # Ì LATIN CAPITAL LETTER I WITH GRAVE + 0xcd: "I", # Í LATIN CAPITAL LETTER I WITH ACUTE + 0xd2: "O", # Ò LATIN CAPITAL LETTER O WITH GRAVE + 0xd3: "O", # Ó LATIN CAPITAL LETTER O WITH ACUTE + 0xd5: "O", # Õ LATIN CAPITAL LETTER O WITH TILDE + 0xd9: "U", # Ù LATIN CAPITAL LETTER U WITH GRAVE + 0xda: "U", # Ú LATIN CAPITAL LETTER U WITH ACUTE + 0xdf: "ss", # ß LATIN SMALL LETTER SHARP S + 0xe6: "ae", # æ LATIN SMALL LETTER AE + 0xf0: "d", # ð LATIN SMALL LETTER ETH + 0xf8: "oe", # ø LATIN SMALL LETTER O WITH STROKE + 0xfe: "th", # þ LATIN SMALL LETTER THORN, + 0xe4: 'ae', # ä LATIN SMALL LETTER A WITH DIAERESIS + 0xf6: 'oe', # ö LATIN SMALL LETTER O WITH DIAERESIS + 0xfc: 'ue', # ü LATIN SMALL LETTER U WITH DIAERESIS + 0xe0: "a", # à LATIN SMALL LETTER A WITH GRAVE + 0xe1: "a", # á LATIN SMALL LETTER A WITH ACUTE + 0xe3: "a", # ã LATIN SMALL LETTER A WITH TILDE + 0xe7: "c", # ç LATIN SMALL LETTER C WITH CEDILLA + 0xe8: "e", # è LATIN SMALL LETTER E WITH GRAVE + 0xe9: "e", # é LATIN SMALL LETTER E WITH ACUTE + 0xea: "e", # ê LATIN SMALL LETTER E WITH CIRCUMFLEX + 0xec: "i", # ì LATIN SMALL LETTER I WITH GRAVE + 0xed: "i", # í LATIN SMALL LETTER I WITH ACUTE + 0xf2: "o", # ò LATIN SMALL LETTER O WITH GRAVE + 0xf3: "o", # ó LATIN SMALL LETTER O WITH ACUTE + 0xf5: "o", # õ LATIN SMALL LETTER O WITH TILDE + 0xf9: "u", # ù LATIN SMALL LETTER U WITH GRAVE + 0xfa: "u", # ú LATIN SMALL LETTER U WITH ACUTE + 0x2018: "'", # ‘ LEFT SINGLE QUOTATION MARK + 0x2019: "'", # ’ RIGHT SINGLE QUOTATION MARK + 0x201c: '"', # “ LEFT DOUBLE QUOTATION MARK + 0x201d: '"', # ” RIGHT DOUBLE QUOTATION MARK + } + + +DEACCENT_MAP = DeaccenterDict(_BASE_DEACCENT_MAP) + + +_SIZE_SYMBOLS = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') +_SIZE_BOUNDS = [(1024 ** i, sym) for i, sym in enumerate(_SIZE_SYMBOLS)] +_SIZE_RANGES = list(zip(_SIZE_BOUNDS, _SIZE_BOUNDS[1:])) + + +def bytes2human(nbytes, ndigits=0): + """Turns an integer value of *nbytes* into a human readable format. Set + *ndigits* to control how many digits after the decimal point + should be shown (default ``0``). + + >>> bytes2human(128991) + '126K' + >>> bytes2human(100001221) + '95M' + >>> bytes2human(0, 2) + '0.00B' + """ + abs_bytes = abs(nbytes) + for (size, symbol), (next_size, next_symbol) in _SIZE_RANGES: + if abs_bytes <= next_size: + break + hnbytes = float(nbytes) / size + return '{hnbytes:.{ndigits}f}{symbol}'.format(hnbytes=hnbytes, + ndigits=ndigits, + symbol=symbol) + + +class HTMLTextExtractor(HTMLParser): + def __init__(self): + self.reset() + self.strict = False + self.convert_charrefs = True + self.result = [] + + def handle_data(self, d): + self.result.append(d) + + def handle_charref(self, number): + if number[0] == 'x' or number[0] == 'X': + codepoint = int(number[1:], 16) + else: + codepoint = int(number) + self.result.append(chr(codepoint)) + + def handle_entityref(self, name): + try: + codepoint = htmlentitydefs.name2codepoint[name] + except KeyError: + self.result.append('&' + name + ';') + else: + self.result.append(chr(codepoint)) + + def get_text(self): + return ''.join(self.result) + + +def html2text(html): + """Strips tags from HTML text, returning markup-free text. Also, does + a best effort replacement of entities like " " + + >>> r = html2text(u'Test &(\u0394ημώ)') + >>> r == u'Test &(\u0394\u03b7\u03bc\u03ce)' + True + """ + # based on answers to http://stackoverflow.com/questions/753052/ + s = HTMLTextExtractor() + s.feed(html) + return s.get_text() + + +_EMPTY_GZIP_BYTES = b'\x1f\x8b\x08\x089\xf3\xb9U\x00\x03empty\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00' +_NON_EMPTY_GZIP_BYTES = b'\x1f\x8b\x08\x08\xbc\xf7\xb9U\x00\x03not_empty\x00K\xaa,I-N\xcc\xc8\xafT\xe4\x02\x00\xf3nb\xbf\x0b\x00\x00\x00' + + +def gunzip_bytes(bytestring): + """The :mod:`gzip` module is great if you have a file or file-like + object, but what if you just have bytes. StringIO is one + possibility, but it's often faster, easier, and simpler to just + use this one-liner. Use this tried-and-true utility function to + decompress gzip from bytes. + + >>> gunzip_bytes(_EMPTY_GZIP_BYTES) == b'' + True + >>> gunzip_bytes(_NON_EMPTY_GZIP_BYTES).rstrip() == b'bytesahoy!' + True + """ + return zlib.decompress(bytestring, 16 + zlib.MAX_WBITS) + + +def gzip_bytes(bytestring, level=6): + """Turn some bytes into some compressed bytes. + + >>> len(gzip_bytes(b'a' * 10000)) + 46 + + Args: + bytestring (bytes): Bytes to be compressed + level (int): An integer, 1-9, controlling the + speed/compression. 1 is fastest, least compressed, 9 is + slowest, but most compressed. + + Note that all levels of gzip are pretty fast these days, though + it's not really a competitor in compression, at any level. + """ + out = StringIO() + f = GzipFile(fileobj=out, mode='wb', compresslevel=level) + f.write(bytestring) + f.close() + return out.getvalue() + + + +_line_ending_re = re.compile(r'(\r\n|\n|\x0b|\f|\r|\x85|\x2028|\x2029)', + re.UNICODE) + + +def iter_splitlines(text): + r"""Like :meth:`str.splitlines`, but returns an iterator of lines + instead of a list. Also similar to :meth:`file.next`, as that also + lazily reads and yields lines from a file. + + This function works with a variety of line endings, but as always, + be careful when mixing line endings within a file. + + >>> list(iter_splitlines('\nhi\nbye\n')) + ['', 'hi', 'bye', ''] + >>> list(iter_splitlines('\r\nhi\rbye\r\n')) + ['', 'hi', 'bye', ''] + >>> list(iter_splitlines('')) + [] + """ + prev_end, len_text = 0, len(text) + # print('last: %r' % last_idx) + # start, end = None, None + for match in _line_ending_re.finditer(text): + start, end = match.start(1), match.end(1) + # print(start, end) + if prev_end <= start: + yield text[prev_end:start] + if end == len_text: + yield '' + prev_end = end + tail = text[prev_end:] + if tail: + yield tail + return + + +def indent(text, margin, newline='\n', key=bool): + """The missing counterpart to the built-in :func:`textwrap.dedent`. + + Args: + text (str): The text to indent. + margin (str): The string to prepend to each line. + newline (str): The newline used to rejoin the lines (default: ``\\n``) + key (callable): Called on each line to determine whether to + indent it. Default: :class:`bool`, to ensure that empty lines do + not get whitespace added. + """ + indented_lines = [(margin + line if key(line) else line) + for line in iter_splitlines(text)] + return newline.join(indented_lines) + + +def is_uuid(obj, version=4): + """Check the argument is either a valid UUID object or string. + + Args: + obj (object): The test target. Strings and UUID objects supported. + version (int): The target UUID version, set to 0 to skip version check. + + >>> is_uuid('e682ccca-5a4c-4ef2-9711-73f9ad1e15ea') + True + >>> is_uuid('0221f0d9-d4b9-11e5-a478-10ddb1c2feb9') + False + >>> is_uuid('0221f0d9-d4b9-11e5-a478-10ddb1c2feb9', version=1) + True + """ + if not isinstance(obj, uuid.UUID): + try: + obj = uuid.UUID(obj) + except (TypeError, ValueError, AttributeError): + return False + if version and obj.version != int(version): + return False + return True + + +def escape_shell_args(args, sep=' ', style=None): + """Returns an escaped version of each string in *args*, according to + *style*. + + Args: + args (list): A list of arguments to escape and join together + sep (str): The separator used to join the escaped arguments. + style (str): The style of escaping to use. Can be one of + ``cmd`` or ``sh``, geared toward Windows and Linux/BSD/etc., + respectively. If *style* is ``None``, then it is picked + according to the system platform. + + See :func:`args2cmd` and :func:`args2sh` for details and example + output for each style. + """ + if not style: + style = 'cmd' if sys.platform == 'win32' else 'sh' + + if style == 'sh': + return args2sh(args, sep=sep) + elif style == 'cmd': + return args2cmd(args, sep=sep) + + raise ValueError("style expected one of 'cmd' or 'sh', not %r" % style) + + +_find_sh_unsafe = re.compile(r'[^a-zA-Z0-9_@%+=:,./-]').search + + +def args2sh(args, sep=' '): + """Return a shell-escaped string version of *args*, separated by + *sep*, based on the rules of sh, bash, and other shells in the + Linux/BSD/MacOS ecosystem. + + >>> print(args2sh(['aa', '[bb]', "cc'cc", 'dd"dd'])) + aa '[bb]' 'cc'"'"'cc' 'dd"dd' + + As you can see, arguments with no special characters are not + escaped, arguments with special characters are quoted with single + quotes, and single quotes themselves are quoted with double + quotes. Double quotes are handled like any other special + character. + + Based on code from the :mod:`pipes`/:mod:`shlex` modules. Also + note that :mod:`shlex` and :mod:`argparse` have functions to split + and parse strings escaped in this manner. + """ + ret_list = [] + + for arg in args: + if not arg: + ret_list.append("''") + continue + if _find_sh_unsafe(arg) is None: + ret_list.append(arg) + continue + # use single quotes, and put single quotes into double quotes + # the string $'b is then quoted as '$'"'"'b' + ret_list.append("'" + arg.replace("'", "'\"'\"'") + "'") + + return ' '.join(ret_list) + + +def args2cmd(args, sep=' '): + r"""Return a shell-escaped string version of *args*, separated by + *sep*, using the same rules as the Microsoft C runtime. + + >>> print(args2cmd(['aa', '[bb]', "cc'cc", 'dd"dd'])) + aa [bb] cc'cc dd\"dd + + As you can see, escaping is through backslashing and not quoting, + and double quotes are the only special character. See the comment + in the code for more details. Based on internal code from the + :mod:`subprocess` module. + + """ + # technique description from subprocess below + """ + 1) Arguments are delimited by white space, which is either a + space or a tab. + + 2) A string surrounded by double quotation marks is + interpreted as a single argument, regardless of white space + contained within. A quoted string can be embedded in an + argument. + + 3) A double quotation mark preceded by a backslash is + interpreted as a literal double quotation mark. + + 4) Backslashes are interpreted literally, unless they + immediately precede a double quotation mark. + + 5) If backslashes immediately precede a double quotation mark, + every pair of backslashes is interpreted as a literal + backslash. If the number of backslashes is odd, the last + backslash escapes the next double quotation mark as + described in rule 3. + + See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx + or search http://msdn.microsoft.com for + "Parsing C++ Command-Line Arguments" + """ + result = [] + needquote = False + for arg in args: + bs_buf = [] + + # Add a space to separate this argument from the others + if result: + result.append(' ') + + needquote = (" " in arg) or ("\t" in arg) or not arg + if needquote: + result.append('"') + + for c in arg: + if c == '\\': + # Don't know if we need to double yet. + bs_buf.append(c) + elif c == '"': + # Double backslashes. + result.append('\\' * len(bs_buf)*2) + bs_buf = [] + result.append('\\"') + else: + # Normal char + if bs_buf: + result.extend(bs_buf) + bs_buf = [] + result.append(c) + + # Add remaining backslashes, if any. + if bs_buf: + result.extend(bs_buf) + + if needquote: + result.extend(bs_buf) + result.append('"') + + return ''.join(result) + + +def parse_int_list(range_string, delim=',', range_delim='-'): + """Returns a sorted list of positive integers based on + *range_string*. Reverse of :func:`format_int_list`. + + Args: + range_string (str): String of comma separated positive + integers or ranges (e.g. '1,2,4-6,8'). Typical of a custom + page range string used in printer dialogs. + delim (char): Defaults to ','. Separates integers and + contiguous ranges of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous + range of integers. + + >>> parse_int_list('1,3,5-8,10-11,15') + [1, 3, 5, 6, 7, 8, 10, 11, 15] + + """ + output = [] + + for x in range_string.strip().split(delim): + + # Range + if range_delim in x: + range_limits = list(map(int, x.split(range_delim))) + output += list(range(min(range_limits), max(range_limits)+1)) + + # Empty String + elif not x: + continue + + # Integer + else: + output.append(int(x)) + + return sorted(output) + + +def format_int_list(int_list, delim=',', range_delim='-', delim_space=False): + """Returns a sorted range string from a list of positive integers + (*int_list*). Contiguous ranges of integers are collapsed to min + and max values. Reverse of :func:`parse_int_list`. + + Args: + int_list (list): List of positive integers to be converted + into a range string (e.g. [1,2,4,5,6,8]). + delim (char): Defaults to ','. Separates integers and + contiguous ranges of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous + range of integers. + delim_space (bool): Defaults to ``False``. If ``True``, adds a + space after all *delim* characters. + + >>> format_int_list([1,3,5,6,7,8,10,11,15]) + '1,3,5-8,10-11,15' + + """ + output = [] + contig_range = collections.deque() + + for x in sorted(int_list): + + # Handle current (and first) value. + if len(contig_range) < 1: + contig_range.append(x) + + # Handle current value, given multiple previous values are contiguous. + elif len(contig_range) > 1: + delta = x - contig_range[-1] + + # Current value is contiguous. + if delta == 1: + contig_range.append(x) + + # Current value is non-contiguous. + elif delta > 1: + range_substr = '{:d}{}{:d}'.format(min(contig_range), + range_delim, + max(contig_range)) + output.append(range_substr) + contig_range.clear() + contig_range.append(x) + + # Current value repeated. + else: + continue + + # Handle current value, given no previous contiguous integers + else: + delta = x - contig_range[0] + + # Current value is contiguous. + if delta == 1: + contig_range.append(x) + + # Current value is non-contiguous. + elif delta > 1: + output.append(f'{contig_range.popleft():d}') + contig_range.append(x) + + # Current value repeated. + else: + continue + + # Handle the last value. + else: + + # Last value is non-contiguous. + if len(contig_range) == 1: + output.append(f'{contig_range.popleft():d}') + contig_range.clear() + + # Last value is part of contiguous range. + elif len(contig_range) > 1: + range_substr = '{:d}{}{:d}'.format(min(contig_range), + range_delim, + max(contig_range)) + output.append(range_substr) + contig_range.clear() + + if delim_space: + output_str = (delim+' ').join(output) + else: + output_str = delim.join(output) + + return output_str + + +def complement_int_list( + range_string, range_start=0, range_end=None, + delim=',', range_delim='-'): + """ Returns range string that is the complement of the one provided as + *range_string* parameter. + + These range strings are of the kind produce by :func:`format_int_list`, and + parseable by :func:`parse_int_list`. + + Args: + range_string (str): String of comma separated positive integers or + ranges (e.g. '1,2,4-6,8'). Typical of a custom page range string + used in printer dialogs. + range_start (int): A positive integer from which to start the resulting + range. Value is inclusive. Defaults to ``0``. + range_end (int): A positive integer from which the produced range is + stopped. Value is exclusive. Defaults to the maximum value found in + the provided ``range_string``. + delim (char): Defaults to ','. Separates integers and contiguous ranges + of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous range of + integers. + + >>> complement_int_list('1,3,5-8,10-11,15') + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=0) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=1) + '2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=2) + '2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=3) + '4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=15) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=14) + '0,2,4,9,12-13' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=13) + '0,2,4,9,12' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=20) + '0,2,4,9,12-14,16-19' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=0) + '' + + >>> complement_int_list('1,3,5-8,10-11,15', range_start=-1) + '0,2,4,9,12-14' + + >>> complement_int_list('1,3,5-8,10-11,15', range_end=-1) + '' + + >>> complement_int_list('1,3,5-8', range_start=1, range_end=1) + '' + + >>> complement_int_list('1,3,5-8', range_start=2, range_end=2) + '' + + >>> complement_int_list('1,3,5-8', range_start=2, range_end=3) + '2' + + >>> complement_int_list('1,3,5-8', range_start=-10, range_end=-5) + '' + + >>> complement_int_list('1,3,5-8', range_start=20, range_end=10) + '' + + >>> complement_int_list('') + '' + """ + int_list = set(parse_int_list(range_string, delim, range_delim)) + if range_end is None: + if int_list: + range_end = max(int_list) + 1 + else: + range_end = range_start + complement_values = set( + range(range_end)) - int_list - set(range(range_start)) + return format_int_list(complement_values, delim, range_delim) + + +def int_ranges_from_int_list(range_string, delim=',', range_delim='-'): + """ Transform a string of ranges (*range_string*) into a tuple of tuples. + + Args: + range_string (str): String of comma separated positive integers or + ranges (e.g. '1,2,4-6,8'). Typical of a custom page range string + used in printer dialogs. + delim (char): Defaults to ','. Separates integers and contiguous ranges + of integers. + range_delim (char): Defaults to '-'. Indicates a contiguous range of + integers. + + >>> int_ranges_from_int_list('1,3,5-8,10-11,15') + ((1, 1), (3, 3), (5, 8), (10, 11), (15, 15)) + + >>> int_ranges_from_int_list('1') + ((1, 1),) + + >>> int_ranges_from_int_list('') + () + """ + int_tuples = [] + # Normalize the range string to our internal format for processing. + range_string = format_int_list( + parse_int_list(range_string, delim, range_delim)) + if range_string: + for bounds in range_string.split(','): + if '-' in bounds: + start, end = bounds.split('-') + else: + start, end = bounds, bounds + int_tuples.append((int(start), int(end))) + return tuple(int_tuples) + + +class MultiReplace: + """ + MultiReplace is a tool for doing multiple find/replace actions in one pass. + + Given a mapping of values to be replaced it allows for all of the matching + values to be replaced in a single pass which can save a lot of performance + on very large strings. In addition to simple replace, it also allows for + replacing based on regular expressions. + + Keyword Arguments: + + :type regex: bool + :param regex: Treat search keys as regular expressions [Default: False] + :type flags: int + :param flags: flags to pass to the regex engine during compile + + Dictionary Usage:: + + from boltons import strutils + s = strutils.MultiReplace({ + 'foo': 'zoo', + 'cat': 'hat', + 'bat': 'kraken' + }) + new = s.sub('The foo bar cat ate a bat') + new == 'The zoo bar hat ate a kraken' + + Iterable Usage:: + + from boltons import strutils + s = strutils.MultiReplace([ + ('foo', 'zoo'), + ('cat', 'hat'), + ('bat', 'kraken)' + ]) + new = s.sub('The foo bar cat ate a bat') + new == 'The zoo bar hat ate a kraken' + + + The constructor can be passed a dictionary or other mapping as well as + an iterable of tuples. If given an iterable, the substitution will be run + in the order the replacement values are specified in the iterable. This is + also true if it is given an OrderedDict. If given a dictionary then the + order will be non-deterministic:: + + >>> 'foo bar baz'.replace('foo', 'baz').replace('baz', 'bar') + 'bar bar bar' + >>> m = MultiReplace({'foo': 'baz', 'baz': 'bar'}) + >>> m.sub('foo bar baz') + 'baz bar bar' + + This is because the order of replacement can matter if you're inserting + something that might be replaced by a later substitution. Pay attention and + if you need to rely on order then consider using a list of tuples instead + of a dictionary. + """ + + def __init__(self, sub_map, **kwargs): + """Compile any regular expressions that have been passed.""" + options = { + 'regex': False, + 'flags': 0, + } + options.update(kwargs) + self.group_map = {} + regex_values = [] + + if isinstance(sub_map, Mapping): + sub_map = sub_map.items() + + for idx, vals in enumerate(sub_map): + group_name = f'group{idx}' + if isinstance(vals[0], str): + # If we're not treating input strings like a regex, escape it + if not options['regex']: + exp = re.escape(vals[0]) + else: + exp = vals[0] + else: + exp = vals[0].pattern + + regex_values.append(f'(?P<{group_name}>{exp})') + self.group_map[group_name] = vals[1] + + self.combined_pattern = re.compile( + '|'.join(regex_values), + flags=options['flags'] + ) + + def _get_value(self, match): + """Given a match object find replacement value.""" + group_dict = match.groupdict() + key = [x for x in group_dict if group_dict[x]][0] + return self.group_map[key] + + def sub(self, text): + """ + Run substitutions on the input text. + + Given an input string, run all substitutions given in the + constructor. + """ + return self.combined_pattern.sub(self._get_value, text) + + +def multi_replace(text, sub_map, **kwargs): + """ + Shortcut function to invoke MultiReplace in a single call. + + Example Usage:: + + from boltons.strutils import multi_replace + new = multi_replace( + 'The foo bar cat ate a bat', + {'foo': 'zoo', 'cat': 'hat', 'bat': 'kraken'} + ) + new == 'The zoo bar hat ate a kraken' + """ + m = MultiReplace(sub_map, **kwargs) + return m.sub(text) + + +def unwrap_text(text, ending='\n\n'): + r""" + Unwrap text, the natural complement to :func:`textwrap.wrap`. + + >>> text = "Short \n lines \nwrapped\nsmall.\n\nAnother\nparagraph." + >>> unwrap_text(text) + 'Short lines wrapped small.\n\nAnother paragraph.' + + Args: + text: A string to unwrap. + ending (str): The string to join all unwrapped paragraphs + by. Pass ``None`` to get the list. Defaults to '\n\n' for + compatibility with Markdown and RST. + + """ + all_grafs = [] + cur_graf = [] + for line in text.splitlines(): + line = line.strip() + if line: + cur_graf.append(line) + else: + all_grafs.append(' '.join(cur_graf)) + cur_graf = [] + if cur_graf: + all_grafs.append(' '.join(cur_graf)) + if ending is None: + return all_grafs + return ending.join(all_grafs) + +def removeprefix(text: str, prefix: str) -> str: + r""" + Remove `prefix` from start of `text` if present. + + Backport of `str.removeprefix` for Python versions less than 3.9. + + Args: + text: A string to remove the prefix from. + prefix: The string to remove from the beginning of `text`. + """ + if text.startswith(prefix): + return text[len(prefix):] + return text diff --git a/miniconda3/lib/python3.13/site-packages/boltons/tableutils.py b/miniconda3/lib/python3.13/site-packages/boltons/tableutils.py new file mode 100644 index 0000000000000000000000000000000000000000..46f155eb08ac6e0aa90db05e4768ec23f4ad6af1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/tableutils.py @@ -0,0 +1,583 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""If there is one recurring theme in ``boltons``, it is that Python +has excellent datastructures that constitute a good foundation for +most quick manipulations, as well as building applications. However, +Python usage has grown much faster than builtin data structure +power. Python has a growing need for more advanced general-purpose +data structures which behave intuitively. + +The :class:`Table` class is one example. When handed one- or +two-dimensional data, it can provide useful, if basic, text and HTML +renditions of small to medium sized data. It also heuristically +handles recursive data of various formats (lists, dicts, namedtuples, +objects). + +For more advanced :class:`Table`-style manipulation check out the +`pandas`_ DataFrame. + +.. _pandas: http://pandas.pydata.org/ + +""" + + +from html import escape as html_escape +import types +from itertools import islice +from collections.abc import Sequence, Mapping, MutableSequence + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + +""" +Some idle feature thoughts: + +* shift around column order without rearranging data +* gotta make it so you can add additional items, not just initialize with +* maybe a shortcut would be to allow adding of Tables to other Tables +* what's the perf of preallocating lists and overwriting items versus + starting from empty? +* is it possible to effectively tell the difference between when a + Table is from_data()'d with a single row (list) or with a list of lists? +* CSS: white-space pre-line or pre-wrap maybe? +* Would be nice to support different backends (currently uses lists + exclusively). Sometimes large datasets come in list-of-dicts and + list-of-tuples format and it's desirable to cut down processing overhead. + +TODO: make iterable on rows? +""" + +__all__ = ['Table'] + + +def to_text(obj, maxlen=None): + try: + text = str(obj) + except Exception: + try: + text = str(repr(obj)) + except Exception: + text = str(object.__repr__(obj)) + if maxlen and len(text) > maxlen: + text = text[:maxlen - 3] + '...' + # TODO: inverse of ljust/rjust/center + return text + + +def escape_html(obj, maxlen=None): + text = to_text(obj, maxlen=maxlen) + return html_escape(text, quote=True) + + +_DNR = {type(None), bool, complex, float, type(NotImplemented), slice, + str, bytes, int, + types.FunctionType, types.MethodType, + types.BuiltinFunctionType, types.GeneratorType} + + +class UnsupportedData(TypeError): + pass + + +class InputType: + def __init__(self, *a, **kw): + pass + + def get_entry_seq(self, data_seq, headers): + return [self.get_entry(entry, headers) for entry in data_seq] + + +class DictInputType(InputType): + def check_type(self, obj): + return isinstance(obj, Mapping) + + def guess_headers(self, obj): + return sorted(obj.keys()) + + def get_entry(self, obj, headers): + return [obj.get(h) for h in headers] + + def get_entry_seq(self, obj, headers): + return [[ci.get(h) for h in headers] for ci in obj] + + +class ObjectInputType(InputType): + def check_type(self, obj): + return type(obj) not in _DNR and hasattr(obj, '__class__') + + def guess_headers(self, obj): + headers = [] + for attr in dir(obj): + # an object's __dict__ could technically have non-string keys + try: + val = getattr(obj, attr) + except Exception: + # seen on greenlet: `run` shows in dir() but raises + # AttributeError. Also properties misbehave. + continue + if callable(val): + continue + headers.append(attr) + return headers + + def get_entry(self, obj, headers): + values = [] + for h in headers: + try: + values.append(getattr(obj, h)) + except Exception: + values.append(None) + return values + + +# might be better to hardcode list support since it's so close to the +# core or might be better to make this the copy-style from_* importer +# and have the non-copy style be hardcoded in __init__ +class ListInputType(InputType): + def check_type(self, obj): + return isinstance(obj, MutableSequence) + + def guess_headers(self, obj): + return None + + def get_entry(self, obj, headers): + return obj + + def get_entry_seq(self, obj_seq, headers): + return obj_seq + + +class TupleInputType(InputType): + def check_type(self, obj): + return isinstance(obj, tuple) + + def guess_headers(self, obj): + return None + + def get_entry(self, obj, headers): + return list(obj) + + def get_entry_seq(self, obj_seq, headers): + return [list(t) for t in obj_seq] + + +class NamedTupleInputType(InputType): + def check_type(self, obj): + return hasattr(obj, '_fields') and isinstance(obj, tuple) + + def guess_headers(self, obj): + return list(obj._fields) + + def get_entry(self, obj, headers): + return [getattr(obj, h, None) for h in headers] + + def get_entry_seq(self, obj_seq, headers): + return [[getattr(obj, h, None) for h in headers] for obj in obj_seq] + + +class Table: + """ + This Table class is meant to be simple, low-overhead, and extensible. Its + most common use would be for translation between in-memory data + structures and serialization formats, such as HTML and console-ready text. + + As such, it stores data in list-of-lists format, and *does not* copy + lists passed in. It also reserves the right to modify those lists in a + "filling" process, whereby short lists are extended to the width of + the table (usually determined by number of headers). This greatly + reduces overhead and processing/validation that would have to occur + otherwise. + + General description of headers behavior: + + Headers describe the columns, but are not part of the data, however, + if the *headers* argument is omitted, Table tries to infer header + names from the data. It is possible to have a table with no headers, + just pass in ``headers=None``. + + Supported inputs: + + * :class:`list` of :class:`list` objects + * :class:`dict` (list/single) + * :class:`object` (list/single) + * :class:`collections.namedtuple` (list/single) + * TODO: DB API cursor? + * TODO: json + + Supported outputs: + + * HTML + * Pretty text (also usable as GF Markdown) + * TODO: CSV + * TODO: json + * TODO: json lines + + To minimize resident size, the Table data is stored as a list of lists. + """ + + # order definitely matters here + _input_types = [DictInputType(), ListInputType(), + NamedTupleInputType(), TupleInputType(), + ObjectInputType()] + + _html_tr, _html_tr_close = '', '' + _html_th, _html_th_close = '', '' + _html_td, _html_td_close = '', '' + _html_thead, _html_thead_close = '', '' + _html_tbody, _html_tbody_close = '', '' + + # _html_tfoot, _html_tfoot_close = '', '' + _html_table_tag, _html_table_tag_close = '', '
' + + def __init__(self, data=None, headers=_MISSING, metadata=None): + if headers is _MISSING: + headers = [] + if data: + headers, data = list(data[0]), islice(data, 1, None) + self.headers = headers or [] + self.metadata = metadata or {} + self._data = [] + self._width = 0 + + self.extend(data) + + def extend(self, data): + """ + Append the given data to the end of the Table. + """ + if not data: + return + self._data.extend(data) + self._set_width() + self._fill() + + def _set_width(self, reset=False): + if reset: + self._width = 0 + if self._width: + return + if self.headers: + self._width = len(self.headers) + return + self._width = max([len(d) for d in self._data]) + + def _fill(self): + width, filler = self._width, [None] + if not width: + return + for d in self._data: + rem = width - len(d) + if rem > 0: + d.extend(filler * rem) + return + + @classmethod + def from_dict(cls, data, headers=_MISSING, max_depth=1, metadata=None): + """Create a Table from a :class:`dict`. Operates the same as + :meth:`from_data`, but forces interpretation of the data as a + Mapping. + """ + return cls.from_data(data=data, headers=headers, + max_depth=max_depth, _data_type=DictInputType(), + metadata=metadata) + + @classmethod + def from_list(cls, data, headers=_MISSING, max_depth=1, metadata=None): + """Create a Table from a :class:`list`. Operates the same as + :meth:`from_data`, but forces the interpretation of the data + as a Sequence. + """ + return cls.from_data(data=data, headers=headers, + max_depth=max_depth, _data_type=ListInputType(), + metadata=metadata) + + @classmethod + def from_object(cls, data, headers=_MISSING, max_depth=1, metadata=None): + """Create a Table from an :class:`object`. Operates the same as + :meth:`from_data`, but forces the interpretation of the data + as an object. May be useful for some :class:`dict` and + :class:`list` subtypes. + """ + return cls.from_data(data=data, headers=headers, + max_depth=max_depth, _data_type=ObjectInputType(), + metadata=metadata) + + @classmethod + def from_data(cls, data, headers=_MISSING, max_depth=1, **kwargs): + + """Create a Table from any supported data, heuristically + selecting how to represent the data in Table format. + + Args: + data (object): Any object or iterable with data to be + imported to the Table. + + headers (iterable): An iterable of headers to be matched + to the data. If not explicitly passed, headers will be + guessed for certain datatypes. + + max_depth (int): The level to which nested Tables should + be created (default: 1). + + _data_type (InputType subclass): For advanced use cases, + do not guess the type of the input data, use this data + type instead. + """ + # TODO: seen/cycle detection/reuse ? + # maxdepth follows the same behavior as find command + # i.e., it doesn't work if max_depth=0 is passed in + metadata = kwargs.pop('metadata', None) + _data_type = kwargs.pop('_data_type', None) + + if max_depth < 1: + # return data instead? + return cls(headers=headers, metadata=metadata) + is_seq = isinstance(data, Sequence) + if is_seq: + if not data: + return cls(headers=headers, metadata=metadata) + to_check = data[0] + if not _data_type: + for it in cls._input_types: + if it.check_type(to_check): + _data_type = it + break + else: + # not particularly happy about this rewind-y approach + is_seq = False + to_check = data + else: + if type(data) in _DNR: + # hmm, got scalar data. + # raise an exception or make an exception, nahmsayn? + return cls([[data]], headers=headers, metadata=metadata) + to_check = data + if not _data_type: + for it in cls._input_types: + if it.check_type(to_check): + _data_type = it + break + else: + raise UnsupportedData('unsupported data type %r' + % type(data)) + if headers is _MISSING: + headers = _data_type.guess_headers(to_check) + if is_seq: + entries = _data_type.get_entry_seq(data, headers) + else: + entries = [_data_type.get_entry(data, headers)] + if max_depth > 1: + new_max_depth = max_depth - 1 + for i, entry in enumerate(entries): + for j, cell in enumerate(entry): + if type(cell) in _DNR: + # optimization to avoid function overhead + continue + try: + entries[i][j] = cls.from_data(cell, + max_depth=new_max_depth) + except UnsupportedData: + continue + return cls(entries, headers=headers, metadata=metadata) + + def __len__(self): + return len(self._data) + + def __getitem__(self, idx): + return self._data[idx] + + def __repr__(self): + cn = self.__class__.__name__ + if self.headers: + return f'{cn}(headers={self.headers!r}, data={self._data!r})' + else: + return f'{cn}({self._data!r})' + + def to_html(self, orientation=None, wrapped=True, + with_headers=True, with_newlines=True, + with_metadata=False, max_depth=1): + """Render this Table to HTML. Configure the structure of Table + HTML by subclassing and overriding ``_html_*`` class + attributes. + + Args: + orientation (str): one of 'auto', 'horizontal', or + 'vertical' (or the first letter of any of + those). Default 'auto'. + wrapped (bool): whether or not to include the wrapping + '
' tags. Default ``True``, set to + ``False`` if appending multiple Table outputs or an + otherwise customized HTML wrapping tag is needed. + with_newlines (bool): Set to ``True`` if output should + include added newlines to make the HTML more + readable. Default ``False``. + with_metadata (bool/str): Set to ``True`` if output should + be preceded with a Table of preset metadata, if it + exists. Set to special value ``'bottom'`` if the + metadata Table HTML should come *after* the main HTML output. + max_depth (int): Indicate how deeply to nest HTML tables + before simply reverting to :func:`repr`-ing the nested + data. + + Returns: + A text string of the HTML of the rendered table. + + """ + lines = [] + headers = [] + if with_metadata and self.metadata: + metadata_table = Table.from_data(self.metadata, + max_depth=max_depth) + metadata_html = metadata_table.to_html(with_headers=True, + with_newlines=with_newlines, + with_metadata=False, + max_depth=max_depth) + if with_metadata != 'bottom': + lines.append(metadata_html) + lines.append('
') + + if with_headers and self.headers: + headers.extend(self.headers) + headers.extend([None] * (self._width - len(self.headers))) + if wrapped: + lines.append(self._html_table_tag) + orientation = orientation or 'auto' + ol = orientation[0].lower() + if ol == 'a': + ol = 'h' if len(self) > 1 else 'v' + if ol == 'h': + self._add_horizontal_html_lines(lines, headers=headers, + max_depth=max_depth) + elif ol == 'v': + self._add_vertical_html_lines(lines, headers=headers, + max_depth=max_depth) + else: + raise ValueError("expected one of 'auto', 'vertical', or" + " 'horizontal', not %r" % orientation) + if with_metadata and self.metadata and with_metadata == 'bottom': + lines.append('
') + lines.append(metadata_html) + + if wrapped: + lines.append(self._html_table_tag_close) + sep = '\n' if with_newlines else '' + return sep.join(lines) + + def get_cell_html(self, value): + """Called on each value in an HTML table. By default it simply escapes + the HTML. Override this method to add additional conditions + and behaviors, but take care to ensure the final output is + HTML escaped. + """ + return escape_html(value) + + def _add_horizontal_html_lines(self, lines, headers, max_depth): + esc = self.get_cell_html + new_depth = max_depth - 1 if max_depth > 1 else max_depth + if max_depth > 1: + new_depth = max_depth - 1 + if headers: + _thth = self._html_th_close + self._html_th + lines.append(self._html_thead) + lines.append(self._html_tr + self._html_th + + _thth.join([esc(h) for h in headers]) + + self._html_th_close + self._html_tr_close) + lines.append(self._html_thead_close) + trtd, _tdtd, _td_tr = (self._html_tr + self._html_td, + self._html_td_close + self._html_td, + self._html_td_close + self._html_tr_close) + lines.append(self._html_tbody) + for row in self._data: + if max_depth > 1: + _fill_parts = [] + for cell in row: + if isinstance(cell, Table): + _fill_parts.append(cell.to_html(max_depth=new_depth)) + else: + _fill_parts.append(esc(cell)) + else: + _fill_parts = [esc(c) for c in row] + lines.append(''.join([trtd, _tdtd.join(_fill_parts), _td_tr])) + lines.append(self._html_tbody_close) + + def _add_vertical_html_lines(self, lines, headers, max_depth): + esc = self.get_cell_html + new_depth = max_depth - 1 if max_depth > 1 else max_depth + tr, th, _th = self._html_tr, self._html_th, self._html_th_close + td, _tdtd = self._html_td, self._html_td_close + self._html_td + _td_tr = self._html_td_close + self._html_tr_close + for i in range(self._width): + line_parts = [tr] + if headers: + line_parts.extend([th, esc(headers[i]), _th]) + if max_depth > 1: + new_depth = max_depth - 1 + _fill_parts = [] + for row in self._data: + cell = row[i] + if isinstance(cell, Table): + _fill_parts.append(cell.to_html(max_depth=new_depth)) + else: + _fill_parts.append(esc(row[i])) + else: + _fill_parts = [esc(row[i]) for row in self._data] + line_parts.extend([td, _tdtd.join(_fill_parts), _td_tr]) + lines.append(''.join(line_parts)) + + def to_text(self, with_headers=True, maxlen=None): + """Get the Table's textual representation. Only works well + for Tables with non-recursive data. + + Args: + with_headers (bool): Whether to include a header row at the top. + maxlen (int): Max length of data in each cell. + """ + lines = [] + widths = [] + headers = list(self.headers) + text_data = [[to_text(cell, maxlen=maxlen) for cell in row] + for row in self._data] + for idx in range(self._width): + cur_widths = [len(cur) for cur in text_data] + if with_headers: + cur_widths.append(len(to_text(headers[idx], maxlen=maxlen))) + widths.append(max(cur_widths)) + if with_headers: + lines.append(' | '.join([h.center(widths[i]) + for i, h in enumerate(headers)])) + lines.append('-|-'.join(['-' * w for w in widths])) + for row in text_data: + lines.append(' | '.join([cell.center(widths[j]) + for j, cell in enumerate(row)])) + return '\n'.join(lines) diff --git a/miniconda3/lib/python3.13/site-packages/boltons/tbutils.py b/miniconda3/lib/python3.13/site-packages/boltons/tbutils.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc49840cc92ccebf5506914c69c14252b158cfe --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/tbutils.py @@ -0,0 +1,820 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""One of the oft-cited tenets of Python is that it is better to ask +forgiveness than permission. That is, there are many cases where it is +more inclusive and correct to handle exceptions than spend extra lines +and execution time checking for conditions. This philosophy makes good +exception handling features all the more important. Unfortunately +Python's :mod:`traceback` module is woefully behind the times. + +The ``tbutils`` module provides two disparate but complementary featuresets: + + 1. With :class:`ExceptionInfo` and :class:`TracebackInfo`, the + ability to extract, construct, manipulate, format, and serialize + exceptions, tracebacks, and callstacks. + 2. With :class:`ParsedException`, the ability to find and parse tracebacks + from captured output such as logs and stdout. + +There is also the :class:`ContextualTracebackInfo` variant of +:class:`TracebackInfo`, which includes much more information from each +frame of the callstack, including values of locals and neighboring +lines of code. +""" + + +import re +import sys +import linecache + + +# TODO: chaining primitives? what are real use cases where these help? + +# TODO: print_* for backwards compatibility +# __all__ = ['extract_stack', 'extract_tb', 'format_exception', +# 'format_exception_only', 'format_list', 'format_stack', +# 'format_tb', 'print_exc', 'format_exc', 'print_exception', +# 'print_last', 'print_stack', 'print_tb'] + + +__all__ = ['ExceptionInfo', 'TracebackInfo', 'Callpoint', + 'ContextualExceptionInfo', 'ContextualTracebackInfo', + 'ContextualCallpoint', 'print_exception', 'ParsedException'] + + +class Callpoint: + """The Callpoint is a lightweight object used to represent a single + entry in the code of a call stack. It stores the code-related + metadata of a given frame. Available attributes are the same as + the parameters below. + + Args: + func_name (str): the function name + lineno (int): the line number + module_name (str): the module name + module_path (str): the filesystem path of the module + lasti (int): the index of bytecode execution + line (str): the single-line code content (if available) + + """ + __slots__ = ('func_name', 'lineno', 'module_name', 'module_path', 'lasti', + 'line') + + def __init__(self, module_name, module_path, func_name, + lineno, lasti, line=None): + self.func_name = func_name + self.lineno = lineno + self.module_name = module_name + self.module_path = module_path + self.lasti = lasti + self.line = line + + def to_dict(self): + "Get a :class:`dict` copy of the Callpoint. Useful for serialization." + ret = {} + for slot in self.__slots__: + try: + val = getattr(self, slot) + except AttributeError: + pass + else: + ret[slot] = str(val) if isinstance(val, _DeferredLine) else val + return ret + + @classmethod + def from_current(cls, level=1): + "Creates a Callpoint from the location of the calling function." + frame = sys._getframe(level) + return cls.from_frame(frame) + + @classmethod + def from_frame(cls, frame): + "Create a Callpoint object from data extracted from the given frame." + func_name = frame.f_code.co_name + lineno = frame.f_lineno + module_name = frame.f_globals.get('__name__', '') + module_path = frame.f_code.co_filename + lasti = frame.f_lasti + line = _DeferredLine(module_path, lineno, frame.f_globals) + return cls(module_name, module_path, func_name, + lineno, lasti, line=line) + + @classmethod + def from_tb(cls, tb): + """Create a Callpoint from the traceback of the current + exception. Main difference with :meth:`from_frame` is that + ``lineno`` and ``lasti`` come from the traceback, which is to + say the line that failed in the try block, not the line + currently being executed (in the except block). + """ + func_name = tb.tb_frame.f_code.co_name + lineno = tb.tb_lineno + lasti = tb.tb_lasti + module_name = tb.tb_frame.f_globals.get('__name__', '') + module_path = tb.tb_frame.f_code.co_filename + line = _DeferredLine(module_path, lineno, tb.tb_frame.f_globals) + return cls(module_name, module_path, func_name, + lineno, lasti, line=line) + + def __repr__(self): + cn = self.__class__.__name__ + args = [getattr(self, s, None) for s in self.__slots__] + if not any(args): + return super().__repr__() + else: + return '{}({})'.format(cn, ', '.join([repr(a) for a in args])) + + def tb_frame_str(self): + """Render the Callpoint as it would appear in a standard printed + Python traceback. Returns a string with filename, line number, + function name, and the actual code line of the error on up to + two lines. + """ + ret = ' File "{}", line {}, in {}\n'.format(self.module_path, + self.lineno, + self.func_name) + if self.line: + ret += f' {str(self.line).strip()}\n' + return ret + + +class _DeferredLine: + """The _DeferredLine type allows Callpoints and TracebackInfos to be + constructed without potentially hitting the filesystem, as is the + normal behavior of the standard Python :mod:`traceback` and + :mod:`linecache` modules. Calling :func:`str` fetches and caches + the line. + + Args: + filename (str): the path of the file containing the line + lineno (int): the number of the line in question + module_globals (dict): an optional dict of module globals, + used to handle advanced use cases using custom module loaders. + + """ + __slots__ = ('filename', 'lineno', '_line', '_mod_name', '_mod_loader') + + def __init__(self, filename, lineno, module_globals=None): + self.filename = filename + self.lineno = lineno + if module_globals is None: + self._mod_name = None + self._mod_loader = None + else: + self._mod_name = module_globals.get('__name__') + self._mod_loader = module_globals.get('__loader__') + + def __eq__(self, other): + return (self.lineno, self.filename) == (other.lineno, other.filename) + + def __ne__(self, other): + return not self == other + + def __str__(self): + ret = getattr(self, '_line', None) + if ret is not None: + return ret + try: + linecache.checkcache(self.filename) + mod_globals = {'__name__': self._mod_name, + '__loader__': self._mod_loader} + line = linecache.getline(self.filename, + self.lineno, + mod_globals) + line = line.rstrip() + except KeyError: + line = '' + self._line = line + return line + + def __repr__(self): + return repr(str(self)) + + def __len__(self): + return len(str(self)) + + +# TODO: dedup frames, look at __eq__ on _DeferredLine +class TracebackInfo: + """The TracebackInfo class provides a basic representation of a stack + trace, be it from an exception being handled or just part of + normal execution. It is basically a wrapper around a list of + :class:`Callpoint` objects representing frames. + + Args: + frames (list): A list of frame objects in the stack. + + .. note :: + + ``TracebackInfo`` can represent both exception tracebacks and + non-exception tracebacks (aka stack traces). As a result, there + is no ``TracebackInfo.from_current()``, as that would be + ambiguous. Instead, call :meth:`TracebackInfo.from_frame` + without the *frame* argument for a stack trace, or + :meth:`TracebackInfo.from_traceback` without the *tb* argument + for an exception traceback. + """ + callpoint_type = Callpoint + + def __init__(self, frames): + self.frames = frames + + @classmethod + def from_frame(cls, frame=None, level=1, limit=None): + """Create a new TracebackInfo *frame* by recurring up in the stack a + max of *limit* times. If *frame* is unset, get the frame from + :func:`sys._getframe` using *level*. + + Args: + frame (types.FrameType): frame object from + :func:`sys._getframe` or elsewhere. Defaults to result + of :func:`sys.get_frame`. + level (int): If *frame* is unset, the desired frame is + this many levels up the stack from the invocation of + this method. Default ``1`` (i.e., caller of this method). + limit (int): max number of parent frames to extract + (defaults to :data:`sys.tracebacklimit`) + + """ + ret = [] + if frame is None: + frame = sys._getframe(level) + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while frame is not None and n < limit: + item = cls.callpoint_type.from_frame(frame) + ret.append(item) + frame = frame.f_back + n += 1 + ret.reverse() + return cls(ret) + + @classmethod + def from_traceback(cls, tb=None, limit=None): + """Create a new TracebackInfo from the traceback *tb* by recurring + up in the stack a max of *limit* times. If *tb* is unset, get + the traceback from the currently handled exception. If no + exception is being handled, raise a :exc:`ValueError`. + + Args: + + frame (types.TracebackType): traceback object from + :func:`sys.exc_info` or elsewhere. If absent or set to + ``None``, defaults to ``sys.exc_info()[2]``, and + raises a :exc:`ValueError` if no exception is + currently being handled. + limit (int): max number of parent frames to extract + (defaults to :data:`sys.tracebacklimit`) + + """ + ret = [] + if tb is None: + tb = sys.exc_info()[2] + if tb is None: + raise ValueError('no tb set and no exception being handled') + if limit is None: + limit = getattr(sys, 'tracebacklimit', 1000) + n = 0 + while tb is not None and n < limit: + item = cls.callpoint_type.from_tb(tb) + ret.append(item) + tb = tb.tb_next + n += 1 + return cls(ret) + + @classmethod + def from_dict(cls, d): + "Complements :meth:`TracebackInfo.to_dict`." + # TODO: check this. + return cls(d['frames']) + + def to_dict(self): + """Returns a dict with a list of :class:`Callpoint` frames converted + to dicts. + """ + return {'frames': [f.to_dict() for f in self.frames]} + + def __len__(self): + return len(self.frames) + + def __iter__(self): + return iter(self.frames) + + def __repr__(self): + cn = self.__class__.__name__ + + if self.frames: + frame_part = f' last={self.frames[-1]!r}' + else: + frame_part = '' + + return f'<{cn} frames={len(self.frames)}{frame_part}>' + + def __str__(self): + return self.get_formatted() + + def get_formatted(self): + """Returns a string as formatted in the traditional Python + built-in style observable when an exception is not caught. In + other words, mimics :func:`traceback.format_tb` and + :func:`traceback.format_stack`. + """ + ret = 'Traceback (most recent call last):\n' + ret += ''.join([f.tb_frame_str() for f in self.frames]) + return ret + + +class ExceptionInfo: + """An ExceptionInfo object ties together three main fields suitable + for representing an instance of an exception: The exception type + name, a string representation of the exception itself (the + exception message), and information about the traceback (stored as + a :class:`TracebackInfo` object). + + These fields line up with :func:`sys.exc_info`, but unlike the + values returned by that function, ExceptionInfo does not hold any + references to the real exception or traceback. This property makes + it suitable for serialization or long-term retention, without + worrying about formatting pitfalls, circular references, or leaking memory. + + Args: + + exc_type (str): The exception type name. + exc_msg (str): String representation of the exception value. + tb_info (TracebackInfo): Information about the stack trace of the + exception. + + Like the :class:`TracebackInfo`, ExceptionInfo is most commonly + instantiated from one of its classmethods: :meth:`from_exc_info` + or :meth:`from_current`. + """ + + #: Override this in inherited types to control the TracebackInfo type used + tb_info_type = TracebackInfo + + def __init__(self, exc_type, exc_msg, tb_info): + # TODO: additional fields for SyntaxErrors + self.exc_type = exc_type + self.exc_msg = exc_msg + self.tb_info = tb_info + + @classmethod + def from_exc_info(cls, exc_type, exc_value, traceback): + """Create an :class:`ExceptionInfo` object from the exception's type, + value, and traceback, as returned by :func:`sys.exc_info`. See + also :meth:`from_current`. + """ + type_str = exc_type.__name__ + type_mod = exc_type.__module__ + if type_mod not in ("__main__", "__builtin__", "exceptions", "builtins"): + type_str = f'{type_mod}.{type_str}' + val_str = _some_str(exc_value) + tb_info = cls.tb_info_type.from_traceback(traceback) + return cls(type_str, val_str, tb_info) + + @classmethod + def from_current(cls): + """Create an :class:`ExceptionInfo` object from the current exception + being handled, by way of :func:`sys.exc_info`. Will raise an + exception if no exception is currently being handled. + """ + return cls.from_exc_info(*sys.exc_info()) + + def to_dict(self): + """Get a :class:`dict` representation of the ExceptionInfo, suitable + for JSON serialization. + """ + return {'exc_type': self.exc_type, + 'exc_msg': self.exc_msg, + 'exc_tb': self.tb_info.to_dict()} + + def __repr__(self): + cn = self.__class__.__name__ + try: + len_frames = len(self.tb_info.frames) + last_frame = f', last={self.tb_info.frames[-1]!r}' + except Exception: + len_frames = 0 + last_frame = '' + args = (cn, self.exc_type, self.exc_msg, len_frames, last_frame) + return '<%s [%s: %s] (%s frames%s)>' % args + + def get_formatted(self): + """Returns a string formatted in the traditional Python + built-in style observable when an exception is not caught. In + other words, mimics :func:`traceback.format_exception`. + """ + # TODO: add SyntaxError formatting + tb_str = self.tb_info.get_formatted() + return ''.join([tb_str, f'{self.exc_type}: {self.exc_msg}']) + + def get_formatted_exception_only(self): + return f'{self.exc_type}: {self.exc_msg}' + + +class ContextualCallpoint(Callpoint): + """The ContextualCallpoint is a :class:`Callpoint` subtype with the + exact same API and storing two additional values: + + 1. :func:`repr` outputs for local variables from the Callpoint's scope + 2. A number of lines before and after the Callpoint's line of code + + The ContextualCallpoint is used by the :class:`ContextualTracebackInfo`. + """ + def __init__(self, *a, **kw): + self.local_reprs = kw.pop('local_reprs', {}) + self.pre_lines = kw.pop('pre_lines', []) + self.post_lines = kw.pop('post_lines', []) + super().__init__(*a, **kw) + + @classmethod + def from_frame(cls, frame): + "Identical to :meth:`Callpoint.from_frame`" + ret = super().from_frame(frame) + ret._populate_local_reprs(frame.f_locals) + ret._populate_context_lines() + return ret + + @classmethod + def from_tb(cls, tb): + "Identical to :meth:`Callpoint.from_tb`" + ret = super().from_tb(tb) + ret._populate_local_reprs(tb.tb_frame.f_locals) + ret._populate_context_lines() + return ret + + def _populate_context_lines(self, pivot=8): + DL, lineno = _DeferredLine, self.lineno + try: + module_globals = self.line.module_globals + except AttributeError: + module_globals = None + start_line = max(0, lineno - pivot) + pre_lines = [DL(self.module_path, ln, module_globals) + for ln in range(start_line, lineno)] + self.pre_lines[:] = pre_lines + post_lines = [DL(self.module_path, ln, module_globals) + for ln in range(lineno + 1, lineno + 1 + pivot)] + self.post_lines[:] = post_lines + return + + def _populate_local_reprs(self, f_locals): + local_reprs = self.local_reprs + for k, v in f_locals.items(): + try: + local_reprs[k] = repr(v) + except Exception: + surrogate = '' % type(v).__name__ + local_reprs[k] = surrogate + return + + def to_dict(self): + """ + Same principle as :meth:`Callpoint.to_dict`, but with the added + contextual values. With ``ContextualCallpoint.to_dict()``, + each frame will now be represented like:: + + {'func_name': 'print_example', + 'lineno': 0, + 'module_name': 'example_module', + 'module_path': '/home/example/example_module.pyc', + 'lasti': 0, + 'line': 'print "example"', + 'locals': {'variable': '"value"'}, + 'pre_lines': ['variable = "value"'], + 'post_lines': []} + + The locals dictionary and line lists are copies and can be mutated + freely. + """ + ret = super().to_dict() + ret['locals'] = dict(self.local_reprs) + + # get the line numbers and textual lines + # without assuming DeferredLines + start_line = self.lineno - len(self.pre_lines) + pre_lines = [{'lineno': start_line + i, 'line': str(l)} + for i, l in enumerate(self.pre_lines)] + # trim off leading empty lines + for i, item in enumerate(pre_lines): + if item['line']: + break + if i: + pre_lines = pre_lines[i:] + ret['pre_lines'] = pre_lines + + # now post_lines + post_lines = [{'lineno': self.lineno + i, 'line': str(l)} + for i, l in enumerate(self.post_lines)] + _last = 0 + for i, item in enumerate(post_lines): + if item['line']: + _last = i + post_lines = post_lines[:_last + 1] + ret['post_lines'] = post_lines + return ret + + +class ContextualTracebackInfo(TracebackInfo): + """The ContextualTracebackInfo type is a :class:`TracebackInfo` + subtype that is used by :class:`ContextualExceptionInfo` and uses + the :class:`ContextualCallpoint` as its frame-representing + primitive. + """ + callpoint_type = ContextualCallpoint + + +class ContextualExceptionInfo(ExceptionInfo): + """The ContextualTracebackInfo type is a :class:`TracebackInfo` + subtype that uses the :class:`ContextualCallpoint` as its + frame-representing primitive. + + It carries with it most of the exception information required to + recreate the widely recognizable "500" page for debugging Django + applications. + """ + tb_info_type = ContextualTracebackInfo + + +# TODO: clean up & reimplement -- specifically for syntax errors +def format_exception_only(etype, value): + """Format the exception part of a traceback. + + The arguments are the exception type and value such as given by + sys.last_type and sys.last_value. The return value is a list of + strings, each ending in a newline. + + Normally, the list contains a single string; however, for + SyntaxError exceptions, it contains several lines that (when + printed) display detailed information about where the syntax + error occurred. + + The message indicating which exception occurred is always the last + string in the list. + + """ + # Gracefully handle (the way Python 2.4 and earlier did) the case of + # being called with (None, None). + if etype is None: + return [_format_final_exc_line(etype, value)] + + stype = etype.__name__ + smod = etype.__module__ + if smod not in ("__main__", "builtins", "exceptions"): + stype = smod + '.' + stype + + if not issubclass(etype, SyntaxError): + return [_format_final_exc_line(stype, value)] + + # It was a syntax error; show exactly where the problem was found. + lines = [] + filename = value.filename or "" + lineno = str(value.lineno) or '?' + lines.append(f' File "{filename}", line {lineno}\n') + badline = value.text + offset = value.offset + if badline is not None: + lines.append(' %s\n' % badline.strip()) + if offset is not None: + caretspace = badline.rstrip('\n')[:offset].lstrip() + # non-space whitespace (likes tabs) must be kept for alignment + caretspace = ((c.isspace() and c or ' ') for c in caretspace) + # only three spaces to account for offset1 == pos 0 + lines.append(' %s^\n' % ''.join(caretspace)) + msg = value.msg or "" + lines.append(f"{stype}: {msg}\n") + return lines + + +# TODO: use asciify, improved if necessary +def _some_str(value): + try: + return str(value) + except Exception: + pass + return '' % type(value).__name__ + + +def _format_final_exc_line(etype, value): + valuestr = _some_str(value) + if value is None or not valuestr: + line = "%s\n" % etype + else: + line = f"{etype}: {valuestr}\n" + return line + + +def print_exception(etype, value, tb, limit=None, file=None): + """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. + + This differs from print_tb() in the following ways: (1) if + traceback is not None, it prints a header "Traceback (most recent + call last):"; (2) it prints the exception type and value after the + stack trace; (3) if type is SyntaxError and value has the + appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error. + """ + + if file is None: + file = sys.stderr + if tb: + tbi = TracebackInfo.from_traceback(tb, limit) + print(str(tbi), end='', file=file) + + for line in format_exception_only(etype, value): + print(line, end='', file=file) + + +def fix_print_exception(): + """ + Sets the default exception hook :func:`sys.excepthook` to the + :func:`tbutils.print_exception` that uses all the ``tbutils`` + facilities to provide a consistent output behavior. + """ + sys.excepthook = print_exception + + +_frame_re = re.compile(r'^File "(?P.+)", line (?P\d+)' + r', in (?P.+)$') +_se_frame_re = re.compile(r'^File "(?P.+)", line (?P\d+)') +_underline_re = re.compile(r'^[~^ ]*$') + +# TODO: ParsedException generator over large bodies of text + +class ParsedException: + """Stores a parsed traceback and exception as would be typically + output by :func:`sys.excepthook` or + :func:`traceback.print_exception`. + + .. note: + + Does not currently store SyntaxError details such as column. + + """ + def __init__(self, exc_type_name, exc_msg, frames=None): + self.exc_type = exc_type_name + self.exc_msg = exc_msg + self.frames = list(frames or []) + + @property + def source_file(self): + """ + The file path of module containing the function that raised the + exception, or None if not available. + """ + try: + return self.frames[-1]['filepath'] + except IndexError: + return None + + def to_dict(self): + "Get a copy as a JSON-serializable :class:`dict`." + return {'exc_type': self.exc_type, + 'exc_msg': self.exc_msg, + 'frames': list(self.frames)} + + def __repr__(self): + cn = self.__class__.__name__ + return ('%s(%r, %r, frames=%r)' + % (cn, self.exc_type, self.exc_msg, self.frames)) + + def to_string(self): + """Formats the exception and its traceback into the standard format, + as returned by the traceback module. + + ``ParsedException.from_string(text).to_string()`` should yield + ``text``. + + .. note:: + + Note that this method does not output "anchors" (e.g., + ``~~~~~^^``), as were added in Python 3.13. See the built-in + ``traceback`` module if these are necessary. + """ + lines = ['Traceback (most recent call last):'] + + for frame in self.frames: + lines.append(' File "{}", line {}, in {}'.format(frame['filepath'], + frame['lineno'], + frame['funcname'])) + source_line = frame.get('source_line') + if source_line: + lines.append(f' {source_line}') + if self.exc_msg: + lines.append(f'{self.exc_type}: {self.exc_msg}') + else: + lines.append(f'{self.exc_type}') + return '\n'.join(lines) + + @classmethod + def from_string(cls, tb_str): + """Parse a traceback and exception from the text *tb_str*. This text + is expected to have been decoded, otherwise it will be + interpreted as UTF-8. + + This method does not search a larger body of text for + tracebacks. If the first line of the text passed does not + match one of the known patterns, a :exc:`ValueError` will be + raised. This method will ignore trailing text after the end of + the first traceback. + + Args: + tb_str (str): The traceback text (:class:`unicode` or UTF-8 bytes) + """ + if not isinstance(tb_str, str): + tb_str = tb_str.decode('utf-8') + tb_lines = tb_str.lstrip().splitlines() + + # First off, handle some ignored exceptions. These can be the + # result of exceptions raised by __del__ during garbage + # collection + while tb_lines: + cl = tb_lines[-1] + if cl.startswith('Exception ') and cl.endswith('ignored'): + tb_lines.pop() + else: + break + if tb_lines and tb_lines[0].strip() == 'Traceback (most recent call last):': + start_line = 1 + frame_re = _frame_re + elif len(tb_lines) > 1 and tb_lines[-2].lstrip().startswith('^'): + # This is to handle the slight formatting difference + # associated with SyntaxErrors, which also don't really + # have tracebacks + start_line = 0 + frame_re = _se_frame_re + else: + raise ValueError('unrecognized traceback string format') + + frames = [] + line_no = start_line + while True: + frame_line = tb_lines[line_no].strip() + frame_match = frame_re.match(frame_line) + if frame_match: + frame_dict = frame_match.groupdict() + try: + next_line = tb_lines[line_no + 1] + except IndexError: + # We read what we could + next_line = '' + next_line_stripped = next_line.strip() + if ( + frame_re.match(next_line_stripped) or + # The exception message will not be indented + # This check is to avoid overrunning on eval-like + # tracebacks where the last frame doesn't have source + # code in the traceback + not next_line.startswith(' ') + ): + frame_dict['source_line'] = '' + else: + frame_dict['source_line'] = next_line_stripped + line_no += 1 + if _underline_re.match(tb_lines[line_no + 1]): + # To deal with anchors + line_no += 1 + else: + break + line_no += 1 + frames.append(frame_dict) + + try: + exc_line = '\n'.join(tb_lines[line_no:]) + exc_type, _, exc_msg = exc_line.partition(': ') + except Exception: + exc_type, exc_msg = '', '' + + return cls(exc_type, exc_msg, frames) + + +ParsedTB = ParsedException # legacy alias diff --git a/miniconda3/lib/python3.13/site-packages/boltons/timeutils.py b/miniconda3/lib/python3.13/site-packages/boltons/timeutils.py new file mode 100644 index 0000000000000000000000000000000000000000..82f201ee94699223728de0cc1799b755707e2b65 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/timeutils.py @@ -0,0 +1,566 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's :mod:`datetime` module provides some of the most complex +and powerful primitives in the Python standard library. Time is +nontrivial, but thankfully its support is first-class in +Python. ``dateutils`` provides some additional tools for working with +time. + +Additionally, timeutils provides a few basic utilities for working +with timezones in Python. The Python :mod:`datetime` module's +documentation describes how to create a +:class:`~datetime.datetime`-compatible :class:`~datetime.tzinfo` +subtype. It even provides a few examples. + +The following module defines usable forms of the timezones in those +docs, as well as a couple other useful ones, :data:`UTC` (aka GMT) and +:data:`LocalTZ` (representing the local timezone as configured in the +operating system). For timezones beyond these, as well as a higher +degree of accuracy in corner cases, check out `pytz`_ and `dateutil`_. + +.. _pytz: https://pypi.python.org/pypi/pytz +.. _dateutil: https://dateutil.readthedocs.io/en/stable/index.html +""" + +import re +import time +import bisect +import operator +from datetime import tzinfo, timedelta, date, datetime, timezone + + +# For legacy compatibility. +# boltons used to offer an implementation of total_seconds for Python <2.7 +total_seconds = timedelta.total_seconds + + +def dt_to_timestamp(dt): + """Converts from a :class:`~datetime.datetime` object to an integer + timestamp, suitable interoperation with :func:`time.time` and + other `Epoch-based timestamps`. + + .. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time + + >>> timestamp = int(time.time()) + >>> utc_dt = datetime.fromtimestamp(timestamp, timezone.utc) + >>> timestamp - dt_to_timestamp(utc_dt) + 0.0 + + ``dt_to_timestamp`` supports both timezone-aware and naïve + :class:`~datetime.datetime` objects. Note that it assumes naïve + datetime objects are implied UTC, such as those generated with + :meth:`datetime.datetime.utcnow`. If your datetime objects are + local time, such as those generated with + :meth:`datetime.datetime.now`, first convert it using the + :meth:`datetime.datetime.replace` method with ``tzinfo=`` + :class:`LocalTZ` object in this module, then pass the result of + that to ``dt_to_timestamp``. + """ + if dt.tzinfo: + td = dt - EPOCH_AWARE + else: + td = dt.replace(tzinfo=timezone.utc) - EPOCH_AWARE + return timedelta.total_seconds(td) + + +_NONDIGIT_RE = re.compile(r'\D') + + +def isoparse(iso_str): + """Parses the limited subset of `ISO8601-formatted time`_ strings as + returned by :meth:`datetime.datetime.isoformat`. + + >>> epoch_dt = datetime.fromtimestamp(0, timezone.utc).replace(tzinfo=None) + >>> iso_str = epoch_dt.isoformat() + >>> print(iso_str) + 1970-01-01T00:00:00 + >>> isoparse(iso_str) + datetime.datetime(1970, 1, 1, 0, 0) + + >>> utcnow = datetime.now(timezone.utc).replace(tzinfo=None) + >>> utcnow == isoparse(utcnow.isoformat()) + True + + For further datetime parsing, see the `iso8601`_ package for strict + ISO parsing and `dateutil`_ package for loose parsing and more. + + .. _ISO8601-formatted time: https://en.wikipedia.org/wiki/ISO_8601 + .. _iso8601: https://pypi.python.org/pypi/iso8601 + .. _dateutil: https://pypi.python.org/pypi/python-dateutil + + """ + dt_args = [int(p) for p in _NONDIGIT_RE.split(iso_str)] + return datetime(*dt_args) + + +_BOUNDS = [(0, timedelta(seconds=1), 'second'), + (1, timedelta(seconds=60), 'minute'), + (1, timedelta(seconds=3600), 'hour'), + (1, timedelta(days=1), 'day'), + (1, timedelta(days=7), 'week'), + (2, timedelta(days=30), 'month'), + (1, timedelta(days=365), 'year')] +_BOUNDS = [(b[0] * b[1], b[1], b[2]) for b in _BOUNDS] +_BOUND_DELTAS = [b[0] for b in _BOUNDS] + +_FLOAT_PATTERN = r'[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?' +_PARSE_TD_RE = re.compile(r"((?P%s)\s*(?P\w)\w*)" % _FLOAT_PATTERN) +_PARSE_TD_KW_MAP = {unit[0]: unit + 's' + for _, _, unit in reversed(_BOUNDS[:-2])} + + +def parse_timedelta(text): + """Robustly parses a short text description of a time period into a + :class:`datetime.timedelta`. Supports weeks, days, hours, minutes, + and seconds, with or without decimal points: + + Args: + text (str): Text to parse. + Returns: + datetime.timedelta + Raises: + ValueError: on parse failure. + + >>> parse_td('1d 2h 3.5m 0s') == timedelta(days=1, seconds=7410) + True + + Also supports full words and whitespace. + + >>> parse_td('2 weeks 1 day') == timedelta(days=15) + True + + Negative times are supported, too: + + >>> parse_td('-1.5 weeks 3m 20s') == timedelta(days=-11, seconds=43400) + True + """ + td_kwargs = {} + for match in _PARSE_TD_RE.finditer(text): + value, unit = match.group('value'), match.group('unit') + try: + unit_key = _PARSE_TD_KW_MAP[unit] + except KeyError: + raise ValueError('invalid time unit %r, expected one of %r' + % (unit, _PARSE_TD_KW_MAP.keys())) + try: + value = float(value) + except ValueError: + raise ValueError('invalid time value for unit %r: %r' + % (unit, value)) + td_kwargs[unit_key] = value + return timedelta(**td_kwargs) + + +parse_td = parse_timedelta # legacy alias + + +def _cardinalize_time_unit(unit, value): + # removes dependency on strutils; nice and simple because + # all time units cardinalize normally + if value == 1: + return unit + return unit + 's' + + +def decimal_relative_time(d, other=None, ndigits=0, cardinalize=True): + """Get a tuple representing the relative time difference between two + :class:`~datetime.datetime` objects or one + :class:`~datetime.datetime` and now. + + Args: + d (datetime): The first datetime object. + other (datetime): An optional second datetime object. If + unset, defaults to the current time as determined + :meth:`datetime.utcnow`. + ndigits (int): The number of decimal digits to round to, + defaults to ``0``. + cardinalize (bool): Whether to pluralize the time unit if + appropriate, defaults to ``True``. + Returns: + (float, str): A tuple of the :class:`float` difference and + respective unit of time, pluralized if appropriate and + *cardinalize* is set to ``True``. + + Unlike :func:`relative_time`, this method's return is amenable to + localization into other languages and custom phrasing and + formatting. + + >>> now = datetime.now(timezone.utc).replace(tzinfo=None) + >>> decimal_relative_time(now - timedelta(days=1, seconds=3600), now) + (1.0, 'day') + >>> decimal_relative_time(now - timedelta(seconds=0.002), now, ndigits=5) + (0.002, 'seconds') + >>> decimal_relative_time(now, now - timedelta(days=900), ndigits=1) + (-2.5, 'years') + + """ + if other is None: + other = datetime.now(timezone.utc).replace(tzinfo=None) + diff = other - d + diff_seconds = timedelta.total_seconds(diff) + abs_diff = abs(diff) + b_idx = bisect.bisect(_BOUND_DELTAS, abs_diff) - 1 + bbound, bunit, bname = _BOUNDS[b_idx] + f_diff = diff_seconds / timedelta.total_seconds(bunit) + rounded_diff = round(f_diff, ndigits) + if cardinalize: + return rounded_diff, _cardinalize_time_unit(bname, abs(rounded_diff)) + return rounded_diff, bname + + +def relative_time(d, other=None, ndigits=0): + """Get a string representation of the difference between two + :class:`~datetime.datetime` objects or one + :class:`~datetime.datetime` and the current time. Handles past and + future times. + + Args: + d (datetime): The first datetime object. + other (datetime): An optional second datetime object. If + unset, defaults to the current time as determined + :meth:`datetime.utcnow`. + ndigits (int): The number of decimal digits to round to, + defaults to ``0``. + Returns: + A short English-language string. + + >>> now = datetime.now(timezone.utc).replace(tzinfo=None) + >>> relative_time(now, ndigits=1) + '0 seconds ago' + >>> relative_time(now - timedelta(days=1, seconds=36000), ndigits=1) + '1.4 days ago' + >>> relative_time(now + timedelta(days=7), now, ndigits=1) + '1 week from now' + + """ + drt, unit = decimal_relative_time(d, other, ndigits, cardinalize=True) + phrase = 'ago' + if drt < 0: + phrase = 'from now' + return f'{abs(drt):g} {unit} {phrase}' + + +def strpdate(string, format): + """Parse the date string according to the format in `format`. Returns a + :class:`date` object. Internally, :meth:`datetime.strptime` is used to + parse the string and thus conversion specifiers for time fields (e.g. `%H`) + may be provided; these will be parsed but ignored. + + Args: + string (str): The date string to be parsed. + format (str): The `strptime`_-style date format string. + Returns: + datetime.date + + .. _`strptime`: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior + + >>> strpdate('2016-02-14', '%Y-%m-%d') + datetime.date(2016, 2, 14) + >>> strpdate('26/12 (2015)', '%d/%m (%Y)') + datetime.date(2015, 12, 26) + >>> strpdate('20151231 23:59:59', '%Y%m%d %H:%M:%S') + datetime.date(2015, 12, 31) + >>> strpdate('20160101 00:00:00.001', '%Y%m%d %H:%M:%S.%f') + datetime.date(2016, 1, 1) + """ + whence = datetime.strptime(string, format) + return whence.date() + + +def daterange(start, stop, step=1, inclusive=False): + """In the spirit of :func:`range` and :func:`xrange`, the `daterange` + generator that yields a sequence of :class:`~datetime.date` + objects, starting at *start*, incrementing by *step*, until *stop* + is reached. + + When *inclusive* is True, the final date may be *stop*, **if** + *step* falls evenly on it. By default, *step* is one day. See + details below for many more details. + + Args: + start (datetime.date): The starting date The first value in + the sequence. + stop (datetime.date): The stopping date. By default not + included in return. Can be `None` to yield an infinite + sequence. + step (int): The value to increment *start* by to reach + *stop*. Can be an :class:`int` number of days, a + :class:`datetime.timedelta`, or a :class:`tuple` of integers, + `(year, month, day)`. Positive and negative *step* values + are supported. + inclusive (bool): Whether or not the *stop* date can be + returned. *stop* is only returned when a *step* falls evenly + on it. + + >>> christmas = date(year=2015, month=12, day=25) + >>> boxing_day = date(year=2015, month=12, day=26) + >>> new_year = date(year=2016, month=1, day=1) + >>> for day in daterange(christmas, new_year): + ... print(repr(day)) + datetime.date(2015, 12, 25) + datetime.date(2015, 12, 26) + datetime.date(2015, 12, 27) + datetime.date(2015, 12, 28) + datetime.date(2015, 12, 29) + datetime.date(2015, 12, 30) + datetime.date(2015, 12, 31) + >>> for day in daterange(christmas, boxing_day): + ... print(repr(day)) + datetime.date(2015, 12, 25) + >>> for day in daterange(date(2017, 5, 1), date(2017, 8, 1), + ... step=(0, 1, 0), inclusive=True): + ... print(repr(day)) + datetime.date(2017, 5, 1) + datetime.date(2017, 6, 1) + datetime.date(2017, 7, 1) + datetime.date(2017, 8, 1) + + *Be careful when using stop=None, as this will yield an infinite + sequence of dates.* + """ + if not isinstance(start, date): + raise TypeError("start expected datetime.date instance") + if stop and not isinstance(stop, date): + raise TypeError("stop expected datetime.date instance or None") + try: + y_step, m_step, d_step = step + except TypeError: + y_step, m_step, d_step = 0, 0, step + else: + y_step, m_step = int(y_step), int(m_step) + if isinstance(d_step, int): + d_step = timedelta(days=int(d_step)) + elif isinstance(d_step, timedelta): + pass + else: + raise ValueError('step expected int, timedelta, or tuple' + ' (year, month, day), not: %r' % step) + + m_step += y_step * 12 + + if stop is None: + finished = lambda now, stop: False + elif start <= stop: + finished = operator.gt if inclusive else operator.ge + else: + finished = operator.lt if inclusive else operator.le + now = start + + while not finished(now, stop): + yield now + if m_step: + m_y_step, cur_month = divmod((now.month - 1) + m_step, 12) + now = now.replace(year=now.year + m_y_step, + month=(cur_month + 1)) + now = now + d_step + return + + +# Timezone support (brought in from tzutils) + + +ZERO = timedelta(0) +HOUR = timedelta(hours=1) + + +class ConstantTZInfo(tzinfo): + """ + A :class:`~datetime.tzinfo` subtype whose *offset* remains constant + (no daylight savings). + + Args: + name (str): Name of the timezone. + offset (datetime.timedelta): Offset of the timezone. + """ + def __init__(self, name="ConstantTZ", offset=ZERO): + self.name = name + self.offset = offset + + @property + def utcoffset_hours(self): + return timedelta.total_seconds(self.offset) / (60 * 60) + + def utcoffset(self, dt): + return self.offset + + def tzname(self, dt): + return self.name + + def dst(self, dt): + return ZERO + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}(name={self.name!r}, offset={self.offset!r})' + + +UTC = ConstantTZInfo('UTC') +EPOCH_AWARE = datetime.fromtimestamp(0, UTC) + + +class LocalTZInfo(tzinfo): + """The ``LocalTZInfo`` type takes data available in the time module + about the local timezone and makes a practical + :class:`datetime.tzinfo` to represent the timezone settings of the + operating system. + + For a more in-depth integration with the operating system, check + out `tzlocal`_. It builds on `pytz`_ and implements heuristics for + many versions of major operating systems to provide the official + ``pytz`` tzinfo, instead of the LocalTZ generalization. + + .. _tzlocal: https://pypi.python.org/pypi/tzlocal + .. _pytz: https://pypi.python.org/pypi/pytz + + """ + _std_offset = timedelta(seconds=-time.timezone) + _dst_offset = _std_offset + if time.daylight: + _dst_offset = timedelta(seconds=-time.altzone) + + def is_dst(self, dt): + dt_t = (dt.year, dt.month, dt.day, dt.hour, dt.minute, + dt.second, dt.weekday(), 0, -1) + local_t = time.localtime(time.mktime(dt_t)) + return local_t.tm_isdst > 0 + + def utcoffset(self, dt): + if self.is_dst(dt): + return self._dst_offset + return self._std_offset + + def dst(self, dt): + if self.is_dst(dt): + return self._dst_offset - self._std_offset + return ZERO + + def tzname(self, dt): + return time.tzname[self.is_dst(dt)] + + def __repr__(self): + return '%s()' % self.__class__.__name__ + + +LocalTZ = LocalTZInfo() + + +def _first_sunday_on_or_after(dt): + days_to_go = 6 - dt.weekday() + if days_to_go: + dt += timedelta(days_to_go) + return dt + + +# US DST Rules +# +# This is a simplified (i.e., wrong for a few cases) set of rules for US +# DST start and end times. For a complete and up-to-date set of DST rules +# and timezone definitions, visit the Olson Database (or try pytz): +# http://www.twinsun.com/tz/tz-link.htm +# http://sourceforge.net/projects/pytz/ (might not be up-to-date) +# +# In the US, since 2007, DST starts at 2am (standard time) on the second +# Sunday in March, which is the first Sunday on or after Mar 8. +DSTSTART_2007 = datetime(1, 3, 8, 2) +# and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov. +DSTEND_2007 = datetime(1, 11, 1, 1) +# From 1987 to 2006, DST used to start at 2am (standard time) on the first +# Sunday in April and to end at 2am (DST time; 1am standard time) on the last +# Sunday of October, which is the first Sunday on or after Oct 25. +DSTSTART_1987_2006 = datetime(1, 4, 1, 2) +DSTEND_1987_2006 = datetime(1, 10, 25, 1) +# From 1967 to 1986, DST used to start at 2am (standard time) on the last +# Sunday in April (the one on or after April 24) and to end at 2am (DST time; +# 1am standard time) on the last Sunday of October, which is the first Sunday +# on or after Oct 25. +DSTSTART_1967_1986 = datetime(1, 4, 24, 2) +DSTEND_1967_1986 = DSTEND_1987_2006 + + +class USTimeZone(tzinfo): + """Copied directly from the Python docs, the ``USTimeZone`` is a + :class:`datetime.tzinfo` subtype used to create the + :data:`Eastern`, :data:`Central`, :data:`Mountain`, and + :data:`Pacific` tzinfo types. + """ + def __init__(self, hours, reprname, stdname, dstname): + self.stdoffset = timedelta(hours=hours) + self.reprname = reprname + self.stdname = stdname + self.dstname = dstname + + def __repr__(self): + return self.reprname + + def tzname(self, dt): + if self.dst(dt): + return self.dstname + else: + return self.stdname + + def utcoffset(self, dt): + return self.stdoffset + self.dst(dt) + + def dst(self, dt): + if dt is None or dt.tzinfo is None: + # An exception may be sensible here, in one or both cases. + # It depends on how you want to treat them. The default + # fromutc() implementation (called by the default astimezone() + # implementation) passes a datetime with dt.tzinfo is self. + return ZERO + assert dt.tzinfo is self + + # Find start and end times for US DST. For years before 1967, return + # ZERO for no DST. + if 2006 < dt.year: + dststart, dstend = DSTSTART_2007, DSTEND_2007 + elif 1986 < dt.year < 2007: + dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 + elif 1966 < dt.year < 1987: + dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986 + else: + return ZERO + + start = _first_sunday_on_or_after(dststart.replace(year=dt.year)) + end = _first_sunday_on_or_after(dstend.replace(year=dt.year)) + + # Can't compare naive to aware objects, so strip the timezone + # from dt first. + if start <= dt.replace(tzinfo=None) < end: + return HOUR + else: + return ZERO + + +Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") +Central = USTimeZone(-6, "Central", "CST", "CDT") +Mountain = USTimeZone(-7, "Mountain", "MST", "MDT") +Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") diff --git a/miniconda3/lib/python3.13/site-packages/boltons/typeutils.py b/miniconda3/lib/python3.13/site-packages/boltons/typeutils.py new file mode 100644 index 0000000000000000000000000000000000000000..875e2e2b0412bc7fee0a11726371bac402566ee5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/typeutils.py @@ -0,0 +1,180 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Python's built-in :mod:`functools` module builds several useful +utilities on top of Python's first-class function support. +``typeutils`` attempts to do the same for metaprogramming with types +and instances. +""" +import sys +from collections import deque + +_issubclass = issubclass + + +def make_sentinel(name='_MISSING', var_name=None): + """Creates and returns a new **instance** of a new class, suitable for + usage as a "sentinel", a kind of singleton often used to indicate + a value is missing when ``None`` is a valid input. + + Args: + name (str): Name of the Sentinel + var_name (str): Set this name to the name of the variable in + its respective module enable pickleability. Note: + pickleable sentinels should be global constants at the top + level of their module. + + >>> make_sentinel(var_name='_MISSING') + _MISSING + + The most common use cases here in boltons are as default values + for optional function arguments, partly because of its + less-confusing appearance in automatically generated + documentation. Sentinels also function well as placeholders in queues + and linked lists. + + .. note:: + + By design, additional calls to ``make_sentinel`` with the same + values will not produce equivalent objects. + + >>> make_sentinel('TEST') == make_sentinel('TEST') + False + >>> type(make_sentinel('TEST')) == type(make_sentinel('TEST')) + False + + """ + class Sentinel: + def __init__(self): + self.name = name + self.var_name = var_name + + def __repr__(self): + if self.var_name: + return self.var_name + return f'{self.__class__.__name__}({self.name!r})' + + if var_name: + def __reduce__(self): + return self.var_name + + def __bool__(self): + return False + + def __copy__(self): + return self + + def __deepcopy__(self, _memo): + return self + + if var_name: + frame = sys._getframe(1) + module = frame.f_globals.get('__name__') + if not module or module not in sys.modules: + raise ValueError('Pickleable sentinel objects (with var_name) can only' + ' be created from top-level module scopes') + Sentinel.__module__ = module + + return Sentinel() + + +def issubclass(subclass, baseclass): + """Just like the built-in :func:`issubclass`, this function checks + whether *subclass* is inherited from *baseclass*. Unlike the + built-in function, this ``issubclass`` will simply return + ``False`` if either argument is not suitable (e.g., if *subclass* + is not an instance of :class:`type`), instead of raising + :exc:`TypeError`. + + Args: + subclass (type): The target class to check. + baseclass (type): The base class *subclass* will be checked against. + + >>> class MyObject(object): pass + ... + >>> issubclass(MyObject, object) # always a fun fact + True + >>> issubclass('hi', 'friend') + False + """ + try: + return _issubclass(subclass, baseclass) + except TypeError: + return False + + +def get_all_subclasses(cls): + """Recursively finds and returns a :class:`list` of all types + inherited from *cls*. + + >>> class A(object): + ... pass + ... + >>> class B(A): + ... pass + ... + >>> class C(B): + ... pass + ... + >>> class D(A): + ... pass + ... + >>> [t.__name__ for t in get_all_subclasses(A)] + ['B', 'D', 'C'] + >>> [t.__name__ for t in get_all_subclasses(B)] + ['C'] + + """ + try: + to_check = deque(cls.__subclasses__()) + except (AttributeError, TypeError): + raise TypeError('expected type object, not %r' % cls) + seen, ret = set(), [] + while to_check: + cur = to_check.popleft() + if cur in seen: + continue + ret.append(cur) + seen.add(cur) + to_check.extend(cur.__subclasses__()) + return ret + + +class classproperty: + """Much like a :class:`property`, but the wrapped get function is a + class method. For simplicity, only read-only properties are + implemented. + """ + + def __init__(self, fn): + self.fn = fn + + def __get__(self, instance, cls): + return self.fn(cls) diff --git a/miniconda3/lib/python3.13/site-packages/boltons/urlutils.py b/miniconda3/lib/python3.13/site-packages/boltons/urlutils.py new file mode 100644 index 0000000000000000000000000000000000000000..45d3e73e87820a34a622540cdf1a29cb34b895c3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/boltons/urlutils.py @@ -0,0 +1,1606 @@ +# Copyright (c) 2013, Mahmoud Hashemi +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * 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. +# +# * The names of the contributors may not 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 NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""":mod:`urlutils` is a module dedicated to one of software's most +versatile, well-aged, and beloved data structures: the URL, also known +as the `Uniform Resource Locator`_. + +Among other things, this module is a full reimplementation of URLs, +without any reliance on the :mod:`urlparse` or :mod:`urllib` standard +library modules. The centerpiece and top-level interface of urlutils +is the :class:`URL` type. Also featured is the :func:`find_all_links` +convenience function. Some low-level functions and constants are also +below. + +The implementations in this module are based heavily on `RFC 3986`_ and +`RFC 3987`_, and incorporates details from several other RFCs and `W3C +documents`_. + +.. _Uniform Resource Locator: https://en.wikipedia.org/wiki/Uniform_Resource_Locator +.. _RFC 3986: https://tools.ietf.org/html/rfc3986 +.. _RFC 3987: https://tools.ietf.org/html/rfc3987 +.. _W3C documents: https://www.w3.org/TR/uri-clarification/ + +""" + +import re +import socket +import string +from unicodedata import normalize + +# The unreserved URI characters (per RFC 3986 Section 2.3) +_UNRESERVED_CHARS = frozenset('~-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz') + +# URL parsing regex (based on RFC 3986 Appendix B, with modifications) +_URL_RE = re.compile(r'^((?P[^:/?#]+):)?' + r'((?P<_netloc_sep>//)(?P[^/?#]*))?' + r'(?P[^?#]*)' + r'(\?(?P[^#]*))?' + r'(#(?P.*))?') + + +_HEX_CHAR_MAP = {(a + b).encode('ascii'): + chr(int(a + b, 16)).encode('charmap') + for a in string.hexdigits for b in string.hexdigits} +_ASCII_RE = re.compile('([\x00-\x7f]+)') + + +# This port list painstakingly curated by hand searching through +# https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml +# and +# https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml +SCHEME_PORT_MAP = {'acap': 674, 'afp': 548, 'dict': 2628, 'dns': 53, + 'file': None, 'ftp': 21, 'git': 9418, 'gopher': 70, + 'http': 80, 'https': 443, 'imap': 143, 'ipp': 631, + 'ipps': 631, 'irc': 194, 'ircs': 6697, 'ldap': 389, + 'ldaps': 636, 'mms': 1755, 'msrp': 2855, 'msrps': None, + 'mtqp': 1038, 'nfs': 111, 'nntp': 119, 'nntps': 563, + 'pop': 110, 'prospero': 1525, 'redis': 6379, 'rsync': 873, + 'rtsp': 554, 'rtsps': 322, 'rtspu': 5005, 'sftp': 22, + 'smb': 445, 'snmp': 161, 'ssh': 22, 'steam': None, + 'svn': 3690, 'telnet': 23, 'ventrilo': 3784, 'vnc': 5900, + 'wais': 210, 'ws': 80, 'wss': 443, 'xmpp': None} + +# This list of schemes that don't use authorities is also from the link above. +NO_NETLOC_SCHEMES = {'urn', 'about', 'bitcoin', 'blob', 'data', 'geo', + 'magnet', 'mailto', 'news', 'pkcs11', + 'sip', 'sips', 'tel'} +# As of Mar 11, 2017, there were 44 netloc schemes, and 13 non-netloc + +# RFC 3986 section 2.2, Reserved Characters +_GEN_DELIMS = frozenset(':/?#[]@') +_SUB_DELIMS = frozenset("!$&'()*+,;=") +_ALL_DELIMS = _GEN_DELIMS | _SUB_DELIMS + +_USERINFO_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS +_USERINFO_DELIMS = _ALL_DELIMS - _USERINFO_SAFE +_PATH_SAFE = _UNRESERVED_CHARS | _SUB_DELIMS | set(':@') +_PATH_DELIMS = _ALL_DELIMS - _PATH_SAFE +_FRAGMENT_SAFE = _UNRESERVED_CHARS | _PATH_SAFE | set('/?') +_FRAGMENT_DELIMS = _ALL_DELIMS - _FRAGMENT_SAFE +_QUERY_SAFE = _UNRESERVED_CHARS | _FRAGMENT_SAFE - set('&=+') +_QUERY_DELIMS = _ALL_DELIMS - _QUERY_SAFE + + +class URLParseError(ValueError): + """Exception inheriting from :exc:`ValueError`, raised when failing to + parse a URL. Mostly raised on invalid ports and IPv6 addresses. + """ + pass + + +DEFAULT_ENCODING = 'utf8' + + +def to_unicode(obj): + try: + return str(obj) + except UnicodeDecodeError: + return str(obj, encoding=DEFAULT_ENCODING) + + +# regex from gruber via tornado +# doesn't support ipv6 +# doesn't support mailto (netloc-less schemes) +_FIND_ALL_URL_RE = re.compile(r"""\b((?:([\w-]+):(/{1,3})|www[.])(?:(?:(?:[^\s&()<>]|&|")*(?:[^!"#$%'()*+,.:;<=>?@\[\]^`{|}~\s]))|(?:\((?:[^\s&()]|&|")*\)))+)""") + + +def find_all_links(text, with_text=False, default_scheme='https', schemes=()): + """This function uses heuristics to searches plain text for strings + that look like URLs, returning a :class:`list` of :class:`URL` + objects. It supports limiting the accepted schemes, and returning + interleaved text as well. + + >>> find_all_links('Visit https://boltons.rtfd.org!') + [URL(u'https://boltons.rtfd.org')] + >>> find_all_links('Visit https://boltons.rtfd.org!', with_text=True) + [u'Visit ', URL(u'https://boltons.rtfd.org'), u'!'] + + Args: + text (str): The text to search. + + with_text (bool): Whether or not to interleave plaintext blocks + with the returned URL objects. Having all tokens can be + useful for transforming the text, e.g., replacing links with + HTML equivalents. Defaults to ``False``. + + default_scheme (str): Many URLs are written without the scheme + component. This function can match a reasonable subset of + those, provided *default_scheme* is set to a string. Set to + ``False`` to disable matching scheme-less URLs. Defaults to + ``'https'``. + + schemes (list): A list of strings that a URL's scheme must + match in order to be included in the results. Defaults to + empty, which matches all schemes. + + .. note:: Currently this function does not support finding IPv6 + addresses or URLs with netloc-less schemes, like mailto. + + """ + text = to_unicode(text) + prev_end, start, end = 0, None, None + ret = [] + _add = ret.append + + def _add_text(t): + if ret and isinstance(ret[-1], str): + ret[-1] += t + else: + _add(t) + + for match in _FIND_ALL_URL_RE.finditer(text): + start, end = match.start(1), match.end(1) + if prev_end < start and with_text: + _add(text[prev_end:start]) + prev_end = end + try: + cur_url_text = match.group(0) + cur_url = URL(cur_url_text) + if not cur_url.scheme: + if default_scheme: + cur_url = URL(default_scheme + '://' + cur_url_text) + else: + _add_text(text[start:end]) + continue + if schemes and cur_url.scheme not in schemes: + _add_text(text[start:end]) + else: + _add(cur_url) + except URLParseError: + # currently this should only be hit with broken port + # strings. the regex above doesn't support ipv6 addresses + if with_text: + _add_text(text[start:end]) + + if with_text: + tail = text[prev_end:] + if tail: + _add_text(tail) + + return ret + + +def _make_quote_map(safe_chars): + ret = {} + # v is included in the dict for py3 mostly, because bytestrings + # are iterables of ints, of course! + for i, v in zip(range(256), range(256)): + c = chr(v) + if c in safe_chars: + ret[c] = ret[v] = c + else: + ret[c] = ret[v] = f'%{i:02X}' + return ret + + +_USERINFO_PART_QUOTE_MAP = _make_quote_map(_USERINFO_SAFE) +_PATH_PART_QUOTE_MAP = _make_quote_map(_PATH_SAFE) +_QUERY_PART_QUOTE_MAP = _make_quote_map(_QUERY_SAFE) +_FRAGMENT_QUOTE_MAP = _make_quote_map(_FRAGMENT_SAFE) + + +def quote_path_part(text, full_quote=True): + """ + Percent-encode a single segment of a URL path. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_PATH_PART_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_PATH_PART_QUOTE_MAP[t] if t in _PATH_DELIMS else t + for t in text]) + + +def quote_query_part(text, full_quote=True): + """ + Percent-encode a single query string key or value. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_QUERY_PART_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_QUERY_PART_QUOTE_MAP[t] if t in _QUERY_DELIMS else t + for t in text]) + + +def quote_fragment_part(text, full_quote=True): + """Quote the fragment part of the URL. Fragments don't have + subdelimiters, so the whole URL fragment can be passed. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_FRAGMENT_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_FRAGMENT_QUOTE_MAP[t] if t in _FRAGMENT_DELIMS else t + for t in text]) + + +def quote_userinfo_part(text, full_quote=True): + """Quote special characters in either the username or password + section of the URL. Note that userinfo in URLs is considered + deprecated in many circles (especially browsers), and support for + percent-encoded userinfo can be spotty. + """ + if full_quote: + bytestr = normalize('NFC', to_unicode(text)).encode('utf8') + return ''.join([_USERINFO_PART_QUOTE_MAP[b] for b in bytestr]) + return ''.join([_USERINFO_PART_QUOTE_MAP[t] if t in _USERINFO_DELIMS + else t for t in text]) + + +def unquote(string, encoding='utf-8', errors='replace'): + """Percent-decode a string, by replacing %xx escapes with their + single-character equivalent. The optional *encoding* and *errors* + parameters specify how to decode percent-encoded sequences into + Unicode characters, as accepted by the :meth:`bytes.decode()` method. By + default, percent-encoded sequences are decoded with UTF-8, and + invalid sequences are replaced by a placeholder character. + + >>> unquote(u'abc%20def') + u'abc def' + """ + if '%' not in string: + string.split + return string + if encoding is None: + encoding = 'utf-8' + if errors is None: + errors = 'replace' + bits = _ASCII_RE.split(string) + res = [bits[0]] + append = res.append + for i in range(1, len(bits), 2): + append(unquote_to_bytes(bits[i]).decode(encoding, errors)) + append(bits[i + 1]) + return ''.join(res) + + +def unquote_to_bytes(string): + """unquote_to_bytes('abc%20def') -> b'abc def'.""" + # Note: strings are encoded as UTF-8. This is only an issue if it contains + # unescaped non-ASCII characters, which URIs should not. + if not string: + # Is it a string-like object? + string.split + return b'' + if isinstance(string, str): + string = string.encode('utf-8') + bits = string.split(b'%') + if len(bits) == 1: + return string + # import pdb;pdb.set_trace() + res = [bits[0]] + append = res.append + + for item in bits[1:]: + try: + append(_HEX_CHAR_MAP[item[:2]]) + append(item[2:]) + except KeyError: + append(b'%') + append(item) + return b''.join(res) + + +def register_scheme(text, uses_netloc=None, default_port=None): + """Registers new scheme information, resulting in correct port and + slash behavior from the URL object. There are dozens of standard + schemes preregistered, so this function is mostly meant for + proprietary internal customizations or stopgaps on missing + standards information. If a scheme seems to be missing, please + `file an issue`_! + + Args: + text (str): Text representing the scheme. + (the 'http' in 'http://hatnote.com') + uses_netloc (bool): Does the scheme support specifying a + network host? For instance, "http" does, "mailto" does not. + default_port (int): The default port, if any, for netloc-using + schemes. + + .. _file an issue: https://github.com/mahmoud/boltons/issues + """ + text = text.lower() + if default_port is not None: + try: + default_port = int(default_port) + except ValueError: + raise ValueError('default_port expected integer or None, not %r' + % (default_port,)) + + if uses_netloc is True: + SCHEME_PORT_MAP[text] = default_port + elif uses_netloc is False: + if default_port is not None: + raise ValueError('unexpected default port while specifying' + ' non-netloc scheme: %r' % default_port) + NO_NETLOC_SCHEMES.add(text) + elif uses_netloc is not None: + raise ValueError('uses_netloc expected True, False, or None') + + return + + +def resolve_path_parts(path_parts): + """Normalize the URL path by resolving segments of '.' and '..', + resulting in a dot-free path. See RFC 3986 section 5.2.4, Remove + Dot Segments. + """ + # TODO: what to do with multiple slashes + ret = [] + + for part in path_parts: + if part == '.': + pass + elif part == '..': + if ret and (len(ret) > 1 or ret[0]): # prevent unrooting + ret.pop() + else: + ret.append(part) + + if list(path_parts[-1:]) in (['.'], ['..']): + ret.append('') + + return ret + + +class cachedproperty: + """The ``cachedproperty`` is used similar to :class:`property`, except + that the wrapped method is only called once. This is commonly used + to implement lazy attributes. + + After the property has been accessed, the value is stored on the + instance itself, using the same name as the cachedproperty. This + allows the cache to be cleared with :func:`delattr`, or through + manipulating the object's ``__dict__``. + """ + def __init__(self, func): + self.__doc__ = getattr(func, '__doc__') + self.func = func + + def __get__(self, obj, objtype=None): + if obj is None: + return self + value = obj.__dict__[self.func.__name__] = self.func(obj) + return value + + def __repr__(self): + cn = self.__class__.__name__ + return f'<{cn} func={self.func}>' + + +class URL: + r"""The URL is one of the most ubiquitous data structures in the + virtual and physical landscape. From blogs to billboards, URLs are + so common, that it's easy to overlook their complexity and + power. + + There are 8 parts of a URL, each with its own semantics and + special characters: + + * :attr:`~URL.scheme` + * :attr:`~URL.username` + * :attr:`~URL.password` + * :attr:`~URL.host` + * :attr:`~URL.port` + * :attr:`~URL.path` + * :attr:`~URL.query_params` (query string parameters) + * :attr:`~URL.fragment` + + Each is exposed as an attribute on the URL object. RFC 3986 offers + this brief structural summary of the main URL components:: + + foo://user:pass@example.com:8042/over/there?name=ferret#nose + \_/ \_______/ \_________/ \__/\_________/ \_________/ \__/ + | | | | | | | + scheme userinfo host port path query fragment + + And here's how that example can be manipulated with the URL type: + + >>> url = URL('foo://example.com:8042/over/there?name=ferret#nose') + >>> print(url.host) + example.com + >>> print(url.get_authority()) + example.com:8042 + >>> print(url.qp['name']) # qp is a synonym for query_params + ferret + + URL's approach to encoding is that inputs are decoded as much as + possible, and data remains in this decoded state until re-encoded + using the :meth:`~URL.to_text()` method. In this way, it's similar + to Python's current approach of encouraging immediate decoding of + bytes to text. + + Note that URL instances are mutable objects. If an immutable + representation of the URL is desired, the string from + :meth:`~URL.to_text()` may be used. For an immutable, but + almost-as-featureful, URL object, check out the `hyperlink + package`_. + + .. _hyperlink package: https://github.com/mahmoud/hyperlink + + """ + + # public attributes (for comparison, see __eq__): + _cmp_attrs = ('scheme', 'uses_netloc', 'username', 'password', + 'family', 'host', 'port', 'path', 'query_params', 'fragment') + + def __init__(self, url=''): + # TODO: encoding param. The encoding that underlies the + # percent-encoding is always utf8 for IRIs, but can be Latin-1 + # for other usage schemes. + ud = DEFAULT_PARSED_URL + if url: + if isinstance(url, URL): + url = url.to_text() # better way to copy URLs? + elif isinstance(url, bytes): + try: + url = url.decode(DEFAULT_ENCODING) + except UnicodeDecodeError as ude: + raise URLParseError('expected text or %s-encoded bytes.' + ' try decoding the url bytes and' + ' passing the result. (got: %s)' + % (DEFAULT_ENCODING, ude)) + ud = parse_url(url) + + _e = '' + self.scheme = ud['scheme'] or _e + self._netloc_sep = ud['_netloc_sep'] or _e + self.username = (unquote(ud['username']) + if '%' in (ud['username'] or _e) else ud['username'] or _e) + self.password = (unquote(ud['password']) + if '%' in (ud['password'] or _e) else ud['password'] or _e) + self.family = ud['family'] + + if not ud['host']: + self.host = _e + else: + try: + self.host = ud['host'].encode("ascii") + except UnicodeEncodeError: + self.host = ud['host'] # already non-ascii text + else: + self.host = self.host.decode("idna") + + self.port = ud['port'] + self.path_parts = tuple([unquote(p) if '%' in p else p for p + in (ud['path'] or _e).split('/')]) + self._query = ud['query'] or _e + self.fragment = (unquote(ud['fragment']) + if '%' in (ud['fragment'] or _e) else ud['fragment'] or _e) + # TODO: possibly use None as marker for empty vs missing + return + + @classmethod + def from_parts(cls, scheme=None, host=None, path_parts=(), query_params=(), + fragment='', port=None, username=None, password=None): + """Build a new URL from parts. Note that the respective arguments are + not in the order they would appear in a URL: + + Args: + scheme (str): The scheme of a URL, e.g., 'http' + host (str): The host string, e.g., 'hatnote.com' + path_parts (tuple): The individual text segments of the + path, e.g., ('post', '123') + query_params (dict): An OMD, dict, or list of (key, value) + pairs representing the keys and values of the URL's query + parameters. + fragment (str): The fragment of the URL, e.g., 'anchor1' + port (int): The integer port of URL, automatic defaults are + available for registered schemes. + username (str): The username for the userinfo part of the URL. + password (str): The password for the userinfo part of the URL. + + Note that this method does relatively little + validation. :meth:`URL.to_text()` should be used to check if + any errors are produced while composing the final textual URL. + """ + ret = cls() + + ret.scheme = scheme + ret.host = host + ret.path_parts = tuple(path_parts) or ('',) + ret.query_params.update(query_params) + ret.fragment = fragment + ret.port = port + ret.username = username + ret.password = password + + return ret + + @cachedproperty + def query_params(self): + """The parsed form of the query string of the URL, represented as a + :class:`~dictutils.OrderedMultiDict`. Also available as the + handy alias ``qp``. + + >>> url = URL('http://boltons.readthedocs.io/?utm_source=doctest&python=great') + >>> url.qp.keys() + [u'utm_source', u'python'] + """ + return QueryParamDict.from_text(self._query) + + qp = query_params + + @property + def path(self): + "The URL's path, in text form." + return '/'.join([quote_path_part(p, full_quote=False) + for p in self.path_parts]) + + @path.setter + def path(self, path_text): + self.path_parts = tuple([unquote(p) if '%' in p else p + for p in to_unicode(path_text).split('/')]) + return + + @property + def uses_netloc(self): + """Whether or not a URL uses :code:`:` or :code:`://` to separate the + scheme from the rest of the URL depends on the scheme's own + standard definition. There is no way to infer this behavior + from other parts of the URL. A scheme either supports network + locations or it does not. + + The URL type's approach to this is to check for explicitly + registered schemes, with common schemes like HTTP + preregistered. This is the same approach taken by + :mod:`urlparse`. + + URL adds two additional heuristics if the scheme as a whole is + not registered. First, it attempts to check the subpart of the + scheme after the last ``+`` character. This adds intuitive + behavior for schemes like ``git+ssh``. Second, if a URL with + an unrecognized scheme is loaded, it will maintain the + separator it sees. + + >>> print(URL('fakescheme://test.com').to_text()) + fakescheme://test.com + >>> print(URL('mockscheme:hello:world').to_text()) + mockscheme:hello:world + + """ + default = self._netloc_sep + if self.scheme in SCHEME_PORT_MAP: + return True + if self.scheme in NO_NETLOC_SCHEMES: + return False + if self.scheme.split('+')[-1] in SCHEME_PORT_MAP: + return True + return default + + @property + def default_port(self): + """Return the default port for the currently-set scheme. Returns + ``None`` if the scheme is unrecognized. See + :func:`register_scheme` above. If :attr:`~URL.port` matches + this value, no port is emitted in the output of + :meth:`~URL.to_text()`. + + Applies the same '+' heuristic detailed in :meth:`URL.uses_netloc`. + """ + try: + return SCHEME_PORT_MAP[self.scheme] + except KeyError: + return SCHEME_PORT_MAP.get(self.scheme.split('+')[-1]) + + def normalize(self, with_case=True): + """Resolve any "." and ".." references in the path, as well as + normalize scheme and host casing. To turn off case + normalization, pass ``with_case=False``. + + More information can be found in `Section 6.2.2 of RFC 3986`_. + + .. _Section 6.2.2 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-6.2.2 + """ + self.path_parts = resolve_path_parts(self.path_parts) + + if with_case: + self.scheme = self.scheme.lower() + self.host = self.host.lower() + return + + def navigate(self, dest): + """Factory method that returns a _new_ :class:`URL` based on a given + destination, *dest*. Useful for navigating those relative + links with ease. + + The newly created :class:`URL` is normalized before being returned. + + >>> url = URL('http://boltons.readthedocs.io') + >>> url.navigate('en/latest/') + URL(u'http://boltons.readthedocs.io/en/latest/') + + Args: + dest (str): A string or URL object representing the destination + + More information can be found in `Section 5 of RFC 3986`_. + + .. _Section 5 of RFC 3986: https://tools.ietf.org/html/rfc3986#section-5 + """ + orig_dest = None + if not isinstance(dest, URL): + dest, orig_dest = URL(dest), dest + if dest.scheme and dest.host: + # absolute URLs replace everything, but don't make an + # extra copy if we don't have to + return URL(dest) if orig_dest is None else dest + query_params = dest.query_params + + if dest.path: + if dest.path.startswith('/'): # absolute path + new_path_parts = list(dest.path_parts) + else: # relative path + new_path_parts = list(self.path_parts[:-1]) \ + + list(dest.path_parts) + else: + new_path_parts = list(self.path_parts) + if not query_params: + query_params = self.query_params + + ret = self.from_parts(scheme=dest.scheme or self.scheme, + host=dest.host or self.host, + port=dest.port or self.port, + path_parts=new_path_parts, + query_params=query_params, + fragment=dest.fragment, + username=dest.username or self.username, + password=dest.password or self.password) + ret.normalize() + return ret + + def get_authority(self, full_quote=False, with_userinfo=False): + """Used by URL schemes that have a network location, + :meth:`~URL.get_authority` combines :attr:`username`, + :attr:`password`, :attr:`host`, and :attr:`port` into one + string, the *authority*, that is used for + connecting to a network-accessible resource. + + Used internally by :meth:`~URL.to_text()` and can be useful + for labeling connections. + + >>> url = URL('ftp://user@ftp.debian.org:2121/debian/README') + >>> print(url.get_authority()) + ftp.debian.org:2121 + >>> print(url.get_authority(with_userinfo=True)) + user@ftp.debian.org:2121 + + Args: + full_quote (bool): Whether or not to apply IDNA encoding. + Defaults to ``False``. + with_userinfo (bool): Whether or not to include username + and password, technically part of the + authority. Defaults to ``False``. + + """ + parts = [] + _add = parts.append + if self.username and with_userinfo: + _add(quote_userinfo_part(self.username)) + if self.password: + _add(':') + _add(quote_userinfo_part(self.password)) + _add('@') + if self.host: + if self.family == socket.AF_INET6: + _add('[') + _add(self.host) + _add(']') + elif full_quote: + _add(self.host.encode('idna').decode('ascii')) + else: + _add(self.host) + # TODO: 0 port? + if self.port and self.port != self.default_port: + _add(':') + _add(str(self.port)) + return ''.join(parts) + + def to_text(self, full_quote=False): + """Render a string representing the current state of the URL + object. + + >>> url = URL('http://listen.hatnote.com') + >>> url.fragment = 'en' + >>> print(url.to_text()) + http://listen.hatnote.com#en + + By setting the *full_quote* flag, the URL can either be fully + quoted or minimally quoted. The most common characteristic of + an encoded-URL is the presence of percent-encoded text (e.g., + %60). Unquoted URLs are more readable and suitable + for display, whereas fully-quoted URLs are more conservative + and generally necessary for sending over the network. + """ + scheme = self.scheme + path = '/'.join([quote_path_part(p, full_quote=full_quote) + for p in self.path_parts]) + authority = self.get_authority(full_quote=full_quote, + with_userinfo=True) + query_string = self.query_params.to_text(full_quote=full_quote) + fragment = quote_fragment_part(self.fragment, full_quote=full_quote) + + parts = [] + _add = parts.append + if scheme: + _add(scheme) + _add(':') + if authority: + _add('//') + _add(authority) + elif (scheme and path[:2] != '//' and self.uses_netloc): + _add('//') + if path: + if scheme and authority and path[:1] != '/': + _add('/') + # TODO: i think this is here because relative paths + # with absolute authorities = undefined + _add(path) + if query_string: + _add('?') + _add(query_string) + if fragment: + _add('#') + _add(fragment) + return ''.join(parts) + + def __repr__(self): + cn = self.__class__.__name__ + return f'{cn}({self.to_text()!r})' + + def __str__(self): + return self.to_text() + + def __unicode__(self): + return self.to_text() + + def __eq__(self, other): + for attr in self._cmp_attrs: + if not getattr(self, attr) == getattr(other, attr, None): + return False + return True + + def __ne__(self, other): + return not self == other + + +try: + from socket import inet_pton +except ImportError: + # from https://gist.github.com/nnemkin/4966028 + import ctypes + + class _sockaddr(ctypes.Structure): + _fields_ = [("sa_family", ctypes.c_short), + ("__pad1", ctypes.c_ushort), + ("ipv4_addr", ctypes.c_byte * 4), + ("ipv6_addr", ctypes.c_byte * 16), + ("__pad2", ctypes.c_ulong)] + + WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA + WSAAddressToStringA = ctypes.windll.ws2_32.WSAAddressToStringA + + def inet_pton(address_family, ip_string): + addr = _sockaddr() + ip_string = ip_string.encode('ascii') + addr.sa_family = address_family + addr_size = ctypes.c_int(ctypes.sizeof(addr)) + + if WSAStringToAddressA(ip_string, address_family, None, ctypes.byref(addr), ctypes.byref(addr_size)) != 0: + raise OSError(ctypes.FormatError()) + + if address_family == socket.AF_INET: + return ctypes.string_at(addr.ipv4_addr, 4) + if address_family == socket.AF_INET6: + return ctypes.string_at(addr.ipv6_addr, 16) + raise OSError('unknown address family') + + +def parse_host(host): + """\ + Low-level function used to parse the host portion of a URL. + + Returns a tuple of (family, host) where *family* is a + :mod:`socket` module constant or ``None``, and host is a string. + + >>> parse_host('googlewebsite.com') == (None, 'googlewebsite.com') + True + >>> parse_host('[::1]') == (socket.AF_INET6, '::1') + True + >>> parse_host('192.168.1.1') == (socket.AF_INET, '192.168.1.1') + True + + Odd doctest formatting above due to py3's switch from int to enums + for :mod:`socket` constants. + + """ + if not host: + return None, '' + if ':' in host and '[' == host[0] and ']' == host[-1]: + host = host[1:-1] + try: + inet_pton(socket.AF_INET6, host) + except OSError as se: + raise URLParseError(f'invalid IPv6 host: {host!r} ({se!r})') + except UnicodeEncodeError: + pass # TODO: this can't be a real host right? + else: + family = socket.AF_INET6 + return family, host + try: + inet_pton(socket.AF_INET, host) + except (OSError, UnicodeEncodeError): + family = None # not an IP + else: + family = socket.AF_INET + return family, host + + +def parse_url(url_text): + """\ + Used to parse the text for a single URL into a dictionary, used + internally by the :class:`URL` type. + + Note that "URL" has a very narrow, standards-based + definition. While :func:`parse_url` may raise + :class:`URLParseError` under a very limited number of conditions, + such as non-integer port, a surprising number of strings are + technically valid URLs. For instance, the text ``"url"`` is a + valid URL, because it is a relative path. + + In short, do not expect this function to validate form inputs or + other more colloquial usages of URLs. + + >>> res = parse_url('http://127.0.0.1:3000/?a=1') + >>> sorted(res.keys()) # res is a basic dictionary + ['_netloc_sep', 'authority', 'family', 'fragment', 'host', 'password', 'path', 'port', 'query', 'scheme', 'username'] + """ + url_text = str(url_text) + # raise TypeError('parse_url expected text, not %r' % url_str) + um = _URL_RE.match(url_text) + try: + gs = um.groupdict() + except AttributeError: + raise URLParseError('could not parse url: %r' % url_text) + + au_text = gs['authority'] + user, pw, hostinfo = None, None, au_text + + if au_text: + userinfo, sep, hostinfo = au_text.rpartition('@') + if sep: + # TODO: empty userinfo error? + user, _, pw = userinfo.partition(':') + + host, port = None, None + if hostinfo: + host, sep, port_str = hostinfo.partition(':') + if sep: + if host and host[0] == '[' and ']' in port_str: + host_right, _, port_str = port_str.partition(']') + host = host + ':' + host_right + ']' + if port_str and port_str[0] == ':': + port_str = port_str[1:] + + try: + port = int(port_str) + except ValueError: + if port_str: # empty ports ok according to RFC 3986 6.2.3 + raise URLParseError('expected integer for port, not %r' + % port_str) + port = None + + family, host = parse_host(host) + + gs['username'] = user + gs['password'] = pw + gs['family'] = family + gs['host'] = host + gs['port'] = port + return gs + + +DEFAULT_PARSED_URL = parse_url('') + + +def parse_qsl(qs, keep_blank_values=True, encoding=DEFAULT_ENCODING): + """ + Converts a query string into a list of (key, value) pairs. + """ + pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')] + ret = [] + for pair in pairs: + if not pair: + continue + key, _, value = pair.partition('=') + if not value: + if keep_blank_values: + value = None + else: + continue + key = unquote(key.replace('+', ' ')) + if value: + value = unquote(value.replace('+', ' ')) + ret.append((key, value)) + return ret + + +""" +# What follows is the OrderedMultiDict from dictutils.py, circa +# 20161021, used for the QueryParamDict, toward the bottom. +""" + +from collections.abc import KeysView, ValuesView, ItemsView +from itertools import zip_longest + +try: + from .typeutils import make_sentinel + _MISSING = make_sentinel(var_name='_MISSING') +except ImportError: + _MISSING = object() + + +PREV, NEXT, KEY, VALUE, SPREV, SNEXT = range(6) + + +class OrderedMultiDict(dict): + """A MultiDict is a dictionary that can have multiple values per key + and the OrderedMultiDict (OMD) is a MultiDict that retains + original insertion order. Common use cases include: + + * handling query strings parsed from URLs + * inverting a dictionary to create a reverse index (values to keys) + * stacking data from multiple dictionaries in a non-destructive way + + The OrderedMultiDict constructor is identical to the built-in + :class:`dict`, and overall the API constitutes an intuitive + superset of the built-in type: + + >>> omd = OrderedMultiDict() + >>> omd['a'] = 1 + >>> omd['b'] = 2 + >>> omd.add('a', 3) + >>> omd.get('a') + 3 + >>> omd.getlist('a') + [1, 3] + + Some non-:class:`dict`-like behaviors also make an appearance, + such as support for :func:`reversed`: + + >>> list(reversed(omd)) + ['b', 'a'] + + Note that unlike some other MultiDicts, this OMD gives precedence + to the most recent value added. ``omd['a']`` refers to ``3``, not + ``1``. + + >>> omd + OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> omd.poplast('a') + 3 + >>> omd + OrderedMultiDict([('a', 1), ('b', 2)]) + >>> omd.pop('a') + 1 + >>> omd + OrderedMultiDict([('b', 2)]) + + If you want a safe-to-modify or flat dictionary, use + :meth:`OrderedMultiDict.todict()`. + + >>> from pprint import pprint as pp # preserve printed ordering + >>> omd = OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]) + >>> pp(omd.todict()) + {'a': 3, 'b': 2} + >>> pp(omd.todict(multi=True)) + {'a': [1, 3], 'b': [2]} + + With ``multi=False``, items appear with the keys in to original + insertion order, alongside the most-recently inserted value for + that key. + + >>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False) + [('a', 3), ('b', 2)] + + .. warning:: + + ``dict(omd)`` changed behavior `in Python 3.7 + `_ due to changes made to + support the transition from :class:`collections.OrderedDict` to + the built-in dictionary being ordered. Before 3.7, the result + would be a new dictionary, with values that were lists, similar + to ``omd.todict(multi=True)`` (but only shallow-copy; the lists + were direct references to OMD internal structures). From 3.7 + onward, the values became singular, like + ``omd.todict(multi=False)``. For reliable cross-version + behavior, just use :meth:`~OrderedMultiDict.todict()`. + + """ + def __new__(cls, *a, **kw): + ret = super().__new__(cls) + ret._clear_ll() + return ret + + def __init__(self, *args, **kwargs): + if len(args) > 1: + raise TypeError('%s expected at most 1 argument, got %s' + % (self.__class__.__name__, len(args))) + super().__init__() + + if args: + self.update_extend(args[0]) + if kwargs: + self.update(kwargs) + + def __getstate__(self): + return list(self.iteritems(multi=True)) + + def __setstate__(self, state): + self.clear() + self.update_extend(state) + + def _clear_ll(self): + try: + _map = self._map + except AttributeError: + _map = self._map = {} + self.root = [] + _map.clear() + self.root[:] = [self.root, self.root, None] + + def _insert(self, k, v): + root = self.root + cells = self._map.setdefault(k, []) + last = root[PREV] + cell = [last, root, k, v] + last[NEXT] = root[PREV] = cell + cells.append(cell) + + def add(self, k, v): + """Add a single value *v* under a key *k*. Existing values under *k* + are preserved. + """ + values = super().setdefault(k, []) + self._insert(k, v) + values.append(v) + + def addlist(self, k, v): + """Add an iterable of values underneath a specific key, preserving + any values already under that key. + + >>> omd = OrderedMultiDict([('a', -1)]) + >>> omd.addlist('a', range(3)) + >>> omd + OrderedMultiDict([('a', -1), ('a', 0), ('a', 1), ('a', 2)]) + + Called ``addlist`` for consistency with :meth:`getlist`, but + tuples and other sequences and iterables work. + """ + if not v: + return + self_insert = self._insert + values = super().setdefault(k, []) + for subv in v: + self_insert(k, subv) + values.extend(v) + + def get(self, k, default=None): + """Return the value for key *k* if present in the dictionary, else + *default*. If *default* is not given, ``None`` is returned. + This method never raises a :exc:`KeyError`. + + To get all values under a key, use :meth:`OrderedMultiDict.getlist`. + """ + return super().get(k, [default])[-1] + + def getlist(self, k, default=_MISSING): + """Get all values for key *k* as a list, if *k* is in the + dictionary, else *default*. The list returned is a copy and + can be safely mutated. If *default* is not given, an empty + :class:`list` is returned. + """ + try: + return super().__getitem__(k)[:] + except KeyError: + if default is _MISSING: + return [] + return default + + def clear(self): + "Empty the dictionary." + super().clear() + self._clear_ll() + + def setdefault(self, k, default=_MISSING): + """If key *k* is in the dictionary, return its value. If not, insert + *k* with a value of *default* and return *default*. *default* + defaults to ``None``. See :meth:`dict.setdefault` for more + information. + """ + if not super().__contains__(k): + self[k] = None if default is _MISSING else default + return self[k] + + def copy(self): + "Return a shallow copy of the dictionary." + return self.__class__(self.iteritems(multi=True)) + + @classmethod + def fromkeys(cls, keys, default=None): + """Create a dictionary from a list of keys, with all the values + set to *default*, or ``None`` if *default* is not set. + """ + return cls([(k, default) for k in keys]) + + def update(self, E, **F): + """Add items from a dictionary or iterable (and/or keyword arguments), + overwriting values under an existing key. See + :meth:`dict.update` for more details. + """ + # E and F are throwback names to the dict() __doc__ + if E is self: + return + self_add = self.add + if isinstance(E, OrderedMultiDict): + for k in E: + if k in self: + del self[k] + for k, v in E.iteritems(multi=True): + self_add(k, v) + elif callable(getattr(E, 'keys', None)): + for k in E.keys(): + self[k] = E[k] + else: + seen = set() + seen_add = seen.add + for k, v in E: + if k not in seen and k in self: + del self[k] + seen_add(k) + self_add(k, v) + for k in F: + self[k] = F[k] + return + + def update_extend(self, E, **F): + """Add items from a dictionary, iterable, and/or keyword + arguments without overwriting existing items present in the + dictionary. Like :meth:`update`, but adds to existing keys + instead of overwriting them. + """ + if E is self: + iterator = iter(E.items()) + elif isinstance(E, OrderedMultiDict): + iterator = E.iteritems(multi=True) + elif hasattr(E, 'keys'): + iterator = ((k, E[k]) for k in E.keys()) + else: + iterator = E + + self_add = self.add + for k, v in iterator: + self_add(k, v) + + def __setitem__(self, k, v): + if super().__contains__(k): + self._remove_all(k) + self._insert(k, v) + super().__setitem__(k, [v]) + + def __getitem__(self, k): + return super().__getitem__(k)[-1] + + def __delitem__(self, k): + super().__delitem__(k) + self._remove_all(k) + + def __eq__(self, other): + if self is other: + return True + try: + if len(other) != len(self): + return False + except TypeError: + return False + if isinstance(other, OrderedMultiDict): + selfi = self.iteritems(multi=True) + otheri = other.iteritems(multi=True) + zipped_items = zip_longest(selfi, otheri, fillvalue=(None, None)) + for (selfk, selfv), (otherk, otherv) in zipped_items: + if selfk != otherk or selfv != otherv: + return False + if not(next(selfi, _MISSING) is _MISSING + and next(otheri, _MISSING) is _MISSING): + # leftovers (TODO: watch for StopIteration?) + return False + return True + elif hasattr(other, 'keys'): + for selfk in self: + try: + other[selfk] == self[selfk] + except KeyError: + return False + return True + return False + + def __ne__(self, other): + return not (self == other) + + def __ior__(self, other): + self.update(other) + return self + + def pop(self, k, default=_MISSING): + """Remove all values under key *k*, returning the most-recently + inserted value. Raises :exc:`KeyError` if the key is not + present and no *default* is provided. + """ + try: + return self.popall(k)[-1] + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + + def popall(self, k, default=_MISSING): + """Remove all values under key *k*, returning them in the form of + a list. Raises :exc:`KeyError` if the key is not present and no + *default* is provided. + """ + super_self = super() + if super_self.__contains__(k): + self._remove_all(k) + if default is _MISSING: + return super_self.pop(k) + return super_self.pop(k, default) + + def poplast(self, k=_MISSING, default=_MISSING): + """Remove and return the most-recently inserted value under the key + *k*, or the most-recently inserted key if *k* is not + provided. If no values remain under *k*, it will be removed + from the OMD. Raises :exc:`KeyError` if *k* is not present in + the dictionary, or the dictionary is empty. + """ + if k is _MISSING: + if self: + k = self.root[PREV][KEY] + else: + if default is _MISSING: + raise KeyError('empty %r' % type(self)) + return default + try: + self._remove(k) + except KeyError: + if default is _MISSING: + raise KeyError(k) + return default + values = super().__getitem__(k) + v = values.pop() + if not values: + super().__delitem__(k) + return v + + def _remove(self, k): + values = self._map[k] + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + if not values: + del self._map[k] + + def _remove_all(self, k): + values = self._map[k] + while values: + cell = values.pop() + cell[PREV][NEXT], cell[NEXT][PREV] = cell[NEXT], cell[PREV] + del self._map[k] + + def iteritems(self, multi=False): + """Iterate over the OMD's items in insertion order. By default, + yields only the most-recently inserted value for each key. Set + *multi* to ``True`` to get all inserted items. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY], curr[VALUE] + curr = curr[NEXT] + else: + for key in self.iterkeys(): + yield key, self[key] + + def iterkeys(self, multi=False): + """Iterate over the OMD's keys in insertion order. By default, yields + each key once, according to the most recent insertion. Set + *multi* to ``True`` to get all keys, including duplicates, in + insertion order. + """ + root = self.root + curr = root[NEXT] + if multi: + while curr is not root: + yield curr[KEY] + curr = curr[NEXT] + else: + yielded = set() + yielded_add = yielded.add + while curr is not root: + k = curr[KEY] + if k not in yielded: + yielded_add(k) + yield k + curr = curr[NEXT] + + def itervalues(self, multi=False): + """Iterate over the OMD's values in insertion order. By default, + yields the most-recently inserted value per unique key. Set + *multi* to ``True`` to get all values according to insertion + order. + """ + for k, v in self.iteritems(multi=multi): + yield v + + def todict(self, multi=False): + """Gets a basic :class:`dict` of the items in this dictionary. Keys + are the same as the OMD, values are the most recently inserted + values for each key. + + Setting the *multi* arg to ``True`` is yields the same + result as calling :class:`dict` on the OMD, except that all the + value lists are copies that can be safely mutated. + """ + if multi: + return {k: self.getlist(k) for k in self} + return {k: self[k] for k in self} + + def sorted(self, key=None, reverse=False): + """Similar to the built-in :func:`sorted`, except this method returns + a new :class:`OrderedMultiDict` sorted by the provided key + function, optionally reversed. + + Args: + key (callable): A callable to determine the sort key of + each element. The callable should expect an **item** + (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict(zip(range(3), range(3))) + >>> omd.sorted(reverse=True) + OrderedMultiDict([(2, 2), (1, 1), (0, 0)]) + + Note that the key function receives an **item** (key-value + tuple), so the recommended signature looks like: + + >>> omd = OrderedMultiDict(zip('hello', 'world')) + >>> omd.sorted(key=lambda i: i[1]) # i[0] is the key, i[1] is the val + OrderedMultiDict([('o', 'd'), ('l', 'l'), ('e', 'o'), ('l', 'r'), ('h', 'w')]) + """ + cls = self.__class__ + return cls(sorted(self.iteritems(multi=True), key=key, reverse=reverse)) + + def sortedvalues(self, key=None, reverse=False): + """Returns a copy of the :class:`OrderedMultiDict` with the same keys + in the same order as the original OMD, but the values within + each keyspace have been sorted according to *key* and + *reverse*. + + Args: + key (callable): A single-argument callable to determine + the sort key of each element. The callable should expect + an **item** (key-value pair tuple). + reverse (bool): Set to ``True`` to reverse the ordering. + + >>> omd = OrderedMultiDict() + >>> omd.addlist('even', [6, 2]) + >>> omd.addlist('odd', [1, 5]) + >>> omd.add('even', 4) + >>> omd.add('odd', 3) + >>> somd = omd.sortedvalues() + >>> somd.getlist('even') + [2, 4, 6] + >>> somd.keys(multi=True) == omd.keys(multi=True) + True + >>> omd == somd + False + >>> somd + OrderedMultiDict([('even', 2), ('even', 4), ('odd', 1), ('odd', 3), ('even', 6), ('odd', 5)]) + + As demonstrated above, contents and key order are + retained. Only value order changes. + """ + try: + superself_iteritems = super().iteritems() + except AttributeError: + superself_iteritems = super().items() + # (not reverse) because they pop off in reverse order for reinsertion + sorted_val_map = {k: sorted(v, key=key, reverse=(not reverse)) + for k, v in superself_iteritems} + ret = self.__class__() + for k in self.iterkeys(multi=True): + ret.add(k, sorted_val_map[k].pop()) + return ret + + def inverted(self): + """Returns a new :class:`OrderedMultiDict` with values and keys + swapped, like creating dictionary transposition or reverse + index. Insertion order is retained and all keys and values + are represented in the output. + + >>> omd = OMD([(0, 2), (1, 2)]) + >>> omd.inverted().getlist(2) + [0, 1] + + Inverting twice yields a copy of the original: + + >>> omd.inverted().inverted() + OrderedMultiDict([(0, 2), (1, 2)]) + """ + return self.__class__((v, k) for k, v in self.iteritems(multi=True)) + + def counts(self): + """Returns a mapping from key to number of values inserted under that + key. Like :py:class:`collections.Counter`, but returns a new + :class:`OrderedMultiDict`. + """ + # Returns an OMD because Counter/OrderedDict may not be + # available, and neither Counter nor dict maintain order. + super_getitem = super().__getitem__ + return self.__class__((k, len(super_getitem(k))) for k in self) + + def keys(self, multi=False): + """Returns a list containing the output of :meth:`iterkeys`. See + that method's docs for more details. + """ + return list(self.iterkeys(multi=multi)) + + def values(self, multi=False): + """Returns a list containing the output of :meth:`itervalues`. See + that method's docs for more details. + """ + return list(self.itervalues(multi=multi)) + + def items(self, multi=False): + """Returns a list containing the output of :meth:`iteritems`. See + that method's docs for more details. + """ + return list(self.iteritems(multi=multi)) + + def __iter__(self): + return self.iterkeys() + + def __reversed__(self): + root = self.root + curr = root[PREV] + lengths = {} + lengths_sd = lengths.setdefault + get_values = super().__getitem__ + while curr is not root: + k = curr[KEY] + vals = get_values(k) + if lengths_sd(k, 1) == len(vals): + yield k + lengths[k] += 1 + curr = curr[PREV] + + def __repr__(self): + cn = self.__class__.__name__ + kvs = ', '.join([repr((k, v)) for k, v in self.iteritems(multi=True)]) + return f'{cn}([{kvs}])' + + def viewkeys(self): + "OMD.viewkeys() -> a set-like object providing a view on OMD's keys" + return KeysView(self) + + def viewvalues(self): + "OMD.viewvalues() -> an object providing a view on OMD's values" + return ValuesView(self) + + def viewitems(self): + "OMD.viewitems() -> a set-like object providing a view on OMD's items" + return ItemsView(self) + + + +try: + # try to import the built-in one anyways + from .dictutils import OrderedMultiDict +except ImportError: + pass + +OMD = OrderedMultiDict + + +class QueryParamDict(OrderedMultiDict): + """A subclass of :class:`~dictutils.OrderedMultiDict` specialized for + representing query string values. Everything is fully unquoted on + load and all parsed keys and values are strings by default. + + As the name suggests, multiple values are supported and insertion + order is preserved. + + >>> qp = QueryParamDict.from_text(u'key=val1&key=val2&utm_source=rtd') + >>> qp.getlist('key') + [u'val1', u'val2'] + >>> qp['key'] + u'val2' + >>> qp.add('key', 'val3') + >>> qp.to_text() + 'key=val1&key=val2&utm_source=rtd&key=val3' + + See :class:`~dictutils.OrderedMultiDict` for more API features. + """ + + @classmethod + def from_text(cls, query_string): + """ + Parse *query_string* and return a new :class:`QueryParamDict`. + """ + pairs = parse_qsl(query_string, keep_blank_values=True) + return cls(pairs) + + def to_text(self, full_quote=False): + """ + Render and return a query string. + + Args: + full_quote (bool): Whether or not to percent-quote special + characters or leave them decoded for readability. + """ + ret_list = [] + for k, v in self.iteritems(multi=True): + key = quote_query_part(to_unicode(k), full_quote=full_quote) + if v is None: + ret_list.append(key) + else: + val = quote_query_part(to_unicode(v), full_quote=full_quote) + ret_list.append('='.join((key, val))) + return '&'.join(ret_list) + +# end urlutils.py diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..dd0c5e58e83e49bd7641da322c24dbaeb6a2740f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/METADATA @@ -0,0 +1,227 @@ +Metadata-Version: 2.4 +Name: brotlicffi +Version: 1.2.0.0 +Summary: Python CFFI bindings to the Brotli library +Home-page: https://github.com/python-hyper/brotlicffi +Author: Cory Benfield +Author-email: cory@lukasa.co.uk +License: MIT +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.8 +License-File: LICENSE +Requires-Dist: cffi>=1.0.0; python_version < "3.13" +Requires-Dist: cffi>=1.17.0; python_version >= "3.13" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +BrotliCFFI +========== + +.. image:: https://img.shields.io/pypi/v/brotlicffi + :alt: Version + :target: https://pypi.org/project/brotlicffi + +.. image:: https://img.shields.io/conda/vn/conda-forge/brotlicffi + :alt: Version-Conda + :target: https://anaconda.org/conda-forge/brotlicffi + +.. image:: https://pepy.tech/badge/brotlicffi + :alt: Downloads + :target: https://pepy.tech/project/brotlicffi + +.. image:: https://img.shields.io/github/workflow/status/python-hyper/brotlicffi/CI/master + :alt: CI Status + :target: https://github.com/python-hyper/brotlicffi/actions + +This library contains Python CFFI bindings for the reference Brotli encoder/decoder, +`available here`_. This allows Python software to use the Brotli compression +algorithm directly from Python code. + +Install from PyPI: + +.. code-block:: + + $ python -m pip install brotlicffi + +Install from Conda: + +.. code-block:: + + $ conda install -c conda-forge brotlicffi + +To use it simply, try this: + +.. code-block:: python + + import brotlicffi + data = brotlicffi.decompress(compressed_data) + +More information can be found `in the documentation`_. + +.. _available here: https://github.com/google/brotli +.. _in the documentation: https://brotlipy.readthedocs.org + +Using BrotliCFFI in Projects +---------------------------- + +The API is 100% compatible with the `Brotli Python C bindings`_. +We recommend installing the C bindings on CPython and the CFFI +bindings everywhere else (PyPy, etc) + +Essentially you use requirements like this: + + .. code-block:: python + + install_requires=[ + "brotli; platform_python_implementation == 'CPython'", + "brotlicffi; platform_python_implementation != 'CPython'" + ] + +and then import the correct Brotli library like so: + + .. code-block:: python + + try: + import brotlicffi as brotli + except ImportError: + import brotli + +We provide an `example project`_ that shows how to use both +libraries together to support Brotli with multiple Python implementations. + +.. _Brotli Python C bindings: https://pypi.org/project/Brotli +.. _example project: https://github.com/python-hyper/brotlipy/tree/master/example + +License +------- + +The source code of BrotliCFFI is available under the MIT license. Brotli itself +is made available under the Version 2.0 of the Apache Software License. See the +LICENSE and libbrotli/LICENSE files for more information. + +Authors +------- + +BrotliCFFI/brotlipy was authored by Cory Benfield and +is currently maintained by Seth Michael Larson. + + +Changelog +========= + +1.2.0.0 (2025-11-21) +-------------------- + +- Upgraded libbrotli to v1.2.0. +- Added ``output_buffer_limit`` parameter to ``Decompressor.decompress()`` and + ``Decompressor.process()`` methods to allow mitigation of unexpectedly large + output. This addresses potential security concerns where maliciously crafted + compressed data could result in excessive memory usage during decompression. + + +1.1.0.0 (2023-09-14) +-------------------- + +- Upgraded libbrotli to v1.1.0 +- Added explicit support for Python 3.10, 3.11, and 3.12 +- Removed support for Python 2.7, 3.5, and 3.6 + + +1.0.9.2 (2021-04-06) +-------------------- + +- Added ``manylinux_aarch64`` wheels + + +1.0.9.1 (2021-01-27) +-------------------- + +- Avoid byte/string comparison warning in error message construction + + +1.0.9.0 (2021-01-20) +-------------------- + +- Updated to v1.0.9 of the Brotli library +- Library version now follows Brotli version +- Removed the ``dictionary`` parameter from ``compress`` and ``Compressor`` +- **NOTE:** Python 2.7 wheels for Windows likely won't work until + `google/brotli#848`_ is resolved + +.. _google/brotli#848: https://github.com/google/brotli/issues/848 + +0.8.0 (2020-11-30) +------------------ + +- Renamed the package on PyPI to ``brotlicffi``, all further updates will be + published to the new package. Using the ``brotlipy`` is deprecated. +- Changed the importable namespace from ``brotli`` to ``brotlicffi`` to no longer + conflict with the ``Brotli`` PyPI package. +- Added ``process()`` method to ``Compressor`` and ``Decompressor``. +- Added ``is_finished()`` method to ``Decompressor``. + +0.7.0 (2017-05-30) +------------------ + +- Update to v0.6.0 of the Brotli library. + +0.6.0 (2016-09-08) +------------------ + +- Resolved a bug where ``decompress()`` would return an empty bytestring + instead of erroring if the provided bytestring was small enough. +- Added the ``finish()`` method to the streaming decompressor. + +0.5.1 (2016-08-17) +------------------ + +- Update to v0.5.2 of the Brotli library. +- Add new exception type (``Error``). +- Add compatibility with C++ brotli library by aliasing ``Error`` to ``error``. +- Extra error checking of input parameters to the compressor. + +0.5.0 (2016-08-16) +------------------ + +- Update to v0.5.0 of the Brotli library. +- Extend one-shot compression API to include all control parameters. +- Added streaming/incremental compression API. +- Added flags to control compression mode. + +0.4.0 (2016-08-01) +------------------ + +Update to v0.4.0 of the Brotli library. + +0.3.0 (2016-05-11) +------------------ + +Update to v0.3.0 of the Brotli library. + +0.2.0 (2015-10-05) +------------------ + +Fix broken ``brotli.compress`` support on Windows. + +0.1.3 (2015-10-05) +------------------ + +- Added basic for ``brotli.compress`` through a C wrapper included in this + library. diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..567dbea23829621580c7ba9372ce537c0b6a345a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/RECORD @@ -0,0 +1,15 @@ +brotlicffi-1.2.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +brotlicffi-1.2.0.0.dist-info/METADATA,sha256=LkuvxaTt9hwuvMIRQQr0ubTMwjIo-llV0oagCGEMrwg,6437 +brotlicffi-1.2.0.0.dist-info/RECORD,, +brotlicffi-1.2.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +brotlicffi-1.2.0.0.dist-info/WHEEL,sha256=aQbDWqlaariPhPENOf9zLeAEUO9lPHXIaSFRigOtn8E,103 +brotlicffi-1.2.0.0.dist-info/direct_url.json,sha256=pVSHbeI_3Nu_1A76-8GFtcr2JzoAejOvySQaQLVPKmM,100 +brotlicffi-1.2.0.0.dist-info/licenses/LICENSE,sha256=8-nCnj2zbcMFpL5oqKIl-TlJhSzi0ZtbCjwJnu5lCcU,1056 +brotlicffi-1.2.0.0.dist-info/top_level.txt,sha256=QNsXaBb1b7FFDoROgMBoHTDwfsWia7dX5GLRhUDPyXM,23 +brotlicffi/__init__.py,sha256=NaVd_IM9h9jeHnOH9xUR-646Zu8TiUIuVtDh5l1upg0,224 +brotlicffi/__pycache__/__init__.cpython-313.pyc,, +brotlicffi/__pycache__/_api.cpython-313.pyc,, +brotlicffi/__pycache__/_build.cpython-313.pyc,, +brotlicffi/_api.py,sha256=9Sntv35FzgU78-Kp3AqLwSEz3Wtcck5EfRnr0rs3Tog,19563 +brotlicffi/_brotlicffi.abi3.so,sha256=IufFo3ndRinZCMccqGSeOolvYhXGzNS-x5sKOzhcVXw,899376 +brotlicffi/_build.py,sha256=Js-FovbzNIsR8ChfWXH8Qups7JuTm3PWRo3h7cJ44lE,9328 diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0643952b52c30583bae522eb4c1411eefa034232 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp313-abi3-linux_x86_64 + diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..6271558295c8582345b48c3a7cee30109f681aa0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176496126124857/conda-bld/brotlicffi_1764961326114/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d6466b602473a2683ccf84a9f6c6dce140a058e3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015 Cory Benfield + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/top_level.txt b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..697e753b0e8f0effe0b3ff3b52a22225f93e5b05 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi-1.2.0.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_brotlicffi +brotlicffi diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi/__init__.py b/miniconda3/lib/python3.13/site-packages/brotlicffi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ad22f00a1e6619ed34ebb40cc0572ae6318fbcb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi/__init__.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# flake8: noqa +from ._api import ( + decompress, Decompressor, compress, BrotliEncoderMode, DEFAULT_MODE, + Compressor, MODE_GENERIC, MODE_TEXT, MODE_FONT, error, Error +) + +__version__ = "1.2.0.0" diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi/_api.py b/miniconda3/lib/python3.13/site-packages/brotlicffi/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..b7e34bebe37fa3749198511eab99808f84e79187 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi/_api.py @@ -0,0 +1,557 @@ +# -*- coding: utf-8 -*- +import math +import enum + +from ._brotlicffi import ffi, lib + + +class error(Exception): + """ + Raised whenever an error is encountered with compressing or decompressing + data using brotlicffi. + + .. versionadded:: 0.5.1 + """ + pass + + +#: An alias of :class:`error ` that +#: exists for compatibility with the original CFFI brotli module. +#: +#: .. versionadded: 0.8.0 +Error = error + + +class BrotliEncoderMode(enum.IntEnum): + """ + Compression modes for the Brotli encoder. + + .. versionadded:: 0.5.0 + """ + #: Default compression mode. The compressor does not know anything in + #: advance about the properties of the input. + GENERIC = lib.BROTLI_MODE_GENERIC + + #: Compression mode for UTF-8 format text input. + TEXT = lib.BROTLI_MODE_TEXT + + #: Compression mode used in WOFF 2.0 + FONT = lib.BROTLI_MODE_FONT + + +# Define some names for compatibility with the C module. + +#: The default compression mode for brotli. +DEFAULT_MODE = BrotliEncoderMode(lib.BROTLI_DEFAULT_MODE) + + +#: A compression mode where the compressor does not know anything in advance +#: about the properties of the input. +#: +#: .. note:: This name is defined for compatibility with the Brotli C +#: extension. If you're not interested in that compatibility, it is +#: recommended that you use :class:`BrotliEncoderMode +#: ` instead. +#: +#: .. versionadded:: 0.5.0 +MODE_GENERIC = BrotliEncoderMode.GENERIC + + +#: A compression mode for UTF-8 format text input. +#: +#: .. note:: This name is defined for compatibility with the Brotli C +#: extension. If you're not interested in that compatibility, it is +#: recommended that you use :class:`BrotliEncoderMode +#: ` instead. +#: +#: .. versionadded:: 0.5.0 +MODE_TEXT = BrotliEncoderMode.TEXT + + +#: The compression mode used in WOFF 2.0. +#: +#: .. note:: This name is defined for compatibility with the Brotli C +#: extension. If you're not interested in that compatibility, it is +#: recommended that you use :class:`BrotliEncoderMode +#: ` instead. +#: +#: .. versionadded:: 0.5.0 +MODE_FONT = BrotliEncoderMode.FONT + + +def decompress(data): + """ + Decompress a complete Brotli-compressed string. + + :param data: A bytestring containing Brotli-compressed data. + """ + d = Decompressor() + data = d.decompress(data) + d.finish() + return data + + +def compress(data, + mode=DEFAULT_MODE, + quality=lib.BROTLI_DEFAULT_QUALITY, + lgwin=lib.BROTLI_DEFAULT_WINDOW, + lgblock=0): + """ + Compress a string using Brotli. + + .. versionchanged:: 0.5.0 + Added ``mode``, ``quality``, `lgwin``, ``lgblock``, and ``dictionary`` + parameters. + + :param data: A bytestring containing the data to compress. + :type data: ``bytes`` + + :param mode: The encoder mode. + :type mode: :class:`BrotliEncoderMode` or ``int`` + + :param quality: Controls the compression-speed vs compression-density + tradeoffs. The higher the quality, the slower the compression. The + range of this value is 0 to 11. + :type quality: ``int`` + + :param lgwin: The base-2 logarithm of the sliding window size. The range of + this value is 10 to 24. + :type lgwin: ``int`` + + :param lgblock: The base-2 logarithm of the maximum input block size. The + range of this value is 16 to 24. If set to 0, the value will be set + based on ``quality``. + :type lgblock: ``int`` + + :returns: The compressed bytestring. + :rtype: ``bytes`` + """ + # This method uses private variables on the Compressor object, and + # generally does a whole lot of stuff that's not supported by the public + # API. The goal here is to minimise the number of allocations and copies + # we have to do. Users should prefer this method over the Compressor if + # they know they have single-shot data. + compressor = Compressor( + mode=mode, + quality=quality, + lgwin=lgwin, + lgblock=lgblock + ) + compressed_data = compressor._compress(data, lib.BROTLI_OPERATION_FINISH) + assert lib.BrotliEncoderIsFinished(compressor._encoder) == lib.BROTLI_TRUE + assert ( + lib.BrotliEncoderHasMoreOutput(compressor._encoder) == lib.BROTLI_FALSE + ) + return compressed_data + + +def _validate_mode(val): + """ + Validate that the mode is valid. + """ + try: + val = BrotliEncoderMode(val) + except ValueError: + raise error("%s is not a valid encoder mode" % val) + + +def _validate_quality(val): + """ + Validate that the quality setting is valid. + """ + if not (0 <= val <= 11): + raise error( + "%d is not a valid quality, must be between 0 and 11" % val + ) + + +def _validate_lgwin(val): + """ + Validate that the lgwin setting is valid. + """ + if not (10 <= val <= 24): + raise error("%d is not a valid lgwin, must be between 10 and 24" % val) + + +def _validate_lgblock(val): + """ + Validate that the lgblock setting is valid. + """ + if (val != 0) and not (16 <= val <= 24): + raise error( + "%d is not a valid lgblock, must be either 0 or between 16 and 24" + % val + ) + + +def _set_parameter(encoder, parameter, parameter_name, val): + """ + This helper function sets a specific Brotli encoder parameter, checking + the return code and raising :class:`Error ` if it is + invalid. + """ + rc = lib.BrotliEncoderSetParameter(encoder, parameter, val) + + if parameter == lib.BROTLI_PARAM_MODE: + _validate_mode(val) + elif parameter == lib.BROTLI_PARAM_QUALITY: + _validate_quality(val) + elif parameter == lib.BROTLI_PARAM_LGWIN: + _validate_lgwin(val) + elif parameter == lib.BROTLI_PARAM_LGBLOCK: + _validate_lgblock(val) + else: # pragma: no cover + raise RuntimeError("Unexpected parameter!") + + # This block is defensive: I see no way to hit it, but as long as the + # function returns a value we can live in hope that the brotli folks will + # enforce their own constraints. + if rc != lib.BROTLI_TRUE: # pragma: no cover + raise error( + "Error setting parameter %s: %d" % (parameter_name, val) + ) + + +class Compressor(object): + """ + An object that allows for streaming compression of data using the Brotli + compression algorithm. + + .. versionadded:: 0.5.0 + + :param mode: The encoder mode. + :type mode: :class:`BrotliEncoderMode` or ``int`` + + :param quality: Controls the compression-speed vs compression-density + tradeoffs. The higher the quality, the slower the compression. The + range of this value is 0 to 11. + :type quality: ``int`` + + :param lgwin: The base-2 logarithm of the sliding window size. The range of + this value is 10 to 24. + :type lgwin: ``int`` + + :param lgblock: The base-2 logarithm of the maximum input block size. The + range of this value is 16 to 24. If set to 0, the value will be set + based on ``quality``. + :type lgblock: ``int`` + + :param dictionary: A pre-set dictionary for LZ77. Please use this with + caution: if a dictionary is used for compression, the same dictionary + **must** be used for decompression! + :type dictionary: ``bytes`` + """ + _dictionary = None + _dictionary_size = None + + def __init__(self, + mode=DEFAULT_MODE, + quality=lib.BROTLI_DEFAULT_QUALITY, + lgwin=lib.BROTLI_DEFAULT_WINDOW, + lgblock=0): + enc = lib.BrotliEncoderCreateInstance( + ffi.NULL, ffi.NULL, ffi.NULL + ) + if not enc: # pragma: no cover + raise RuntimeError("Unable to allocate Brotli encoder!") + + enc = ffi.gc(enc, lib.BrotliEncoderDestroyInstance) + + # Configure the encoder appropriately. + _set_parameter(enc, lib.BROTLI_PARAM_MODE, "mode", mode) + _set_parameter(enc, lib.BROTLI_PARAM_QUALITY, "quality", quality) + _set_parameter(enc, lib.BROTLI_PARAM_LGWIN, "lgwin", lgwin) + _set_parameter(enc, lib.BROTLI_PARAM_LGBLOCK, "lgblock", lgblock) + + self._encoder = enc + + def _compress(self, data, operation): + """ + This private method compresses some data in a given mode. This is used + because almost all of the code uses the exact same setup. It wouldn't + have to, but it doesn't hurt at all. + """ + # The 'algorithm' for working out how big to make this buffer is from + # the Brotli source code, brotlimodule.cc. + original_output_size = int( + math.ceil(len(data) + (len(data) >> 2) + 10240) + ) + available_out = ffi.new("size_t *") + available_out[0] = original_output_size + output_buffer = ffi.new("uint8_t []", available_out[0]) + ptr_to_output_buffer = ffi.new("uint8_t **", output_buffer) + input_size = ffi.new("size_t *", len(data)) + input_buffer = ffi.new("uint8_t []", data) + ptr_to_input_buffer = ffi.new("uint8_t **", input_buffer) + + rc = lib.BrotliEncoderCompressStream( + self._encoder, + operation, + input_size, + ptr_to_input_buffer, + available_out, + ptr_to_output_buffer, + ffi.NULL + ) + if rc != lib.BROTLI_TRUE: # pragma: no cover + raise error("Error encountered compressing data.") + + assert not input_size[0] + + size_of_output = original_output_size - available_out[0] + return ffi.buffer(output_buffer, size_of_output)[:] + + def compress(self, data): + """ + Incrementally compress more data. + + :param data: A bytestring containing data to compress. + :returns: A bytestring containing some compressed data. May return the + empty bytestring if not enough data has been inserted into the + compressor to create the output yet. + """ + return self._compress(data, lib.BROTLI_OPERATION_PROCESS) + + process = compress + + def flush(self): + """ + Flush the compressor. This will emit the remaining output data, but + will not destroy the compressor. It can be used, for example, to ensure + that given chunks of content will decompress immediately. + """ + chunks = [self._compress(b'', lib.BROTLI_OPERATION_FLUSH)] + + while lib.BrotliEncoderHasMoreOutput(self._encoder) == lib.BROTLI_TRUE: + chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FLUSH)) + + return b''.join(chunks) + + def finish(self): + """ + Finish the compressor. This will emit the remaining output data and + transition the compressor to a completed state. The compressor cannot + be used again after this point, and must be replaced. + """ + chunks = [] + while lib.BrotliEncoderIsFinished(self._encoder) == lib.BROTLI_FALSE: + chunks.append(self._compress(b'', lib.BROTLI_OPERATION_FINISH)) + + return b''.join(chunks) + + +class Decompressor(object): + """ + An object that allows for streaming decompression of Brotli-compressed + data. + + .. versionchanged:: 0.5.0 + Added ``dictionary`` parameter. + + .. versionchanged:: 1.2.0 + Added ``can_accept_more_data()`` method and optional + ``output_buffer_limit`` parameter to ``process()``/``decompress()``. + + :param dictionary: A pre-set dictionary for LZ77. Please use this with + caution: if a dictionary is used for compression, the same dictionary + **must** be used for decompression! + :type dictionary: ``bytes`` + """ + _dictionary = None + _dictionary_size = None + _unconsumed_data = None + + def __init__(self, dictionary=b''): + dec = lib.BrotliDecoderCreateInstance(ffi.NULL, ffi.NULL, ffi.NULL) + self._decoder = ffi.gc(dec, lib.BrotliDecoderDestroyInstance) + self._unconsumed_data = b'' + + if dictionary: + self._dictionary = ffi.new("uint8_t []", dictionary) + self._dictionary_size = len(dictionary) + lib.BrotliDecoderSetCustomDictionary( + self._decoder, + self._dictionary_size, + self._dictionary + ) + + @staticmethod + def _calculate_buffer_size( + input_data_len, output_buffer_limit, chunks_len, chunks_num + ): + if output_buffer_limit is not None: + return output_buffer_limit - chunks_len + # When `decompress(b'')` is called without `output_buffer_limit`. + elif input_data_len == 0: + # libbrotli would use 32 KB as a starting buffer size and double it + # each time, capped at 16 MB. + # https://github.com/google/brotli/blob/028fb5a23661f123017c060daa546b55cf4bde29/python/_brotli.c#L291-L292 + return 1 << min(chunks_num + 15, 24) + else: + # Allocate a buffer that's hopefully overlarge, but if it's not we + # don't mind: we'll spin around again. + return 5 * input_data_len + + def decompress(self, data, output_buffer_limit=None): + """ + Decompress part of a complete Brotli-compressed string. + + .. versionchanged:: 1.2.0 + Added ``output_buffer_limit`` parameter. + + :param data: A bytestring containing Brotli-compressed data. + :param output_buffer_limit: Optional maximum size for the output + buffer. If set, the output buffer will not grow once its size + equals or exceeds this value. If the limit is reached, further + calls to process (potentially with empty input) will continue to + yield more data. Following process() calls must only be called + with empty input until can_accept_more_data() returns True. + :type output_buffer_limit: ``int`` or ``None`` + :returns: A bytestring containing the decompressed data. + """ + if self._unconsumed_data and data: + raise error( + "brotli: decoder process called with data when " + "'can_accept_more_data()' is False" + ) + + # We should avoid operations on the `self._unconsumed_data` if no data + # is to be processed. + if output_buffer_limit is not None and output_buffer_limit <= 0: + return b'' + + # Use unconsumed data if available, use new data otherwise. + if self._unconsumed_data: + input_data = self._unconsumed_data + self._unconsumed_data = b'' + else: + input_data = data + + chunks = [] + chunks_len = 0 + + available_in = ffi.new("size_t *", len(input_data)) + in_buffer = ffi.new("uint8_t[]", input_data) + next_in = ffi.new("uint8_t **", in_buffer) + + while True: + buffer_size = self._calculate_buffer_size( + input_data_len=len(input_data), + output_buffer_limit=output_buffer_limit, + chunks_len=chunks_len, + chunks_num=len(chunks), + ) + + available_out = ffi.new("size_t *", buffer_size) + out_buffer = ffi.new("uint8_t[]", buffer_size) + next_out = ffi.new("uint8_t **", out_buffer) + + rc = lib.BrotliDecoderDecompressStream(self._decoder, + available_in, + next_in, + available_out, + next_out, + ffi.NULL) + + # First, check for errors. + if rc == lib.BROTLI_DECODER_RESULT_ERROR: + error_code = lib.BrotliDecoderGetErrorCode(self._decoder) + error_message = lib.BrotliDecoderErrorString(error_code) + raise error( + b"Decompression error: %s" % ffi.string(error_message) + ) + + # Next, copy the result out. + chunk = ffi.buffer(out_buffer, buffer_size - available_out[0])[:] + chunks.append(chunk) + chunks_len += len(chunk) + + # Save any unconsumed input for the next call. + if available_in[0] > 0: + remaining_input = ffi.buffer(next_in[0], available_in[0])[:] + self._unconsumed_data = remaining_input + + # Check if we've reached the output limit. + if ( + output_buffer_limit is not None + and chunks_len >= output_buffer_limit + ): + break + + if rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: + assert available_in[0] == 0 + break + elif rc == lib.BROTLI_DECODER_RESULT_SUCCESS: + break + else: + # It's cool if we need more output, we just loop again. + assert rc == lib.BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT + + return b''.join(chunks) + + process = decompress + + def flush(self): + """ + Complete the decompression, return whatever data is remaining to be + decompressed. + + .. deprecated:: 0.4.0 + + This method is no longer required, as decompress() will now + decompress eagerly. + + :returns: A bytestring containing the remaining decompressed data. + """ + return b'' + + def finish(self): + """ + Finish the decompressor. As the decompressor decompresses eagerly, this + will never actually emit any data. However, it will potentially throw + errors if a truncated or damaged data stream has been used. + + Note that, once this method is called, the decompressor is no longer + safe for further use and must be thrown away. + """ + assert ( + lib.BrotliDecoderHasMoreOutput(self._decoder) == lib.BROTLI_FALSE + ) + if not self.is_finished(): + raise error("Decompression error: incomplete compressed stream.") + + return b'' + + def is_finished(self): + """ + Returns ``True`` if the decompression stream + is complete, ``False`` otherwise + """ + return lib.BrotliDecoderIsFinished(self._decoder) == lib.BROTLI_TRUE + + def can_accept_more_data(self): + """ + Checks if the decompressor can accept more compressed data. + + If the ``output_buffer_limit`` parameter was used with + ``decompress()`` or ``process()``, this method should be checked to + determine if the decompressor is ready to accept new input. When the + output buffer limit is reached, the decompressor may still have + unconsumed input data or internal buffered output, and calling + ``decompress(b'')`` repeatedly will continue producing output until + this method returns ``True``. + + .. versionadded:: 1.2.0 + + :returns: ``True`` if the decompressor is ready to accept more + compressed data via ``decompress()`` or ``process()``, ``False`` + if the decompressor needs to output some data via + ``decompress(b'')``/``process(b'')`` before being provided any + more compressed data. + :rtype: ``bool`` + """ + if len(self._unconsumed_data) > 0: + return False + if lib.BrotliDecoderHasMoreOutput(self._decoder) == lib.BROTLI_TRUE: + return False + return True diff --git a/miniconda3/lib/python3.13/site-packages/brotlicffi/_build.py b/miniconda3/lib/python3.13/site-packages/brotlicffi/_build.py new file mode 100644 index 0000000000000000000000000000000000000000..115be2e9bf04c40d26e2920f1d03c5c947129f64 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/brotlicffi/_build.py @@ -0,0 +1,207 @@ +# -*- coding: utf-8 -*- +import os +import sys + +from cffi import FFI +ffi = FFI() + +USE_SHARED_BROTLI = os.environ.get("USE_SHARED_BROTLI") +if USE_SHARED_BROTLI != "1": + libraries = ['libbrotli'] +else: + libraries = ['brotlienc', 'brotlidec'] + + if 'win32' not in str(sys.platform).lower(): + libraries.append('stdc++') + + +ffi.set_source( + "_brotlicffi", + """#include + #include + """, + libraries=libraries, + include_dirs=["libbrotli/c", "libbrotli/c/include", "libbrotli/c/common"] +) + +ffi.cdef(""" + /* common/types.h */ + typedef bool BROTLI_BOOL; + #define BROTLI_TRUE ... + #define BROTLI_FALSE ... + + /* dec/state.h */ + /* Allocating function pointer. Function MUST return 0 in the case of + failure. Otherwise it MUST return a valid pointer to a memory region of + at least size length. Neither items nor size are allowed to be 0. + opaque argument is a pointer provided by client and could be used to + bind function to specific object (memory pool). */ + typedef void* (*brotli_alloc_func)(void* opaque, size_t size); + + /* Deallocating function pointer. Function SHOULD be no-op in the case the + address is 0. */ + typedef void (*brotli_free_func)(void* opaque, void* address); + + /* dec/decode.h */ + + typedef enum { + /* Decoding error, e.g. corrupt input or memory allocation problem */ + BROTLI_DECODER_RESULT_ERROR = 0, + /* Decoding successfully completed */ + BROTLI_DECODER_RESULT_SUCCESS = 1, + /* Partially done; should be called again with more input */ + BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT = 2, + /* Partially done; should be called again with more output */ + BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT = 3 + } BrotliDecoderResult; + + typedef enum {...} BrotliDecoderErrorCode; + typedef ... BrotliDecoderState; + + /* Creates the instance of BrotliDecoderState and initializes it. + |alloc_func| and |free_func| MUST be both zero or both non-zero. In the + case they are both zero, default memory allocators are used. |opaque| is + passed to |alloc_func| and |free_func| when they are called. */ + BrotliDecoderState* BrotliDecoderCreateInstance(brotli_alloc_func, + brotli_free_func, + void *); + + /* Deinitializes and frees BrotliDecoderState instance. */ + void BrotliDecoderDestroyInstance(BrotliDecoderState* state); + + /* Decompresses the data. Supports partial input and output. + + Must be called with an allocated input buffer in |*next_in| and an + allocated output buffer in |*next_out|. The values |*available_in| and + |*available_out| must specify the allocated size in |*next_in| and + |*next_out| respectively. + + After each call, |*available_in| will be decremented by the amount of + input bytes consumed, and the |*next_in| pointer will be incremented by + that amount. Similarly, |*available_out| will be decremented by the + amount of output bytes written, and the |*next_out| pointer will be + incremented by that amount. |total_out|, if it is not a null-pointer, + will be set to the number of bytes decompressed since the last state + initialization. + + Input is never overconsumed, so |next_in| and |available_in| could be + passed to the next consumer after decoding is complete. */ + BrotliDecoderResult BrotliDecoderDecompressStream(BrotliDecoderState* s, + size_t* available_in, + const uint8_t** next_in, + size_t* available_out, + uint8_t** next_out, + size_t* total_out); + + /* Returns true, if decoder has some unconsumed output. + Otherwise returns false. */ + BROTLI_BOOL BrotliDecoderHasMoreOutput(const BrotliDecoderState* s); + + /* Returns true, if decoder has already received some input bytes. + Otherwise returns false. */ + BROTLI_BOOL BrotliDecoderIsUsed(const BrotliDecoderState* s); + + /* Returns true, if decoder is in a state where we reached the end of the + input and produced all of the output; returns false otherwise. */ + BROTLI_BOOL BrotliDecoderIsFinished(const BrotliDecoderState* s); + + /* Returns detailed error code after BrotliDecompressStream returns + BROTLI_DECODER_RESULT_ERROR. */ + BrotliDecoderErrorCode BrotliDecoderGetErrorCode( + const BrotliDecoderState* s); + + const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c); + + /* enc/encode.h */ + typedef ... BrotliEncoderState; + + typedef enum BrotliEncoderParameter { + BROTLI_PARAM_MODE = 0, + /* Controls the compression-speed vs compression-density tradeoffs. The + higher the quality, the slower the compression. Range is 0 to 11. */ + BROTLI_PARAM_QUALITY = 1, + /* Base 2 logarithm of the sliding window size. Range is 10 to 24. */ + BROTLI_PARAM_LGWIN = 2, + /* Base 2 logarithm of the maximum input block size. Range is 16 to 24. + If set to 0, the value will be set based on the quality. */ + BROTLI_PARAM_LGBLOCK = 3 + } BrotliEncoderParameter; + + typedef enum BrotliEncoderMode { + /* Default compression mode. The compressor does not know anything in + advance about the properties of the input. */ + BROTLI_MODE_GENERIC = 0, + /* Compression mode for UTF-8 format text input. */ + BROTLI_MODE_TEXT = 1, + /* Compression mode used in WOFF 2.0. */ + BROTLI_MODE_FONT = 2 + } BrotliEncoderMode; + + int BROTLI_DEFAULT_QUALITY = 11; + int BROTLI_DEFAULT_WINDOW = 22; + #define BROTLI_DEFAULT_MODE ... + + typedef enum BrotliEncoderOperation { + BROTLI_OPERATION_PROCESS = 0, + /* Request output stream to flush. Performed when input stream is + depleted and there is enough space in output stream. */ + BROTLI_OPERATION_FLUSH = 1, + /* Request output stream to finish. Performed when input stream is + depleted and there is enough space in output stream. */ + BROTLI_OPERATION_FINISH = 2 + } BrotliEncoderOperation; + + /* Creates the instance of BrotliEncoderState and initializes it. + |alloc_func| and |free_func| MUST be both zero or both non-zero. In the + case they are both zero, default memory allocators are used. |opaque| is + passed to |alloc_func| and |free_func| when they are called. */ + BrotliEncoderState* BrotliEncoderCreateInstance(brotli_alloc_func, + brotli_free_func, + void *); + + /* Deinitializes and frees BrotliEncoderState instance. */ + void BrotliEncoderDestroyInstance(BrotliEncoderState* state); + + /* Compresses the data in |input_buffer| into |encoded_buffer|, and sets + |*encoded_size| to the compressed length. + BROTLI_DEFAULT_QUALITY, BROTLI_DEFAULT_WINDOW and BROTLI_DEFAULT_MODE + should be used as |quality|, |lgwin| and |mode| if there are no specific + requirements to encoder speed and compression ratio. + If compression fails, |*encoded_size| is set to 0. + If BrotliEncoderMaxCompressedSize(|input_size|) is not zero, then + |*encoded_size| is never set to the bigger value. + Returns false if there was an error and true otherwise. */ + BROTLI_BOOL BrotliEncoderCompress(int quality, + int lgwin, + BrotliEncoderMode mode, + size_t input_size, + const uint8_t* input_buffer, + size_t* encoded_size, + uint8_t* encoded_buffer); + + BROTLI_BOOL BrotliEncoderCompressStream(BrotliEncoderState* s, + BrotliEncoderOperation op, + size_t* available_in, + const uint8_t** next_in, + size_t* available_out, + uint8_t** next_out, + size_t* total_out); + + BROTLI_BOOL BrotliEncoderSetParameter(BrotliEncoderState* state, + BrotliEncoderParameter p, + uint32_t value); + + /* Check if encoder is in "finished" state, i.e. no more input is + acceptable and no more output will be produced. + Works only with BrotliEncoderCompressStream workflow. + Returns 1 if stream is finished and 0 otherwise. */ + BROTLI_BOOL BrotliEncoderIsFinished(BrotliEncoderState* s); + + /* Check if encoder has more output bytes in internal buffer. + Works only with BrotliEncoderCompressStream workflow. + Returns 1 if has more output (in internal buffer) and 0 otherwise. */ + BROTLI_BOOL BrotliEncoderHasMoreOutput(BrotliEncoderState* s); +""") + +if __name__ == '__main__': + ffi.compile() diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/LICENSE b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..62b076cdee58ec8f34034141ba0befd9015b0c7e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/LICENSE @@ -0,0 +1,20 @@ +This package contains a modified version of ca-bundle.crt: + +ca-bundle.crt -- Bundle of CA Root Certificates + +This is a bundle of X.509 certificates of public Certificate Authorities +(CA). These were automatically extracted from Mozilla's root certificates +file (certdata.txt). This file can be found in the mozilla source tree: +https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt +It contains the certificates in PEM format and therefore +can be directly used with curl / libcurl / php_curl, or with +an Apache+mod_ssl webserver for SSL client authentication. +Just configure this file as the SSLCACertificateFile.# + +***** BEGIN LICENSE BLOCK ***** +This Source Code Form is subject to the terms of the Mozilla Public License, +v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain +one at http://mozilla.org/MPL/2.0/. + +***** END LICENSE BLOCK ***** +@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $ diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ed3932a32a832d513ae75ed3898debc7db418d04 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/METADATA @@ -0,0 +1,68 @@ +Metadata-Version: 2.1 +Name: certifi +Version: 2026.1.4 +Summary: Python package for providing Mozilla's CA Bundle. +Home-page: https://github.com/certifi/python-certifi +Author: Kenneth Reitz +Author-email: me@kennethreitz.com +License: MPL-2.0 +Project-URL: Source, https://github.com/certifi/python-certifi +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) +Classifier: Natural Language :: English +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.7 +License-File: LICENSE + +Certifi: Python SSL Certificates +================================ + +Certifi provides Mozilla's carefully curated collection of Root Certificates for +validating the trustworthiness of SSL certificates while verifying the identity +of TLS hosts. It has been extracted from the `Requests`_ project. + +Installation +------------ + +``certifi`` is available on PyPI. Simply install it with ``pip``:: + + $ pip install certifi + +Usage +----- + +To reference the installed certificate authority (CA) bundle, you can use the +built-in function:: + + >>> import certifi + + >>> certifi.where() + '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem' + +Or from the command line:: + + $ python -m certifi + /usr/local/lib/python3.7/site-packages/certifi/cacert.pem + +Enjoy! + +.. _`Requests`: https://requests.readthedocs.io/en/master/ + +Addition/Removal of Certificates +-------------------------------- + +Certifi does not support any addition/removal or other modification of the +CA trust store content. This project is intended to provide a reliable and +highly portable root of trust to python deployments. Look to upstream projects +for methods to use alternate trust. diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f4ea23912a02a2cc1d85df22a04009ed5a156ecd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/RECORD @@ -0,0 +1,16 @@ +certifi-2026.1.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +certifi-2026.1.4.dist-info/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989 +certifi-2026.1.4.dist-info/METADATA,sha256=yeKVf1EYbPjuT6P4R959vOxQwbjATa94TDBlp13QWxE,2273 +certifi-2026.1.4.dist-info/RECORD,, +certifi-2026.1.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +certifi-2026.1.4.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +certifi-2026.1.4.dist-info/direct_url.json,sha256=q2E3HGfxQqOOrlK-gjsNECFT9UyA7qSDTWnE2zgbSpg,101 +certifi-2026.1.4.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8 +certifi/__init__.py,sha256=969deMMS7Uchipr0oO4dbRBUvRi0uNYCn07VmG1aTrg,94 +certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243 +certifi/__pycache__/__init__.cpython-313.pyc,, +certifi/__pycache__/__main__.cpython-313.pyc,, +certifi/__pycache__/core.cpython-313.pyc,, +certifi/cacert.pem,sha256=Tzl1_zCrvzVEO0hgZK6Ly0Hf9wf_31dsdtKS-0WKoKk,270954 +certifi/core.py,sha256=XFXycndG5pf37ayeF8N32HUuDafsyhkVMbO4BAPWHa0,3394 +certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..e65943c0d27aad2ef9e143ffe2646880f7a85c91 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176765916174011/croot/certifi_1767659183877/work/certifi"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/top_level.txt b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..963eac530b9bc28d704d1bc410299c68e3216d4d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi-2026.1.4.dist-info/top_level.txt @@ -0,0 +1 @@ +certifi diff --git a/miniconda3/lib/python3.13/site-packages/certifi/__init__.py b/miniconda3/lib/python3.13/site-packages/certifi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..090fd58487b7ea8176a57024a478435720515486 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi/__init__.py @@ -0,0 +1,4 @@ +from .core import contents, where + +__all__ = ["contents", "where"] +__version__ = "2026.01.04" diff --git a/miniconda3/lib/python3.13/site-packages/certifi/__main__.py b/miniconda3/lib/python3.13/site-packages/certifi/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..8945b5da857f4a7dec2b84f1225f012f6098418c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi/__main__.py @@ -0,0 +1,12 @@ +import argparse + +from certifi import contents, where + +parser = argparse.ArgumentParser() +parser.add_argument("-c", "--contents", action="store_true") +args = parser.parse_args() + +if args.contents: + print(contents()) +else: + print(where()) diff --git a/miniconda3/lib/python3.13/site-packages/certifi/cacert.pem b/miniconda3/lib/python3.13/site-packages/certifi/cacert.pem new file mode 100644 index 0000000000000000000000000000000000000000..132db0df1b87e4d6b4519f362c82b01467d5d2e8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi/cacert.pem @@ -0,0 +1,4468 @@ + +# Issuer: CN=QuoVadis Root CA 2 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 2 O=QuoVadis Limited +# Label: "QuoVadis Root CA 2" +# Serial: 1289 +# MD5 Fingerprint: 5e:39:7b:dd:f8:ba:ec:82:e9:ac:62:ba:0c:54:00:2b +# SHA1 Fingerprint: ca:3a:fb:cf:12:40:36:4b:44:b2:16:20:88:80:48:39:19:93:7c:f7 +# SHA256 Fingerprint: 85:a0:dd:7d:d7:20:ad:b7:ff:05:f8:3d:54:2b:20:9d:c7:ff:45:28:f7:d6:77:b1:83:89:fe:a5:e5:c4:9e:86 +-----BEGIN CERTIFICATE----- +MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x +GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv +b3QgQ0EgMjAeFw0wNjExMjQxODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNV +BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W +YWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCa +GMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6XJxg +Fyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55J +WpzmM+Yklvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bB +rrcCaoF6qUWD4gXmuVbBlDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp ++ARz8un+XJiM9XOva7R+zdRcAitMOeGylZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1 +ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt66/3FsvbzSUr5R/7mp/i +Ucw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1JdxnwQ5hYIiz +PtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og +/zOhD7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UH +oycR7hYQe7xFSkyyBNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuI +yV77zGHcizN300QyNQliBJIWENieJ0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1Ud +EwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBQahGK8SEwzJQTU7tD2 +A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGUa6FJpEcwRTEL +MAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT +ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2f +BluornFdLwUvZ+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzn +g/iN/Ae42l9NLmeyhP3ZRPx3UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2Bl +fF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodmVjB3pjd4M1IQWK4/YY7yarHvGH5K +WWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK+JDSV6IZUaUtl0Ha +B0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrWIozc +hLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPR +TUIZ3Ph1WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWD +mbA4CD/pXvk1B+TJYm5Xf6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0Z +ohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y +4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8VCLAAVBpQ570su9t+Oza +8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 3" +# Serial: 1478 +# MD5 Fingerprint: 31:85:3c:62:94:97:63:b9:aa:fd:89:4e:af:6f:e0:cf +# SHA1 Fingerprint: 1f:49:14:f7:d8:74:95:1d:dd:ae:02:c0:be:fd:3a:2d:82:75:51:85 +# SHA256 Fingerprint: 18:f1:fc:7f:20:5d:f8:ad:dd:eb:7f:e0:07:dd:57:e3:af:37:5a:9c:4d:8d:73:54:6b:f4:f1:fe:d1:e1:8d:35 +-----BEGIN CERTIFICATE----- +MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x +GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv +b3QgQ0EgMzAeFw0wNjExMjQxOTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNV +BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W +YWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDM +V0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNggDhoB +4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUr +H556VOijKTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd +8lyyBTNvijbO0BNO/79KDDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9Cabwv +vWhDFlaJKjdhkf2mrk7AyxRllDdLkgbvBNDInIjbC3uBr7E9KsRlOni27tyAsdLT +mZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwpp5ijJUMv7/FfJuGITfhe +btfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8nT8KKdjc +T5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDt +WAEXMJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZ +c6tsgLjoC2SToJyMGf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A +4iLItLRkT9a6fUg+qGkM17uGcclzuD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYD +VR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHTBgkrBgEEAb5YAAMwgcUwgZMG +CCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmljYXRlIGNvbnN0 +aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0 +aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVu +dC4wLQYIKwYBBQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2Nw +czALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4G +A1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4ywLQoUmkRzBFMQswCQYDVQQGEwJC +TTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UEAxMSUXVvVmFkaXMg +Um9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZVqyM0 +7ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSem +d1o417+shvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd ++LJ2w/w4E6oM3kJpK27zPOuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B +4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadN +t54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp8kokUvd0/bpO5qgdAm6x +DYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBCbjPsMZ57 +k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6s +zHXug/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0j +Wy10QJLZYxkNc91pvGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeT +mJlglFwjz1onl14LBQaTNx47aTbrqZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK +4SVhM7JZG+Ju1zdXtg2pEto= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root CA" +# Serial: 17154717934120587862167794914071425081 +# MD5 Fingerprint: 87:ce:0b:7b:2a:0e:49:00:e1:58:71:9b:37:a8:93:72 +# SHA1 Fingerprint: 05:63:b8:63:0d:62:d7:5a:bb:c8:ab:1e:4b:df:b5:a8:99:b2:4d:43 +# SHA256 Fingerprint: 3e:90:99:b5:01:5e:8f:48:6c:00:bc:ea:9d:11:1e:e7:21:fa:ba:35:5a:89:bc:f1:df:69:56:1e:3d:c6:32:5c +-----BEGIN CERTIFICATE----- +MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv +b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl +cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c +JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP +mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+ +wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4 +VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/ +AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB +AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun +pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC +dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf +fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm +NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx +H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe ++o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root CA" +# Serial: 10944719598952040374951832963794454346 +# MD5 Fingerprint: 79:e4:a9:84:0d:7d:3a:96:d7:c0:4f:e2:43:4c:89:2e +# SHA1 Fingerprint: a8:98:5d:3a:65:e5:e5:c4:b2:d7:d6:6d:40:c6:dd:2f:b1:9c:54:36 +# SHA256 Fingerprint: 43:48:a0:e9:44:4c:78:cb:26:5e:05:8d:5e:89:44:b4:d8:4f:96:62:bd:26:db:25:7f:89:34:a4:43:c7:01:61 +-----BEGIN CERTIFICATE----- +MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD +QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB +CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 +nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt +43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P +T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 +gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO +BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR +TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw +DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr +hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg +06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF +PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls +YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk +CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert High Assurance EV Root CA" +# Serial: 3553400076410547919724730734378100087 +# MD5 Fingerprint: d4:74:de:57:5c:39:b2:d3:9c:85:83:c5:c0:65:49:8a +# SHA1 Fingerprint: 5f:b7:ee:06:33:e2:59:db:ad:0c:4c:9a:e6:d3:8f:1a:61:c7:dc:25 +# SHA256 Fingerprint: 74:31:e5:f4:c3:c1:ce:46:90:77:4f:0b:61:e0:54:40:88:3b:a9:a0:1e:d0:0b:a6:ab:d7:80:6e:d3:b1:18:cf +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j +ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL +MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 +LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug +RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm ++9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW +PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM +xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB +Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 +hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg +EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA +FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec +nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z +eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF +hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 +Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe +vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep ++OkuE6N36B9K +-----END CERTIFICATE----- + +# Issuer: CN=SwissSign Gold CA - G2 O=SwissSign AG +# Subject: CN=SwissSign Gold CA - G2 O=SwissSign AG +# Label: "SwissSign Gold CA - G2" +# Serial: 13492815561806991280 +# MD5 Fingerprint: 24:77:d9:a8:91:d1:3b:fa:88:2d:c2:ff:f8:cd:33:93 +# SHA1 Fingerprint: d8:c5:38:8a:b7:30:1b:1b:6e:d4:7a:e6:45:25:3a:6f:9f:1a:27:61 +# SHA256 Fingerprint: 62:dd:0b:e9:b9:f5:0a:16:3e:a0:f8:e7:5c:05:3b:1e:ca:57:ea:55:c8:68:8f:64:7c:68:81:f2:c8:35:7b:95 +-----BEGIN CERTIFICATE----- +MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV +BAYTAkNIMRUwEwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2ln +biBHb2xkIENBIC0gRzIwHhcNMDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBF +MQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dpc3NTaWduIEFHMR8wHQYDVQQDExZT +d2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC +CgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUqt2/8 +76LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+ +bbqBHH5CjCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c +6bM8K8vzARO/Ws/BtQpgvd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqE +emA8atufK+ze3gE/bk3lUIbLtK/tREDFylqM2tIrfKjuvqblCqoOpd8FUrdVxyJd +MmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvRAiTysybUa9oEVeXBCsdt +MDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuendjIj3o02y +MszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69y +FGkOpeUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPi +aG59je883WX0XaxR7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxM +gI93e2CaHt+28kgeDrpOVG2Y4OGiGqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCB +qTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUWyV7 +lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64OfPAeGZe6Drn +8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov +L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe6 +45R88a7A3hfm5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczO +UYrHUDFu4Up+GC9pWbY9ZIEr44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5 +O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOfMke6UiI0HTJ6CVanfCU2qT1L2sCC +bwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6mGu6uLftIdxf+u+yv +GPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxpmo/a +77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCC +hdiDyyJkvC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid3 +92qgQmwLOM7XdVAyksLfKzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEpp +Ld6leNcG2mqeSz53OiATIgHQv2ieY2BrNU0LbbqhPcCT4H8js1WtciVORvnSFu+w +ZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6LqjviOvrv1vA+ACOzB2+htt +Qc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ +-----END CERTIFICATE----- + +# Issuer: CN=SecureTrust CA O=SecureTrust Corporation +# Subject: CN=SecureTrust CA O=SecureTrust Corporation +# Label: "SecureTrust CA" +# Serial: 17199774589125277788362757014266862032 +# MD5 Fingerprint: dc:32:c3:a7:6d:25:57:c7:68:09:9d:ea:2d:a9:a2:d1 +# SHA1 Fingerprint: 87:82:c6:c3:04:35:3b:cf:d2:96:92:d2:59:3e:7d:44:d9:34:ff:11 +# SHA256 Fingerprint: f1:c1:b5:0a:e5:a2:0d:d8:03:0e:c9:f6:bc:24:82:3d:d3:67:b5:25:57:59:b4:e7:1b:61:fc:e9:f7:37:5d:73 +-----BEGIN CERTIFICATE----- +MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBI +MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x +FzAVBgNVBAMTDlNlY3VyZVRydXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIz +MTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENv +cnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQXOZEz +Zum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO +0gMdA+9tDWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIao +wW8xQmxSPmjL8xk037uHGFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj +7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b01k/unK8RCSc43Oz969XL0Imnal0ugBS +8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmHursCAwEAAaOBnTCBmjAT +BgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB +/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCeg +JYYjaHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGC +NxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt3 +6Z3q059c4EVlew3KW+JwULKUBRSuSceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/ +3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHfmbx8IVQr5Fiiu1cprp6poxkm +D5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZnMUFdAvnZyPS +CPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR +3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= +-----END CERTIFICATE----- + +# Issuer: CN=Secure Global CA O=SecureTrust Corporation +# Subject: CN=Secure Global CA O=SecureTrust Corporation +# Label: "Secure Global CA" +# Serial: 9751836167731051554232119481456978597 +# MD5 Fingerprint: cf:f4:27:0d:d4:ed:dc:65:16:49:6d:3d:da:bf:6e:de +# SHA1 Fingerprint: 3a:44:73:5a:e5:81:90:1f:24:86:61:46:1e:3b:9c:c4:5f:f5:3a:1b +# SHA256 Fingerprint: 42:00:f5:04:3a:c8:59:0e:bb:52:7d:20:9e:d1:50:30:29:fb:cb:d4:1c:a1:b5:06:ec:27:f1:5a:de:7d:ac:69 +-----BEGIN CERTIFICATE----- +MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBK +MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x +GTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkx +MjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3Qg +Q29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jxYDiJ +iQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa +/FHtaMbQbqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJ +jnIFHovdRIWCQtBJwB1g8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnI +HmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYVHDGA76oYa8J719rO+TMg1fW9ajMtgQT7 +sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi0XPnj3pDAgMBAAGjgZ0w +gZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCsw +KaAnoCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsG +AQQBgjcVAQQDAgEAMA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0L +URYD7xh8yOOvaliTFGCRsoTciE6+OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXO +H0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cnCDpOGR86p1hcF895P4vkp9Mm +I50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/53CYNv6ZHdAbY +iNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc +f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW +-----END CERTIFICATE----- + +# Issuer: CN=COMODO Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO Certification Authority O=COMODO CA Limited +# Label: "COMODO Certification Authority" +# Serial: 104350513648249232941998508985834464573 +# MD5 Fingerprint: 5c:48:dc:f7:42:72:ec:56:94:6d:1c:cc:71:35:80:75 +# SHA1 Fingerprint: 66:31:bf:9e:f7:4f:9e:b6:c9:d5:a6:0c:ba:6a:be:d1:f7:bd:ef:7b +# SHA256 Fingerprint: 0c:2c:d6:3d:f7:80:6f:a3:99:ed:e8:09:11:6b:57:5b:f8:79:89:f0:65:18:f9:80:8c:86:05:03:17:8b:af:66 +-----BEGIN CERTIFICATE----- +MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB +gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV +BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw +MDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl +YXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P +RE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3 +UcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI +2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8 +Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp ++2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+ +DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O +nKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW +/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g +PKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u +QXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY +SdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv +IC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ +RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4 +zJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd +BA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB +ZQ== +-----END CERTIFICATE----- + +# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited +# Label: "COMODO ECC Certification Authority" +# Serial: 41578283867086692638256921589707938090 +# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23 +# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11 +# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7 +-----BEGIN CERTIFICATE----- +MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL +MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE +BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT +IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw +MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy +ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N +T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR +FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J +cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW +BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm +fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv +GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= +-----END CERTIFICATE----- + +# Issuer: CN=Certigna O=Dhimyotis +# Subject: CN=Certigna O=Dhimyotis +# Label: "Certigna" +# Serial: 18364802974209362175 +# MD5 Fingerprint: ab:57:a6:5b:7d:42:82:19:b5:d8:58:26:28:5e:fd:ff +# SHA1 Fingerprint: b1:2e:13:63:45:86:a4:6f:1a:b2:60:68:37:58:2d:c4:ac:fd:94:97 +# SHA256 Fingerprint: e3:b6:a2:db:2e:d7:ce:48:84:2f:7a:c5:32:41:c7:b7:1d:54:14:4b:fb:40:c1:1f:3f:1d:0b:42:f5:ee:a1:2d +-----BEGIN CERTIFICATE----- +MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNV +BAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4X +DTA3MDYyOTE1MTMwNVoXDTI3MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQ +BgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwIQ2VydGlnbmEwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7qXOEm7RFHYeGifBZ4 +QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyHGxny +gQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbw +zBfsV1/pogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q +130yGLMLLGq/jj8UEYkgDncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2 +JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKfIrjxwo1p3Po6WAbfAgMBAAGjgbwwgbkw +DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQtCRZvgHyUtVF9lo53BEw +ZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJBgNVBAYT +AkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzj +AQ/JSP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG +9w0BAQUFAAOCAQEAhQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8h +bV6lUmPOEvjvKtpv6zf+EwLHyzs+ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFnc +fca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1kluPBS1xp81HlDQwY9qcEQCYsuu +HWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY1gkIl2PlwS6w +t0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw +WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg== +-----END CERTIFICATE----- + +# Issuer: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority +# Subject: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority +# Label: "ePKI Root Certification Authority" +# Serial: 28956088682735189655030529057352760477 +# MD5 Fingerprint: 1b:2e:00:ca:26:06:90:3d:ad:fe:6f:15:68:d3:6b:b3 +# SHA1 Fingerprint: 67:65:0d:f1:7e:8e:7e:5b:82:40:a4:f4:56:4b:cf:e2:3d:69:c6:f0 +# SHA256 Fingerprint: c0:a6:f4:dc:63:a2:4b:fd:cf:54:ef:2a:6a:08:2a:0a:72:de:35:80:3e:2f:f5:ff:52:7a:e5:d8:72:06:df:d5 +-----BEGIN CERTIFICATE----- +MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBe +MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 +ZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe +Fw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMxMjdaMF4xCzAJBgNVBAYTAlRXMSMw +IQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEqMCgGA1UECwwhZVBL +SSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAH +SyZbCUNsIZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAh +ijHyl3SJCRImHJ7K2RKilTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3X +DZoTM1PRYfl61dd4s5oz9wCGzh1NlDivqOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1 +TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX12ruOzjjK9SXDrkb5wdJ +fzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0OWQqraffA +sgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uU +WH1+ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLS +nT0IFaUQAS2zMnaolQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pH +dmX2Os+PYhcZewoozRrSgx4hxyy/vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJip +NiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXiZo1jDiVN1Rmy5nk3pyKdVDEC +AwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/QkqiMAwGA1UdEwQF +MAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH +ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGB +uvl2ICO1J2B01GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6Yl +PwZpVnPDimZI+ymBV3QGypzqKOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkP +JXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdVxrsStZf0X4OFunHB2WyBEXYKCrC/ +gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEPNXubrjlpC2JgQCA2 +j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+rGNm6 +5ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUB +o2M3IUxExJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS +/jQ6fbjpKdx2qcgw+BRxgMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2z +Gp1iro2C6pSe3VkQw63d4k3jMdXH7OjysP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTE +W9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmODBCEIZ43ygknQW/2xzQ+D +hNQ+IIX3Sj0rnP0qCglN6oH4EZw= +-----END CERTIFICATE----- + +# Issuer: O=certSIGN OU=certSIGN ROOT CA +# Subject: O=certSIGN OU=certSIGN ROOT CA +# Label: "certSIGN ROOT CA" +# Serial: 35210227249154 +# MD5 Fingerprint: 18:98:c0:d6:e9:3a:fc:f9:b0:f5:0c:f7:4b:01:44:17 +# SHA1 Fingerprint: fa:b7:ee:36:97:26:62:fb:2d:b0:2a:f6:bf:03:fd:e8:7c:4b:2f:9b +# SHA256 Fingerprint: ea:a9:62:c4:fa:4a:6b:af:eb:e4:15:19:6d:35:1c:cd:88:8d:4f:53:f3:fa:8a:e6:d7:c4:66:a9:4e:60:42:bb +-----BEGIN CERTIFICATE----- +MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYT +AlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBD +QTAeFw0wNjA3MDQxNzIwMDRaFw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJP +MREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7IJUqOtdu0KBuqV5Do +0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHHrfAQ +UySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5d +RdY4zTW2ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQ +OA7+j0xbm0bqQfWwCHTD0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwv +JoIQ4uNllAoEwF73XVv4EOLQunpL+943AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08C +AwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAcYwHQYDVR0O +BBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IBAQA+0hyJ +LjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecY +MnQ8SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ +44gx+FkagQnIl6Z0x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6I +Jd1hJyMctTEHBDa0GpC9oHRxUIltvBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNw +i/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7NzTogVZ96edhBiIL5VaZVDADlN +9u6wWk5JRFRYX0KD +-----END CERTIFICATE----- + +# Issuer: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) +# Subject: CN=NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny O=NetLock Kft. OU=Tan\xfas\xedtv\xe1nykiad\xf3k (Certification Services) +# Label: "NetLock Arany (Class Gold) F\u0151tan\xfas\xedtv\xe1ny" +# Serial: 80544274841616 +# MD5 Fingerprint: c5:a1:b7:ff:73:dd:d6:d7:34:32:18:df:fc:3c:ad:88 +# SHA1 Fingerprint: 06:08:3f:59:3f:15:a1:04:a0:69:a4:6b:a9:03:d0:06:b7:97:09:91 +# SHA256 Fingerprint: 6c:61:da:c3:a2:de:f0:31:50:6b:e0:36:d2:a6:fe:40:19:94:fb:d1:3d:f9:c8:d4:66:59:92:74:c4:46:ec:98 +-----BEGIN CERTIFICATE----- +MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG +EwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3 +MDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl +cnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR +dGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB +pzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM +b2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm +aWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz +IEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT +lF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz +AZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5 +VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG +ILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2 +BJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG +AQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M +U9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh +bvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C ++C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC +bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F +uLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2 +XjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= +-----END CERTIFICATE----- + +# Issuer: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. +# Subject: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd. +# Label: "Microsec e-Szigno Root CA 2009" +# Serial: 14014712776195784473 +# MD5 Fingerprint: f8:49:f4:03:bc:44:2d:83:be:48:69:7d:29:64:fc:b1 +# SHA1 Fingerprint: 89:df:74:fe:5c:f4:0f:4a:80:f9:e3:37:7d:54:da:91:e1:01:31:8e +# SHA256 Fingerprint: 3c:5f:81:fe:a5:fa:b8:2c:64:bf:a2:ea:ec:af:cd:e8:e0:77:fc:86:20:a7:ca:e5:37:16:3d:f3:6e:db:f3:78 +-----BEGIN CERTIFICATE----- +MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD +VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0 +ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G +CSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y +OTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx +FjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp +Z25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o +dTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP +kd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc +cbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U +fIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7 +N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC +xkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1 ++rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G +A1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM +Pcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG +SIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h +mLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk +ddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 +tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c +2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t +HMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3 +# Label: "GlobalSign Root CA - R3" +# Serial: 4835703278459759426209954 +# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28 +# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad +# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b +-----BEGIN CERTIFICATE----- +MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G +A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp +Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 +MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG +A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 +RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT +gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm +KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd +QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ +XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw +DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o +LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU +RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp +jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK +6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX +mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs +Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH +WD9f +-----END CERTIFICATE----- + +# Issuer: CN=Izenpe.com O=IZENPE S.A. +# Subject: CN=Izenpe.com O=IZENPE S.A. +# Label: "Izenpe.com" +# Serial: 917563065490389241595536686991402621 +# MD5 Fingerprint: a6:b0:cd:85:80:da:5c:50:34:a3:39:90:2f:55:67:73 +# SHA1 Fingerprint: 2f:78:3d:25:52:18:a7:4a:65:39:71:b5:2c:a2:9c:45:15:6f:e9:19 +# SHA256 Fingerprint: 25:30:cc:8e:98:32:15:02:ba:d9:6f:9b:1f:ba:1b:09:9e:2d:29:9e:0f:45:48:bb:91:4f:36:3b:c0:d4:53:1f +-----BEGIN CERTIFICATE----- +MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4 +MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6 +ZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD +VQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j +b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq +scIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO +xdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H +LmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX +uaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD +yCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+ +JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q +rLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN +BjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L +hij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB +QFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+ +HMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu +Zm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg +QTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB +BgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx +MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA +A4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb +laQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56 +awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo +JNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw +LDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT +VyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk +LhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb +UjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/ +QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+ +naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls +QyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== +-----END CERTIFICATE----- + +# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc. +# Label: "Go Daddy Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01 +# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b +# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT +EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp +ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz +NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH +EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE +AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD +E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH +/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy +DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh +GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR +tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA +AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX +WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu +9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr +gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo +2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO +LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI +4uJEvlz36hz1 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96 +# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e +# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5 +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs +ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw +MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 +b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj +aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp +Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg +nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1 +HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N +Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN +dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0 +HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO +BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G +CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU +sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3 +4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg +8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K +pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1 +mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 +-----END CERTIFICATE----- + +# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc. +# Label: "Starfield Services Root Certificate Authority - G2" +# Serial: 0 +# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2 +# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f +# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5 +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx +EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT +HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs +ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 +MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD +VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy +ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy +dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p +OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2 +8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K +Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe +hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk +6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw +DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q +AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI +bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB +ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z +qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd +iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn +0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN +sSi6 +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Network CA" +# Serial: 279744 +# MD5 Fingerprint: d5:e9:81:40:c5:18:69:fc:46:2c:89:75:62:0f:aa:78 +# SHA1 Fingerprint: 07:e0:32:e0:20:b7:2c:3f:19:2f:06:28:a2:59:3a:19:a7:0f:06:9e +# SHA256 Fingerprint: 5c:58:46:8d:55:f5:8e:49:7e:74:39:82:d2:b5:00:10:b6:d1:65:37:4a:cf:83:a7:d4:a3:2d:b7:68:c4:40:8e +-----BEGIN CERTIFICATE----- +MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM +MSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D +ZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU +cnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3 +WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg +Uy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw +IAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH +UV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM +TXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU +BBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM +kUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x +AcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV +HQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y +sHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL +I9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8 +J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY +VoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI +03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= +-----END CERTIFICATE----- + +# Issuer: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA +# Subject: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA +# Label: "TWCA Root Certification Authority" +# Serial: 1 +# MD5 Fingerprint: aa:08:8f:f6:f9:7b:b7:f2:b1:a7:1e:9b:ea:ea:bd:79 +# SHA1 Fingerprint: cf:9e:87:6d:d3:eb:fc:42:26:97:a3:b5:a3:7a:a0:76:a9:06:23:48 +# SHA256 Fingerprint: bf:d8:8f:e1:10:1c:41:ae:3e:80:1b:f8:be:56:35:0e:e9:ba:d1:a6:b9:bd:51:5e:dc:5c:6d:5b:87:11:ac:44 +-----BEGIN CERTIFICATE----- +MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES +MBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU +V0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz +WhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO +LUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm +aWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE +AcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH +K3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX +RfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z +rX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx +3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq +hkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC +MErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls +XebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D +lhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn +aspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ +YiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== +-----END CERTIFICATE----- + +# Issuer: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 +# Subject: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2 +# Label: "Security Communication RootCA2" +# Serial: 0 +# MD5 Fingerprint: 6c:39:7d:a4:0e:55:59:b2:3f:d6:41:b1:12:50:de:43 +# SHA1 Fingerprint: 5f:3b:8c:f2:f8:10:b3:7d:78:b4:ce:ec:19:19:c3:73:34:b9:c7:74 +# SHA256 Fingerprint: 51:3b:2c:ec:b8:10:d4:cd:e5:dd:85:39:1a:df:c6:c2:dd:60:d8:7b:b7:36:d2:b5:21:48:4a:a4:7a:0e:be:f6 +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl +MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe +U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX +DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy +dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj +YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV +OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr +zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM +VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ +hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO +ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw +awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs +OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3 +DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF +coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc +okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8 +t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy +1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/ +SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 +-----END CERTIFICATE----- + +# Issuer: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 +# Subject: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967 +# Label: "Actalis Authentication Root CA" +# Serial: 6271844772424770508 +# MD5 Fingerprint: 69:c1:0d:4f:07:a3:1b:c3:fe:56:3d:04:bc:11:f6:a6 +# SHA1 Fingerprint: f3:73:b3:87:06:5a:28:84:8a:f2:f3:4a:ce:19:2b:dd:c7:8e:9c:ac +# SHA256 Fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66 +-----BEGIN CERTIFICATE----- +MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE +BhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w +MzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 +IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC +SVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1 +ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv +UTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX +4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9 +KK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/ +gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb +rxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ +51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F +be8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe +KF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F +v6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn +fpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7 +jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz +ezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt +ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL +e3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70 +jsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz +WochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V +SM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j +pwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX +X04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok +fcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R +K4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU +ZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU +LysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT +LnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== +-----END CERTIFICATE----- + +# Issuer: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 +# Subject: CN=Buypass Class 2 Root CA O=Buypass AS-983163327 +# Label: "Buypass Class 2 Root CA" +# Serial: 2 +# MD5 Fingerprint: 46:a7:d2:fe:45:fb:64:5a:a8:59:90:9b:78:44:9b:29 +# SHA1 Fingerprint: 49:0a:75:74:de:87:0a:47:fe:58:ee:f6:c7:6b:eb:c6:0b:12:40:99 +# SHA256 Fingerprint: 9a:11:40:25:19:7c:5b:b9:5d:94:e6:3d:55:cd:43:79:08:47:b6:46:b2:3c:df:11:ad:a4:a0:0e:ff:15:fb:48 +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd +MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg +Q2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow +TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw +HgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB +BQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr +6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV +L4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91 +1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx +MlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ +QmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB +arcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr +Us3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi +FRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS +P/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN +9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP +AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz +uvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h +9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s +A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t +OluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo ++fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7 +KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2 +DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us +H8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ +I+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7 +5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h +3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz +Y11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA= +-----END CERTIFICATE----- + +# Issuer: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 +# Subject: CN=Buypass Class 3 Root CA O=Buypass AS-983163327 +# Label: "Buypass Class 3 Root CA" +# Serial: 2 +# MD5 Fingerprint: 3d:3b:18:9e:2c:64:5a:e8:d5:88:ce:0e:f9:37:c2:ec +# SHA1 Fingerprint: da:fa:f7:fa:66:84:ec:06:8f:14:50:bd:c7:c2:81:a5:bc:a9:64:57 +# SHA256 Fingerprint: ed:f7:eb:bc:a2:7a:2a:38:4d:38:7b:7d:40:10:c6:66:e2:ed:b4:84:3e:4c:29:b4:ae:1d:5b:93:32:e6:b2:4d +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd +MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg +Q2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow +TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw +HgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB +BQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y +ZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E +N3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9 +tznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX +0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c +/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X +KhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY +zIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS +O1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D +34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP +K9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3 +AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv +Tg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj +QTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV +cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS +IGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2 +HJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa +O5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv +033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u +dmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE +kbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41 +3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD +u79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq +4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc= +-----END CERTIFICATE----- + +# Issuer: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Subject: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Label: "T-TeleSec GlobalRoot Class 3" +# Serial: 1 +# MD5 Fingerprint: ca:fb:40:a8:4e:39:92:8a:1d:fe:8e:2f:c4:27:ea:ef +# SHA1 Fingerprint: 55:a6:72:3e:cb:f2:ec:cd:c3:23:74:70:19:9d:2a:be:11:e3:81:d1 +# SHA256 Fingerprint: fd:73:da:d3:1c:64:4f:f1:b4:3b:ef:0c:cd:da:96:71:0b:9c:d9:87:5e:ca:7e:31:70:7a:f3:e9:6d:52:2b:bd +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx +KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd +BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl +YyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1 +OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy +aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 +ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN +8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/ +RLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4 +hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5 +ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM +EnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1 +A/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy +WL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ +1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30 +6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT +91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml +e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p +TpPDpFQUWw== +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH +# Subject: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH +# Label: "D-TRUST Root Class 3 CA 2 2009" +# Serial: 623603 +# MD5 Fingerprint: cd:e0:25:69:8d:47:ac:9c:89:35:90:f7:fd:51:3d:2f +# SHA1 Fingerprint: 58:e8:ab:b0:36:15:33:fb:80:f7:9b:1b:6d:29:d3:ff:8d:5f:00:f0 +# SHA256 Fingerprint: 49:e7:a4:42:ac:f0:ea:62:87:05:00:54:b5:25:64:b6:50:e4:f4:9e:42:e3:48:d6:aa:38:e0:39:e9:57:b1:c1 +-----BEGIN CERTIFICATE----- +MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF +MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD +bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha +ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM +HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03 +UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42 +tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R +ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM +lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp +/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G +A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G +A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj +dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy +MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl +cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js +L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL +BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni +acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 +o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K +zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8 +PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y +Johw1+qRzT65ysCQblrGXnRl11z+o+I= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH +# Subject: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH +# Label: "D-TRUST Root Class 3 CA 2 EV 2009" +# Serial: 623604 +# MD5 Fingerprint: aa:c6:43:2c:5e:2d:cd:c4:34:c0:50:4f:11:02:4f:b6 +# SHA1 Fingerprint: 96:c9:1b:0b:95:b4:10:98:42:fa:d0:d8:22:79:fe:60:fa:b9:16:83 +# SHA256 Fingerprint: ee:c5:49:6b:98:8c:e9:86:25:b9:34:09:2e:ec:29:08:be:d0:b0:f3:16:c2:d4:73:0c:84:ea:f1:f3:d3:48:81 +-----BEGIN CERTIFICATE----- +MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF +MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD +bGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw +NDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV +BAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn +ljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0 +3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z +qQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR +p75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8 +HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw +ggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea +HNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw +Oi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh +c3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E +RT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt +dHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku +Y3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp +3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 +nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF +CSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na +xpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX +KVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1 +-----END CERTIFICATE----- + +# Issuer: CN=CA Disig Root R2 O=Disig a.s. +# Subject: CN=CA Disig Root R2 O=Disig a.s. +# Label: "CA Disig Root R2" +# Serial: 10572350602393338211 +# MD5 Fingerprint: 26:01:fb:d8:27:a7:17:9a:45:54:38:1a:43:01:3b:03 +# SHA1 Fingerprint: b5:61:eb:ea:a4:de:e4:25:4b:69:1a:98:a5:57:47:c2:34:c7:d9:71 +# SHA256 Fingerprint: e2:3d:4a:03:6d:7b:70:e9:f5:95:b1:42:20:79:d2:b9:1e:df:bb:1f:b6:51:a0:63:3e:aa:8a:9d:c5:f8:07:03 +-----BEGIN CERTIFICATE----- +MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV +BAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu +MRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy +MDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx +EzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw +ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe +NcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH +PWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I +x2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe +QTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR +yyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO +QG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912 +H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ +QfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD +i/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs +nLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1 +rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud +DwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI +hvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM +tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf +GopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb +lvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka ++elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal +TFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i +nSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3 +gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr +G5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os +zMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x +L4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL +-----END CERTIFICATE----- + +# Issuer: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV +# Subject: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV +# Label: "ACCVRAIZ1" +# Serial: 6828503384748696800 +# MD5 Fingerprint: d0:a0:5a:ee:05:b6:09:94:21:a1:7d:f1:b2:29:82:02 +# SHA1 Fingerprint: 93:05:7a:88:15:c6:4f:ce:88:2f:fa:91:16:52:28:78:bc:53:64:17 +# SHA256 Fingerprint: 9a:6e:c0:12:e1:a7:da:9d:be:34:19:4d:47:8a:d7:c0:db:18:22:fb:07:1d:f1:29:81:49:6e:d1:04:38:41:13 +-----BEGIN CERTIFICATE----- +MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE +AwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw +CQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ +BgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND +VjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb +qau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY +HtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo +G2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA +lHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr +IA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/ +0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH +k6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47 +4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO +m3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa +cXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl +uUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI +KwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls +ZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG +AQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 +VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT +VfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG +CCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA +cgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA +QwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA +7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA +cgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA +QwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA +czAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu +aHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt +aW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud +DwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF +BQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp +D70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU +JyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m +AM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD +vV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms +tn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH +7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h +I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA +h1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF +d3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H +pPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7 +-----END CERTIFICATE----- + +# Issuer: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA +# Subject: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA +# Label: "TWCA Global Root CA" +# Serial: 3262 +# MD5 Fingerprint: f9:03:7e:cf:e6:9e:3c:73:7a:2a:90:07:69:ff:2b:96 +# SHA1 Fingerprint: 9c:bb:48:53:f6:a4:f6:d3:52:a4:e8:32:52:55:60:13:f5:ad:af:65 +# SHA256 Fingerprint: 59:76:90:07:f7:68:5d:0f:cd:50:87:2f:9f:95:d5:75:5a:5b:2b:45:7d:81:f3:69:2b:61:0a:98:67:2f:0e:1b +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx +EjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT +VFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5 +NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT +B1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF +10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz +0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh +MBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH +zIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc +46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2 +yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi +laLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP +oA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA +BDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE +qYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm +4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL +1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn +LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF +H6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo +RI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+ +nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh +15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW +6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW +nsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j +wa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz +aGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy +KwbQBM0= +-----END CERTIFICATE----- + +# Issuer: CN=TeliaSonera Root CA v1 O=TeliaSonera +# Subject: CN=TeliaSonera Root CA v1 O=TeliaSonera +# Label: "TeliaSonera Root CA v1" +# Serial: 199041966741090107964904287217786801558 +# MD5 Fingerprint: 37:41:49:1b:18:56:9a:26:f5:ad:c2:66:fb:40:a5:4c +# SHA1 Fingerprint: 43:13:bb:96:f1:d5:86:9b:c1:4e:6a:92:f6:cf:f6:34:69:87:82:37 +# SHA256 Fingerprint: dd:69:36:fe:21:f8:f0:77:c1:23:a1:a5:21:c1:22:24:f7:22:55:b7:3e:03:a7:26:06:93:e8:a2:4b:0f:a3:89 +-----BEGIN CERTIFICATE----- +MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAw +NzEUMBIGA1UECgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJv +b3QgQ0EgdjEwHhcNMDcxMDE4MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYD +VQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwWVGVsaWFTb25lcmEgUm9vdCBDQSB2 +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+6yfwIaPzaSZVfp3F +VRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA3GV1 +7CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+X +Z75Ljo1kB1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+ +/jXh7VB7qTCNGdMJjmhnXb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs +81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxHoLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkm +dtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3F0fUTPHSiXk+TT2YqGHe +Oh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJoWjiUIMu +sDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4 +pgd7gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fs +slESl1MpWtTwEhDcTwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQ +arMCpgKIv7NHfirZ1fpoeDVNAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYD +VR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qWDNXr+nuqF+gTEjANBgkqhkiG +9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNmzqjMDfz1mgbl +dxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx +0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1Tj +TQpgcmLNkQfWpb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBed +Y2gea+zDTYa4EzAvXUYNR0PVG6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7 +Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpcc41teyWRyu5FrgZLAMzTsVlQ2jqI +OylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOTJsjrDNYmiLbAJM+7 +vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2qReW +t88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcn +HL/EVlP6Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVx +SK236thZiNSQvxaz2emsWWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= +-----END CERTIFICATE----- + +# Issuer: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Subject: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center +# Label: "T-TeleSec GlobalRoot Class 2" +# Serial: 1 +# MD5 Fingerprint: 2b:9b:9e:e4:7b:6c:1f:00:72:1a:cc:c1:77:79:df:6a +# SHA1 Fingerprint: 59:0d:2d:7d:88:4f:40:2e:61:7e:a5:62:32:17:65:cf:17:d8:94:e9 +# SHA256 Fingerprint: 91:e2:f5:78:8d:58:10:eb:a7:ba:58:73:7d:e1:54:8a:8e:ca:cd:01:45:98:bc:0b:14:3e:04:1b:17:05:25:52 +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx +KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd +BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl +YyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1 +OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy +aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 +ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd +AqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC +FoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi +1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq +jnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ +wI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/ +WSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy +NsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC +uvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw +IEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6 +g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN +9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP +BSeOE6Fuwg== +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot 2011 O=Atos +# Subject: CN=Atos TrustedRoot 2011 O=Atos +# Label: "Atos TrustedRoot 2011" +# Serial: 6643877497813316402 +# MD5 Fingerprint: ae:b9:c4:32:4b:ac:7f:5d:66:cc:77:94:bb:2a:77:56 +# SHA1 Fingerprint: 2b:b1:f5:3e:55:0c:1d:c5:f1:d4:e6:b7:6a:46:4b:55:06:02:ac:21 +# SHA256 Fingerprint: f3:56:be:a2:44:b7:a9:1e:b3:5d:53:ca:9a:d7:86:4a:ce:01:8e:2d:35:d5:f8:f9:6d:df:68:a6:f4:1a:a4:74 +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UE +AwwVQXRvcyBUcnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQG +EwJERTAeFw0xMTA3MDcxNDU4MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMM +FUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMC +REUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVhTuXbyo7LjvPpvMp +Nb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr54rM +VD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+ +SZFhyBH+DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ +4J7sVaE3IqKHBAUsR320HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0L +cp2AMBYHlT8oDv3FdU9T1nSatCQujgKRz3bFmx5VdJx4IbHwLfELn8LVlhgf8FQi +eowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7Rl+lwrrw7GWzbITAPBgNV +HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZbNshMBgG +A1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3 +DQEBCwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8j +vZfza1zv7v1Apt+hk6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kP +DpFrdRbhIfzYJsdHt6bPWHJxfrrhTZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pc +maHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a961qn8FYiqTxlVMYVqL2Gns2D +lmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G3mB/ufNPRJLv +KrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 1 G3" +# Serial: 687049649626669250736271037606554624078720034195 +# MD5 Fingerprint: a4:bc:5b:3f:fe:37:9a:fa:64:f0:e2:fa:05:3d:0b:ab +# SHA1 Fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67 +# SHA256 Fingerprint: 8a:86:6f:d1:b2:76:b5:7e:57:8e:92:1c:65:82:8a:2b:ed:58:e9:f2:f2:88:05:41:34:b7:f1:f4:bf:c9:cc:74 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00 +MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV +wedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe +rNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341 +68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh +4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp +UhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o +abw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc +3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G +KubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt +hfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO +Tk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt +zCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD +ggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC +MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2 +cDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN +qXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5 +YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv +b2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2 +8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k +NSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj +ZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp +q1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt +nh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 2 G3" +# Serial: 390156079458959257446133169266079962026824725800 +# MD5 Fingerprint: af:0c:86:6e:bf:40:2d:7f:0b:3e:12:50:ba:12:3d:06 +# SHA1 Fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36 +# SHA256 Fingerprint: 8f:e4:fb:0a:f9:3a:4d:0d:67:db:0b:eb:b2:3e:37:c7:1b:f3:25:dc:bc:dd:24:0e:a0:4d:af:58:b4:7e:18:40 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00 +MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf +qq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW +n4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym +c5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+ +O7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1 +o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j +IaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq +IcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz +8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh +vNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l +7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG +cC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD +ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66 +AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC +roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga +W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n +lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE ++V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV +csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd +dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg +KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM +HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4 +WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M +-----END CERTIFICATE----- + +# Issuer: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited +# Subject: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited +# Label: "QuoVadis Root CA 3 G3" +# Serial: 268090761170461462463995952157327242137089239581 +# MD5 Fingerprint: df:7d:b9:ad:54:6f:68:a1:df:89:57:03:97:43:b0:d7 +# SHA1 Fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d +# SHA256 Fingerprint: 88:ef:81:de:20:2e:b0:18:45:2e:43:f8:64:72:5c:ea:5f:bd:1f:c2:d9:d2:05:73:07:09:c5:d8:b8:69:0f:46 +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL +BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc +BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00 +MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR +/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu +FoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR +U7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c +ra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR +FHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k +A9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw +eyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl +sSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp +VzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q +A4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+ +ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD +ggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px +KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI +FUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv +oxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg +u/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP +0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf +3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl +8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+ +DhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN +PlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/ +ywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0 +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root G2" +# Serial: 15385348160840213938643033620894905419 +# MD5 Fingerprint: 92:38:b9:f8:63:24:82:65:2c:57:33:e6:fe:81:8f:9d +# SHA1 Fingerprint: a1:4b:48:d9:43:ee:0a:0e:40:90:4f:3c:e0:a4:c0:91:93:51:5d:3f +# SHA256 Fingerprint: 7d:05:eb:b6:82:33:9f:8c:94:51:ee:09:4e:eb:fe:fa:79:53:a1:14:ed:b2:f4:49:49:45:2f:ab:7d:2f:c1:85 +-----BEGIN CERTIFICATE----- +MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv +b3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl +cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA +n61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc +biJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp +EgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA +bx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu +YjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB +AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW +BBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI +QW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I +0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni +lmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9 +B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv +ON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo +IhNzbM8m9Yop5w== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Assured ID Root G3" +# Serial: 15459312981008553731928384953135426796 +# MD5 Fingerprint: 7c:7f:65:31:0c:81:df:8d:ba:3e:99:e2:5c:ad:6e:fb +# SHA1 Fingerprint: f5:17:a2:4f:9a:48:c6:c9:f8:a2:00:26:9f:dc:0f:48:2c:ab:30:89 +# SHA256 Fingerprint: 7e:37:cb:8b:4c:47:09:0c:ab:36:55:1b:a6:f4:5d:b8:40:68:0f:ba:16:6a:95:2d:b1:00:71:7f:43:05:3f:c2 +-----BEGIN CERTIFICATE----- +MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw +CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu +ZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg +RzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu +Y29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf +Zn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q +RSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ +BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD +AwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY +JjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv +6pZjamVFkpUBtA== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root G2" +# Serial: 4293743540046975378534879503202253541 +# MD5 Fingerprint: e4:a6:8a:c8:54:ac:52:42:46:0a:fd:72:48:1b:2a:44 +# SHA1 Fingerprint: df:3c:24:f9:bf:d6:66:76:1b:26:80:73:fe:06:d1:cc:8d:4f:82:a4 +# SHA256 Fingerprint: cb:3c:cb:b7:60:31:e5:e0:13:8f:8d:d3:9a:23:f9:de:47:ff:c3:5e:43:c1:14:4c:ea:27:d4:6a:5a:b1:cb:5f +-----BEGIN CERTIFICATE----- +MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH +MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT +MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j +b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI +2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx +1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ +q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz +tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ +vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV +5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY +1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4 +NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG +Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91 +8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe +pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl +MrY= +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Global Root G3" +# Serial: 7089244469030293291760083333884364146 +# MD5 Fingerprint: f5:5d:a4:50:a5:fb:28:7e:1e:0f:0d:cc:96:57:56:ca +# SHA1 Fingerprint: 7e:04:de:89:6a:3e:66:6d:00:e6:87:d3:3f:fa:d9:3b:e8:3d:34:9e +# SHA256 Fingerprint: 31:ad:66:48:f8:10:41:38:c7:38:f3:9e:a4:32:01:33:39:3e:3a:18:cc:02:29:6e:f9:7c:2a:c9:ef:67:31:d0 +-----BEGIN CERTIFICATE----- +MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw +CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu +ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe +Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw +EwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x +IDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF +K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG +fp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO +Z9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd +BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx +AK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/ +oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8 +sycX +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com +# Subject: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com +# Label: "DigiCert Trusted Root G4" +# Serial: 7451500558977370777930084869016614236 +# MD5 Fingerprint: 78:f2:fc:aa:60:1f:2f:b4:eb:c9:37:ba:53:2e:75:49 +# SHA1 Fingerprint: dd:fb:16:cd:49:31:c9:73:a2:03:7d:3f:c8:3a:4d:7d:77:5d:05:e4 +# SHA256 Fingerprint: 55:2f:7b:dc:f1:a7:af:9e:6c:e6:72:01:7f:4f:12:ab:f7:72:40:c7:8e:76:1a:c2:03:d1:d9:d2:0a:c8:99:88 +-----BEGIN CERTIFICATE----- +MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg +RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu +Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y +ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If +xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV +ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO +DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ +jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/ +CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi +EhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM +fRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY +uKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK +chYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t +9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB +hjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD +ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2 +SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd ++SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc +fFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa +sjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N +cCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N +0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie +4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI +r/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1 +/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm +gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+ +-----END CERTIFICATE----- + +# Issuer: CN=COMODO RSA Certification Authority O=COMODO CA Limited +# Subject: CN=COMODO RSA Certification Authority O=COMODO CA Limited +# Label: "COMODO RSA Certification Authority" +# Serial: 101909084537582093308941363524873193117 +# MD5 Fingerprint: 1b:31:b0:71:40:36:cc:14:36:91:ad:c4:3e:fd:ec:18 +# SHA1 Fingerprint: af:e5:d2:44:a8:d1:19:42:30:ff:47:9f:e2:f8:97:bb:cd:7a:8c:b4 +# SHA256 Fingerprint: 52:f0:e1:c4:e5:8e:c6:29:29:1b:60:31:7f:07:46:71:b8:5d:7e:a8:0d:5b:07:27:34:63:53:4b:32:b4:02:34 +-----BEGIN CERTIFICATE----- +MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB +hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G +A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV +BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5 +MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT +EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR +Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR +6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X +pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC +9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV +/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf +Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z ++pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w +qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah +SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC +u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf +Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq +crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E +FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB +/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl +wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM +4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV +2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna +FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ +CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK +boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke +jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL +S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb +QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl +0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB +NVOFBkpdn627G190 +-----END CERTIFICATE----- + +# Issuer: CN=USERTrust RSA Certification Authority O=The USERTRUST Network +# Subject: CN=USERTrust RSA Certification Authority O=The USERTRUST Network +# Label: "USERTrust RSA Certification Authority" +# Serial: 2645093764781058787591871645665788717 +# MD5 Fingerprint: 1b:fe:69:d1:91:b7:19:33:a3:72:a8:0f:e1:55:e5:b5 +# SHA1 Fingerprint: 2b:8f:1b:57:33:0d:bb:a2:d0:7a:6c:51:f7:0e:e9:0d:da:b9:ad:8e +# SHA256 Fingerprint: e7:93:c9:b0:2f:d8:aa:13:e2:1c:31:22:8a:cc:b0:81:19:64:3b:74:9c:89:89:64:b1:74:6d:46:c3:d4:cb:d2 +-----BEGIN CERTIFICATE----- +MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB +iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl +cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV +BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw +MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV +BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU +aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy +dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK +AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B +3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY +tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ +Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 +VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT +79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 +c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT +Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l +c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee +UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE +Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd +BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G +A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF +Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO +VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 +ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs +8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR +iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze +Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ +XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ +qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB +VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB +L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG +jjxDah2nGN59PRbxYvnKkKj9 +-----END CERTIFICATE----- + +# Issuer: CN=USERTrust ECC Certification Authority O=The USERTRUST Network +# Subject: CN=USERTrust ECC Certification Authority O=The USERTRUST Network +# Label: "USERTrust ECC Certification Authority" +# Serial: 123013823720199481456569720443997572134 +# MD5 Fingerprint: fa:68:bc:d9:b5:7f:ad:fd:c9:1d:06:83:28:cc:24:c1 +# SHA1 Fingerprint: d1:cb:ca:5d:b2:d5:2a:7f:69:3b:67:4d:e5:f0:5a:1d:0c:95:7d:f0 +# SHA256 Fingerprint: 4f:f4:60:d5:4b:9c:86:da:bf:bc:fc:57:12:e0:40:0d:2b:ed:3f:bc:4d:4f:bd:aa:86:e0:6a:dc:d2:a9:ad:7a +-----BEGIN CERTIFICATE----- +MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL +MAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl +eSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT +JVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx +MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT +Ck5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg +VVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm +aWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo +I+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng +o4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G +A1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB +zzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW +RNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg= +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5 +# Label: "GlobalSign ECC Root CA - R5" +# Serial: 32785792099990507226680698011560947931244 +# MD5 Fingerprint: 9f:ad:3b:1c:02:1e:8a:ba:17:74:38:81:0c:a2:bc:08 +# SHA1 Fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa +# SHA256 Fingerprint: 17:9f:bc:14:8a:3d:d0:0f:d2:4e:a1:34:58:cc:43:bf:a7:f5:9c:81:82:d7:83:a5:13:f6:eb:ec:10:0c:89:24 +-----BEGIN CERTIFICATE----- +MIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk +MCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH +bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX +DTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD +QSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu +MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc +8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke +hOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI +KoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg +515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO +xwy8p2Fp8fc74SrL+SvzZpA3 +-----END CERTIFICATE----- + +# Issuer: CN=IdenTrust Commercial Root CA 1 O=IdenTrust +# Subject: CN=IdenTrust Commercial Root CA 1 O=IdenTrust +# Label: "IdenTrust Commercial Root CA 1" +# Serial: 13298821034946342390520003877796839426 +# MD5 Fingerprint: b3:3e:77:73:75:ee:a0:d3:e3:7e:49:63:49:59:bb:c7 +# SHA1 Fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25 +# SHA256 Fingerprint: 5d:56:49:9b:e4:d2:e0:8b:cf:ca:d0:8a:3e:38:72:3d:50:50:3b:de:70:69:48:e4:2f:55:60:30:19:e5:28:ae +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu +VHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw +MTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw +JQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT +3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU ++ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp +S0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1 +bVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi +T0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL +vYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK +Vsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK +dHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT +c+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv +l7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N +iGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB +/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD +ggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH +6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt +LRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93 +nAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3 ++wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK +W2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT +AwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq +l1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG +4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ +mUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A +7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H +-----END CERTIFICATE----- + +# Issuer: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust +# Subject: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust +# Label: "IdenTrust Public Sector Root CA 1" +# Serial: 13298821034946342390521976156843933698 +# MD5 Fingerprint: 37:06:a5:b0:fc:89:9d:ba:f4:6b:8c:1a:64:cd:d5:ba +# SHA1 Fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd +# SHA256 Fingerprint: 30:d0:89:5a:9a:44:8a:26:20:91:63:55:22:d1:f5:20:10:b5:86:7a:ca:e1:2c:78:ef:95:8f:d4:f4:38:9f:2f +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu +VHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN +MzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0 +MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7 +ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy +RBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS +bdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF +/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R +3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw +EUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy +9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V +GxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ +2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV +WaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD +W/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN +AQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj +t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV +DRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9 +TaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G +lwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW +mhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df +WN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5 ++bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ +tshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA +GaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv +8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c +-----END CERTIFICATE----- + +# Issuer: CN=CFCA EV ROOT O=China Financial Certification Authority +# Subject: CN=CFCA EV ROOT O=China Financial Certification Authority +# Label: "CFCA EV ROOT" +# Serial: 407555286 +# MD5 Fingerprint: 74:e1:b6:ed:26:7a:7a:44:30:33:94:ab:7b:27:81:30 +# SHA1 Fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83 +# SHA256 Fingerprint: 5c:c3:d7:8e:4e:1d:5e:45:54:7a:04:e6:87:3e:64:f9:0c:f9:53:6d:1c:cc:2e:f8:00:f3:55:c4:c5:fd:70:fd +-----BEGIN CERTIFICATE----- +MIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD +TjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y +aXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx +MjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j +aWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP +T1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03 +sQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL +TIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5 +/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp +7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz +EpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt +hxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP +a931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot +aK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg +TnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV +PKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv +cWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL +tbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd +BgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB +ACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT +ej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL +jOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS +ESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy +P5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19 +xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d +Ci77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN +5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe +/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z +AAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ +5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su +-----END CERTIFICATE----- + +# Issuer: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed +# Subject: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed +# Label: "OISTE WISeKey Global Root GB CA" +# Serial: 157768595616588414422159278966750757568 +# MD5 Fingerprint: a4:eb:b9:61:28:2e:b7:2f:98:b0:35:26:90:99:51:1d +# SHA1 Fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed +# SHA256 Fingerprint: 6b:9c:08:e8:6e:b0:f7:67:cf:ad:65:cd:98:b6:21:49:e5:49:4a:67:f5:84:5e:7b:d1:ed:01:9f:27:b8:6b:d6 +-----BEGIN CERTIFICATE----- +MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt +MQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg +Rm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i +YWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x +CzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG +b3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh +bCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3 +HEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx +WuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX +1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk +u7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P +99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r +M2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB +BAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh +cViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5 +gSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO +ZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf +aPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic +Nc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM= +-----END CERTIFICATE----- + +# Issuer: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. +# Subject: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A. +# Label: "SZAFIR ROOT CA2" +# Serial: 357043034767186914217277344587386743377558296292 +# MD5 Fingerprint: 11:64:c1:89:b0:24:b1:8c:b1:07:7e:89:9e:51:9e:99 +# SHA1 Fingerprint: e2:52:fa:95:3f:ed:db:24:60:bd:6e:28:f3:9c:cc:cf:5e:b3:3f:de +# SHA256 Fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe +-----BEGIN CERTIFICATE----- +MIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL +BQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6 +ZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw +NzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L +cmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg +Uk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN +QLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT +3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw +3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6 +3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5 +BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN +XGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF +AAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw +8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG +nXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP +oky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy +d05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg +LvWpCz/UXeHPhJ/iGcJfitYgHuNztw== +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Network CA 2" +# Serial: 44979900017204383099463764357512596969 +# MD5 Fingerprint: 6d:46:9e:d9:25:6d:08:23:5b:5e:74:7d:1e:27:db:f2 +# SHA1 Fingerprint: d3:dd:48:3e:2b:bf:4c:05:e8:af:10:f5:fa:76:26:cf:d3:dc:30:92 +# SHA256 Fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 +-----BEGIN CERTIFICATE----- +MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB +gDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu +QS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG +A1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz +OTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ +VW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3 +b3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA +DGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn +0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB +OJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE +fktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E +Sv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m +o130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i +sx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW +OZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez +Tv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS +adgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n +3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC +AQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ +F/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf +CVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29 +XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm +djWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/ +WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb +AoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq +P/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko +b7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj +XALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P +5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi +DrW5viSP +-----END CERTIFICATE----- + +# Issuer: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Subject: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Label: "Hellenic Academic and Research Institutions RootCA 2015" +# Serial: 0 +# MD5 Fingerprint: ca:ff:e2:db:03:d9:cb:4b:e9:0f:ad:84:fd:7b:18:ce +# SHA1 Fingerprint: 01:0c:06:95:a6:98:19:14:ff:bf:5f:c6:b0:b6:95:ea:29:e9:12:a6 +# SHA256 Fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:45:fe:0b:2a:69:2b:cd:52:52:3f:36 +-----BEGIN CERTIFICATE----- +MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix +DzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k +IFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT +N0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v +dENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG +A1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh +ZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx +QDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1 +dGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC +AQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA +4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0 +AoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10 +4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C +ojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV +9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD +gfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6 +Y5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq +NhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko +LfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc +Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd +ctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I +XtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI +M4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot +9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V +Z5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea +j8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh +X9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ +l033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf +bzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4 +pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK +e7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0 +vm9qp/UsQu0yrbYhnr68 +-----END CERTIFICATE----- + +# Issuer: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Subject: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority +# Label: "Hellenic Academic and Research Institutions ECC RootCA 2015" +# Serial: 0 +# MD5 Fingerprint: 81:e5:b4:17:eb:c2:f5:e1:4b:0d:41:7b:49:92:fe:ef +# SHA1 Fingerprint: 9f:f1:71:8d:92:d5:9a:f3:7d:74:97:b4:bc:6f:84:68:0b:ba:b6:66 +# SHA256 Fingerprint: 44:b5:45:aa:8a:25:e6:5a:73:ca:15:dc:27:fc:36:d2:4c:1c:b9:95:3a:06:65:39:b1:15:82:dc:48:7b:48:33 +-----BEGIN CERTIFICATE----- +MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN +BgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl +c2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl +bGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv +b3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ +BgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj +YWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5 +MUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0 +dXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg +QehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa +jq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi +C4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep +lSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof +TUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR +-----END CERTIFICATE----- + +# Issuer: CN=ISRG Root X1 O=Internet Security Research Group +# Subject: CN=ISRG Root X1 O=Internet Security Research Group +# Label: "ISRG Root X1" +# Serial: 172886928669790476064670243504169061120 +# MD5 Fingerprint: 0c:d2:f9:e0:da:17:73:e9:ed:86:4d:a5:e3:70:e7:4e +# SHA1 Fingerprint: ca:bd:2a:79:a1:07:6a:31:f2:1d:25:36:35:cb:03:9d:43:29:a5:e8 +# SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- + +# Issuer: O=FNMT-RCM OU=AC RAIZ FNMT-RCM +# Subject: O=FNMT-RCM OU=AC RAIZ FNMT-RCM +# Label: "AC RAIZ FNMT-RCM" +# Serial: 485876308206448804701554682760554759 +# MD5 Fingerprint: e2:09:04:b4:d3:bd:d1:a0:14:fd:1a:d2:47:c4:57:1d +# SHA1 Fingerprint: ec:50:35:07:b2:15:c4:95:62:19:e2:a8:9a:5b:42:99:2c:4c:2c:20 +# SHA256 Fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx +CzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ +WiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ +BgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG +Tk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/ +yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf +BBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz +WHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF +tBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z +374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC +IfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL +mbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7 +wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS +MKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2 +ZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet +UqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw +AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H +YJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3 +LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD +nFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1 +RXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM +LVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf +77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N +JpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm +fZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp +6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp +1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B +9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok +RqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv +uu8wd+RU4riEmViAqhOLUTpPSPaLtrM= +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 1 O=Amazon +# Subject: CN=Amazon Root CA 1 O=Amazon +# Label: "Amazon Root CA 1" +# Serial: 143266978916655856878034712317230054538369994 +# MD5 Fingerprint: 43:c6:bf:ae:ec:fe:ad:2f:18:c6:88:68:30:fc:c8:e6 +# SHA1 Fingerprint: 8d:a7:f9:65:ec:5e:fc:37:91:0f:1c:6e:59:fd:c1:cc:6a:6e:de:16 +# SHA256 Fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e +-----BEGIN CERTIFICATE----- +MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF +ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 +b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL +MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv +b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj +ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM +9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw +IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 +VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L +93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm +jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA +A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI +U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs +N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv +o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU +5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy +rqXRfboQnoZsG4q5WTP468SQvvG5 +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 2 O=Amazon +# Subject: CN=Amazon Root CA 2 O=Amazon +# Label: "Amazon Root CA 2" +# Serial: 143266982885963551818349160658925006970653239 +# MD5 Fingerprint: c8:e5:8d:ce:a8:42:e2:7a:c0:2a:5c:7c:9e:26:bf:66 +# SHA1 Fingerprint: 5a:8c:ef:45:d7:a6:98:59:76:7a:8c:8b:44:96:b5:78:cf:47:4b:1a +# SHA256 Fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4 +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF +ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 +b24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL +MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv +b3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK +gXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ +W0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg +1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K +8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r +2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me +z/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR +8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj +mUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz +7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6 ++XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI +0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB +Af8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm +UjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2 +LIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY ++gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS +k5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl +7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm +btmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl +urR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+ +fUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63 +n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE +76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H +9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT +4PsJYGw= +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 3 O=Amazon +# Subject: CN=Amazon Root CA 3 O=Amazon +# Label: "Amazon Root CA 3" +# Serial: 143266986699090766294700635381230934788665930 +# MD5 Fingerprint: a0:d4:ef:0b:f7:b5:d8:49:95:2a:ec:f5:c4:fc:81:87 +# SHA1 Fingerprint: 0d:44:dd:8c:3c:8c:1a:1a:58:75:64:81:e9:0f:2e:2a:ff:b3:d2:6e +# SHA256 Fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:43:b4:6d:b3:a4 +-----BEGIN CERTIFICATE----- +MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5 +MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g +Um9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG +A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg +Q0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl +ui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j +QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr +ttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr +BqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM +YyRIHN8wfdVoOw== +-----END CERTIFICATE----- + +# Issuer: CN=Amazon Root CA 4 O=Amazon +# Subject: CN=Amazon Root CA 4 O=Amazon +# Label: "Amazon Root CA 4" +# Serial: 143266989758080763974105200630763877849284878 +# MD5 Fingerprint: 89:bc:27:d5:eb:17:8d:06:6a:69:d5:fd:89:47:b4:cd +# SHA1 Fingerprint: f6:10:84:07:d6:f8:bb:67:98:0c:c2:e2:44:c2:eb:ae:1c:ef:63:be +# SHA256 Fingerprint: e3:5d:28:41:9e:d0:20:25:cf:a6:90:38:cd:62:39:62:45:8d:a5:c6:95:fb:de:a3:c2:2b:0b:fb:25:89:70:92 +-----BEGIN CERTIFICATE----- +MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5 +MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g +Um9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG +A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg +Q0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi +9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk +M6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB +MAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw +CkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW +1KyLa2tJElMzrdfkviT8tQp21KW8EA== +-----END CERTIFICATE----- + +# Issuer: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM +# Subject: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM +# Label: "TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1" +# Serial: 1 +# MD5 Fingerprint: dc:00:81:dc:69:2f:3e:2f:b0:3b:f6:3d:5a:91:8e:49 +# SHA1 Fingerprint: 31:43:64:9b:ec:ce:27:ec:ed:3a:3f:0b:8f:0d:e4:e8:91:dd:ee:ca +# SHA256 Fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16 +-----BEGIN CERTIFICATE----- +MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx +GDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp +bXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w +KwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0 +BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy +dW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG +EwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll +IEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU +QUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT +TTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg +LSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7 +a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr +LqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr +N3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X +YacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/ +iSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f +AJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH +V8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh +AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf +IPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4 +lzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c +8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf +lo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM= +-----END CERTIFICATE----- + +# Issuer: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. +# Subject: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD. +# Label: "GDCA TrustAUTH R5 ROOT" +# Serial: 9009899650740120186 +# MD5 Fingerprint: 63:cc:d9:3d:34:35:5c:6f:53:a3:e2:08:70:48:1f:b4 +# SHA1 Fingerprint: 0f:36:38:5b:81:1a:25:c3:9b:31:4e:83:ca:e9:34:66:70:cc:74:b4 +# SHA256 Fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93 +-----BEGIN CERTIFICATE----- +MIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UE +BhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ +IENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0 +MTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVowYjELMAkGA1UEBhMCQ04xMjAwBgNV +BAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8w +HQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0BAQEF +AAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJj +Dp6L3TQsAlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBj +TnnEt1u9ol2x8kECK62pOqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+u +KU49tm7srsHwJ5uu4/Ts765/94Y9cnrrpftZTqfrlYwiOXnhLQiPzLyRuEH3FMEj +qcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ9Cy5WmYqsBebnh52nUpm +MUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQxXABZG12 +ZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloP +zgsMR6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3Gk +L30SgLdTMEZeS1SZD2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeC +jGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4oR24qoAATILnsn8JuLwwoC8N9VKejveSswoA +HQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx9hoh49pwBiFYFIeFd3mqgnkC +AwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlRMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg +p8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZm +DRd9FBUb1Ov9H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5 +COmSdI31R9KrO9b7eGZONn356ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ry +L3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd+PwyvzeG5LuOmCd+uh8W4XAR8gPf +JWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQHtZa37dG/OaG+svg +IHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBDF8Io +2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV +09tL7ECQ8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQ +XR4EzzffHqhmsYzmIGrv/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrq +T8p+ck0LcIymSLumoRT2+1hEmRSuqguTaaApJUqlyyvdimYHFngVV3Eb7PVHhPOe +MTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g== +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com Root Certification Authority RSA O=SSL Corporation +# Subject: CN=SSL.com Root Certification Authority RSA O=SSL Corporation +# Label: "SSL.com Root Certification Authority RSA" +# Serial: 8875640296558310041 +# MD5 Fingerprint: 86:69:12:c0:70:f1:ec:ac:ac:c2:d5:bc:a5:5b:a1:29 +# SHA1 Fingerprint: b7:ab:33:08:d1:ea:44:77:ba:14:80:12:5a:6f:bd:a9:36:49:0c:bb +# SHA256 Fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:69 +-----BEGIN CERTIFICATE----- +MIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UE +BhMCVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQK +DA9TU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYwMjEyMTczOTM5WhcNNDEwMjEyMTcz +OTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv +dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv +bSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcN +AQEBBQADggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2R +xFdHaxh3a3by/ZPkPQ/CFp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aX +qhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcC +C52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/geoeOy3ZExqysdBP+lSgQ3 +6YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkpk8zruFvh +/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrF +YD3ZfBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93E +JNyAKoFBbZQ+yODJgUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVc +US4cK38acijnALXRdMbX5J+tB5O2UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8 +ZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi81xtZPCvM8hnIk2snYxnP/Okm ++Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4sbE6x/c+cCbqi +M+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV +HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4G +A1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGV +cpNxJK1ok1iOMq8bs3AD/CUrdIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBc +Hadm47GUBwwyOabqG7B52B2ccETjit3E+ZUfijhDPwGFpUenPUayvOUiaPd7nNgs +PgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAslu1OJD7OAUN5F7kR/ +q5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjqerQ0 +cuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jr +a6x+3uxjMxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90I +H37hVZkLId6Tngr75qNJvTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/Y +K9f1JmzJBjSWFupwWRoyeXkLtoh/D1JIPb9s2KJELtFOt3JY04kTlf5Eq/jXixtu +nLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406ywKBjYZC6VWg3dGq2ktuf +oYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NIWuuA8ShY +Ic2wBlX7Jz9TkHCpBB5XJ7k= +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com Root Certification Authority ECC O=SSL Corporation +# Subject: CN=SSL.com Root Certification Authority ECC O=SSL Corporation +# Label: "SSL.com Root Certification Authority ECC" +# Serial: 8495723813297216424 +# MD5 Fingerprint: 2e:da:e4:39:7f:9c:8f:37:d1:70:9f:26:17:51:3a:8e +# SHA1 Fingerprint: c3:19:7c:39:24:e6:54:af:1b:c4:ab:20:95:7a:e2:c3:0e:13:02:6a +# SHA256 Fingerprint: 34:17:bb:06:cc:60:07:da:1b:96:1c:92:0b:8a:b4:ce:3f:ad:82:0e:4a:a3:0b:9a:cb:c4:a7:4e:bd:ce:bc:65 +-----BEGIN CERTIFICATE----- +MIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMC +VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T +U0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNDAzWhcNNDEwMjEyMTgxNDAz +WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0 +b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBS +b290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB +BAAiA2IABEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI +7Z4INcgn64mMU1jrYor+8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPg +CemB+vNH06NjMGEwHQYDVR0OBBYEFILRhXMw5zUE044CkvvlpNHEIejNMA8GA1Ud +EwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTTjgKS++Wk0cQh6M0wDgYD +VR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCWe+0F+S8T +kdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+ +gA0z5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation +# Subject: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation +# Label: "SSL.com EV Root Certification Authority RSA R2" +# Serial: 6248227494352943350 +# MD5 Fingerprint: e1:1e:31:58:1a:ae:54:53:02:f6:17:6a:11:7b:4d:95 +# SHA1 Fingerprint: 74:3a:f0:52:9b:d0:32:a0:f4:4a:83:cd:d4:ba:a9:7b:7c:2e:c4:9a +# SHA256 Fingerprint: 2e:7b:f1:6c:c2:24:85:a7:bb:e2:aa:86:96:75:07:61:b0:ae:39:be:3b:2f:e9:d0:cc:6d:4e:f7:34:91:42:5c +-----BEGIN CERTIFICATE----- +MIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNV +BAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UE +CgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2Vy +dGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMB4XDTE3MDUzMTE4MTQzN1oXDTQy +MDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4G +A1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQD +DC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvq +M0fNTPl9fb69LT3w23jhhqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssuf +OePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7wcXHswxzpY6IXFJ3vG2fThVUCAtZJycxa +4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTOZw+oz12WGQvE43LrrdF9 +HSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+B6KjBSYR +aZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcA +b9ZhCBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQ +Gp8hLH94t2S42Oim9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQV +PWKchjgGAGYS5Fl2WlPAApiiECtoRHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMO +pgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+SlmJuwgUHfbSguPvuUCYHBBXtSu +UDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48+qvWBkofZ6aY +MBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV +HSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa4 +9QaAJadz20ZpqJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBW +s47LCp1Jjr+kxJG7ZhcFUZh1++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5 +Sm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nxY/hoLVUE0fKNsKTPvDxeH3jnpaAg +cLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2GguDKBAdRUNf/ktUM +79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDzOFSz +/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXt +ll9ldDz7CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEm +Kf7GUmG6sXP/wwyc5WxqlD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKK +QbNmC1r7fSOl8hqw/96bg5Qu0T/fkreRrwU7ZcegbLHNYhLDkBvjJc40vG93drEQ +w/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1hlMYegouCRw2n5H9gooi +S9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX9hwJ1C07 +mKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w== +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation +# Subject: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation +# Label: "SSL.com EV Root Certification Authority ECC" +# Serial: 3182246526754555285 +# MD5 Fingerprint: 59:53:22:65:83:42:01:54:c0:ce:42:b9:5a:7c:f2:90 +# SHA1 Fingerprint: 4c:dd:51:a3:d1:f5:20:32:14:b0:c6:c5:32:23:03:91:c7:46:42:6d +# SHA256 Fingerprint: 22:a2:c1:f7:bd:ed:70:4c:c1:e7:01:b5:f4:08:c3:10:88:0f:e9:56:b5:de:2a:4a:44:f9:9c:87:3a:25:a7:c8 +-----BEGIN CERTIFICATE----- +MIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMC +VVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T +U0wgQ29ycG9yYXRpb24xNDAyBgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNTIzWhcNNDEwMjEyMTgx +NTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv +dXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NMLmNv +bSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMA +VIbc/R/fALhBYlzccBYy3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1Kthku +WnBaBu2+8KGwytAJKaNjMGEwHQYDVR0OBBYEFFvKXuXe0oGqzagtZFG22XKbl+ZP +MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe5d7SgarNqC1kUbbZcpuX +5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJN+vp1RPZ +ytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZg +h5Mmm7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6 +# Label: "GlobalSign Root CA - R6" +# Serial: 1417766617973444989252670301619537 +# MD5 Fingerprint: 4f:dd:07:e4:d4:22:64:39:1e:0c:37:42:ea:d1:c6:ae +# SHA1 Fingerprint: 80:94:64:0e:b5:a7:a1:ca:11:9c:1f:dd:d5:9f:81:02:63:a7:fb:d1 +# SHA256 Fingerprint: 2c:ab:ea:fe:37:d0:6c:a2:2a:ba:73:91:c0:03:3d:25:98:29:52:c4:53:64:73:49:76:3a:3a:b5:ad:6c:cf:69 +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEg +MB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2Jh +bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQx +MjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSNjET +MBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQssgrRI +xutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1k +ZguSgMpE3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxD +aNc9PIrFsmbVkJq3MQbFvuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJw +LnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqMPKq0pPbzlUoSB239jLKJz9CgYXfIWHSw +1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+azayOeSsJDa38O+2HBNX +k7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05OWgtH8wY2 +SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/h +bguyCLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4n +WUx2OVvq+aWh2IMP0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpY +rZxCRXluDocZXFSxZba/jJvcE+kNb7gu3GduyYsRtYQUigAZcIN5kZeR1Bonvzce +MgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNVHSMEGDAWgBSu +bAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN +nsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGt +Ixg93eFyRJa0lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr61 +55wsTLxDKZmOMNOsIeDjHfrYBzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLj +vUYAGm0CuiVdjaExUd1URhxN25mW7xocBFymFe944Hn+Xds+qkxV/ZoVqW/hpvvf +cDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr3TsTjxKM4kEaSHpz +oHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB10jZp +nOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfs +pA9MRf/TuTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+v +JJUEeKgDu+6B5dpffItKoZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R +8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+tJDfLRVpOoERIyNiwmcUVhAn21klJwGW4 +5hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA= +-----END CERTIFICATE----- + +# Issuer: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed +# Subject: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed +# Label: "OISTE WISeKey Global Root GC CA" +# Serial: 44084345621038548146064804565436152554 +# MD5 Fingerprint: a9:d6:b9:2d:2f:93:64:f8:a5:69:ca:91:e9:68:07:23 +# SHA1 Fingerprint: e0:11:84:5e:34:de:be:88:81:b9:9c:f6:16:26:d1:96:1f:c3:b9:31 +# SHA256 Fingerprint: 85:60:f9:1c:36:24:da:ba:95:70:b5:fe:a0:db:e3:6f:f1:1a:83:23:be:94:86:85:4f:b3:f3:4a:55:71:19:8d +-----BEGIN CERTIFICATE----- +MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQsw +CQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91 +bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwg +Um9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRaFw00MjA1MDkwOTU4MzNaMG0xCzAJ +BgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBGb3Vu +ZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2JhbCBS +b290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4ni +eUqjFqdrVCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4W +p2OQ0jnUsYd4XxiWD1AbNTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7T +rYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0EAwMDaAAwZQIwJsdpW9zV +57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtkAjEA2zQg +Mgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9 +-----END CERTIFICATE----- + +# Issuer: CN=UCA Global G2 Root O=UniTrust +# Subject: CN=UCA Global G2 Root O=UniTrust +# Label: "UCA Global G2 Root" +# Serial: 124779693093741543919145257850076631279 +# MD5 Fingerprint: 80:fe:f0:c4:4a:f0:5c:62:32:9f:1c:ba:78:a9:50:f8 +# SHA1 Fingerprint: 28:f9:78:16:19:7a:ff:18:25:18:aa:44:fe:c1:a0:ce:5c:b6:4c:8a +# SHA256 Fingerprint: 9b:ea:11:c9:76:fe:01:47:64:c1:be:56:a6:f9:14:b5:a5:60:31:7a:bd:99:88:39:33:82:e5:16:1a:a0:49:3c +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9 +MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBH +bG9iYWwgRzIgUm9vdDAeFw0xNjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0x +CzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlUcnVzdDEbMBkGA1UEAwwSVUNBIEds +b2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxeYr +b3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmToni9 +kmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzm +VHqUwCoV8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/R +VogvGjqNO7uCEeBHANBSh6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDc +C/Vkw85DvG1xudLeJ1uK6NjGruFZfc8oLTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIj +tm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/R+zvWr9LesGtOxdQXGLY +D0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBeKW4bHAyv +j5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6Dl +NaBa4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6 +iIis7nCs+dwp4wwcOxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznP +O6Q0ibd5Ei9Hxeepl2n8pndntd978XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/ +BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIHEjMz15DD/pQwIX4wV +ZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo5sOASD0Ee/oj +L3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5 +1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl +1qnN3e92mI0ADs0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oU +b3n09tDh05S60FdRvScFDcH9yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LV +PtateJLbXDzz2K36uGt/xDYotgIVilQsnLAXc47QN6MUPJiVAAwpBVueSUmxX8fj +y88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHojhJi6IjMtX9Gl8Cb +EGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZkbxqg +DMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI ++Vg7RE+xygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGy +YiGqhkCyLmTTX8jjfhFnRR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bX +UB+K+wb1whnw0A== +-----END CERTIFICATE----- + +# Issuer: CN=UCA Extended Validation Root O=UniTrust +# Subject: CN=UCA Extended Validation Root O=UniTrust +# Label: "UCA Extended Validation Root" +# Serial: 106100277556486529736699587978573607008 +# MD5 Fingerprint: a1:f3:5f:43:c6:34:9b:da:bf:8c:7e:05:53:ad:96:e2 +# SHA1 Fingerprint: a3:a1:b0:6f:24:61:23:4a:e3:36:a5:c2:37:fc:a6:ff:dd:f0:d7:3a +# SHA256 Fingerprint: d4:3a:f9:b3:54:73:75:5c:96:84:fc:06:d7:d8:cb:70:ee:5c:28:e7:73:fb:29:4e:b4:1e:e7:17:22:92:4d:24 +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBH +MQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBF +eHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMx +MDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNV +BAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrsiWog +D4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvS +sPGP2KxFRv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aop +O2z6+I9tTcg1367r3CTueUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dk +sHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR59mzLC52LqGj3n5qiAno8geK+LLNEOfi +c0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH0mK1lTnj8/FtDw5lhIpj +VMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KRel7sFsLz +KuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/ +TuDvB0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41G +sx2VYVdWf6/wFlthWG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs +1+lvK9JKBZP8nm9rZ/+I8U6laUpSNwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQD +fwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS3H5aBZ8eNJr34RQwDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADaN +l8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR +ap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQ +VBcZEhrxH9cMaVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5 +c6sq1WnIeJEmMX3ixzDx/BR4dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp +4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb+7lsq+KePRXBOy5nAliRn+/4Qh8s +t2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOWF3sGPjLtx7dCvHaj +2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwiGpWO +vpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2C +xR9GUeOcGMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmx +cmtpzyKEC2IPrNkZAJSidjzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbM +fjKaiJUINlK73nZfdklJrX+9ZSCyycErdhh2n1ax +-----END CERTIFICATE----- + +# Issuer: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 +# Subject: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036 +# Label: "Certigna Root CA" +# Serial: 269714418870597844693661054334862075617 +# MD5 Fingerprint: 0e:5c:30:62:27:eb:5b:bc:d7:ae:62:ba:e9:d5:df:77 +# SHA1 Fingerprint: 2d:0d:52:14:ff:9e:ad:99:24:01:74:20:47:6e:6c:85:27:27:f5:43 +# SHA256 Fingerprint: d4:8d:3d:23:ee:db:50:a4:59:e5:51:97:60:1c:27:77:4b:9d:7b:18:c9:4d:5a:05:95:11:a1:02:50:b9:31:68 +-----BEGIN CERTIFICATE----- +MIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAw +WjELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAw +MiA0ODE0NjMwODEwMDAzNjEZMBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0x +MzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjdaMFoxCzAJBgNVBAYTAkZSMRIwEAYD +VQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYzMDgxMDAwMzYxGTAX +BgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw +ggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sO +ty3tRQgXstmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9M +CiBtnyN6tMbaLOQdLNyzKNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPu +I9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8JXrJhFwLrN1CTivngqIkicuQstDuI7pm +TLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16XdG+RCYyKfHx9WzMfgIh +C59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq4NYKpkDf +ePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3Yz +IoejwpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWT +Co/1VTp2lc5ZmIoJlXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1k +JWumIWmbat10TWuXekG9qxf5kBdIjzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5 +hwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp//TBt2dzhauH8XwIDAQABo4IB +GjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of +1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczov +L3d3d3cuY2VydGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilo +dHRwOi8vY3JsLmNlcnRpZ25hLmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYr +aHR0cDovL2NybC5kaGlteW90aXMuY29tL2NlcnRpZ25hcm9vdGNhLmNybDANBgkq +hkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOItOoldaDgvUSILSo3L +6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxPTGRG +HVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH6 +0BGM+RFq7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncB +lA2c5uk5jR+mUYyZDDl34bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdi +o2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1 +gPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS6Cvu5zHbugRqh5jnxV/v +faci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaYtlu3zM63 +Nwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayh +jWZSaX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw +3kAP+HwV96LOPNdeE4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0= +-----END CERTIFICATE----- + +# Issuer: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI +# Subject: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI +# Label: "emSign Root CA - G1" +# Serial: 235931866688319308814040 +# MD5 Fingerprint: 9c:42:84:57:dd:cb:0b:a7:2e:95:ad:b6:f3:da:bc:ac +# SHA1 Fingerprint: 8a:c7:ad:8f:73:ac:4e:c1:b5:75:4d:a5:40:f4:fc:cf:7c:b5:8e:8c +# SHA256 Fingerprint: 40:f6:af:03:46:a9:9a:a1:cd:1d:55:5a:4e:9c:ce:62:c7:f9:63:46:03:ee:40:66:15:83:3d:c8:c8:d0:03:67 +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +# Issuer: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI +# Subject: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI +# Label: "emSign ECC Root CA - G3" +# Serial: 287880440101571086945156 +# MD5 Fingerprint: ce:0b:72:d1:9f:88:8e:d0:50:03:e8:e3:b8:8b:67:40 +# SHA1 Fingerprint: 30:43:fa:4f:f2:57:dc:a0:c3:80:ee:2e:58:ea:78:b2:3f:e6:bb:c1 +# SHA256 Fingerprint: 86:a1:ec:ba:08:9c:4a:8d:3b:be:27:34:c6:12:ba:34:1d:81:3e:04:3c:f9:e8:a8:62:cd:5c:57:a3:6b:be:6b +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +# Issuer: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI +# Subject: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI +# Label: "emSign Root CA - C1" +# Serial: 825510296613316004955058 +# MD5 Fingerprint: d8:e3:5d:01:21:fa:78:5a:b0:df:ba:d2:ee:2a:5f:68 +# SHA1 Fingerprint: e7:2e:f1:df:fc:b2:09:28:cf:5d:d4:d5:67:37:b1:51:cb:86:4f:01 +# SHA256 Fingerprint: 12:56:09:aa:30:1d:a0:a2:49:b9:7a:82:39:cb:6a:34:21:6f:44:dc:ac:9f:39:54:b1:42:92:f2:e8:c8:60:8f +-----BEGIN CERTIFICATE----- +MIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkG +A1UEBhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEg +SW5jMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAw +MFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln +biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9v +dCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+upufGZ +BczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZ +HdPIWoU/Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH +3DspVpNqs8FqOp099cGXOFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvH +GPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4VI5b2P/AgNBbeCsbEBEV5f6f9vtKppa+c +xSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleoomslMuoaJuvimUnzYnu3Yy1 +aylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+XJGFehiq +TbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87 +/kOXSTKZEhVb3xEp/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4 +kqNPEjE2NuLe/gDEo2APJ62gsIq1NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrG +YQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9wC68AivTxEDkigcxHpvOJpkT ++xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQBmIMMMAVSKeo +WXzhriKi4gp6D/piq1JM4fHfyr6DDUI= +-----END CERTIFICATE----- + +# Issuer: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI +# Subject: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI +# Label: "emSign ECC Root CA - C3" +# Serial: 582948710642506000014504 +# MD5 Fingerprint: 3e:53:b3:a3:81:ee:d7:10:f8:d3:b0:1d:17:92:f5:d5 +# SHA1 Fingerprint: b6:af:43:c2:9b:81:53:7d:f6:ef:6b:c3:1f:1f:60:15:0c:ee:48:66 +# SHA256 Fingerprint: bc:4d:80:9b:15:18:9d:78:db:3e:1d:8c:f4:f9:72:6a:79:5d:a1:64:3c:a5:f1:35:8e:1d:db:0e:dc:0d:7e:b3 +-----BEGIN CERTIFICATE----- +MIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQG +EwJVUzETMBEGA1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMx +IDAeBgNVBAMTF2VtU2lnbiBFQ0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAw +MFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln +biBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQDExdlbVNpZ24gRUND +IFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd6bci +MK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4Ojavti +sIGJAnB9SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0O +BBYEFPtaSNCAIEDyqOkAB2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB +Af8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMQC02C8Cif22TGK6Q04ThHK1rt0c +3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwUZOR8loMRnLDRWmFLpg9J +0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ== +-----END CERTIFICATE----- + +# Issuer: CN=Hongkong Post Root CA 3 O=Hongkong Post +# Subject: CN=Hongkong Post Root CA 3 O=Hongkong Post +# Label: "Hongkong Post Root CA 3" +# Serial: 46170865288971385588281144162979347873371282084 +# MD5 Fingerprint: 11:fc:9f:bd:73:30:02:8a:fd:3f:f3:58:b9:cb:20:f0 +# SHA1 Fingerprint: 58:a2:d0:ec:20:52:81:5b:c1:f3:f8:64:02:24:4e:c2:8e:02:4b:02 +# SHA256 Fingerprint: 5a:2f:c0:3f:0c:83:b0:90:bb:fa:40:60:4b:09:88:44:6c:76:36:18:3d:f9:84:6e:17:10:1a:44:7f:b8:ef:d6 +-----BEGIN CERTIFICATE----- +MIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQEL +BQAwbzELMAkGA1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJ +SG9uZyBLb25nMRYwFAYDVQQKEw1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25n +a29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2MDMwMjI5NDZaFw00MjA2MDMwMjI5 +NDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtvbmcxEjAQBgNVBAcT +CUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMXSG9u +Z2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK +AoICAQCziNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFO +dem1p+/l6TWZ5Mwc50tfjTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mI +VoBc+L0sPOFMV4i707mV78vH9toxdCim5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV +9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOesL4jpNrcyCse2m5FHomY +2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj0mRiikKY +vLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+Tt +bNe/JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZb +x39ri1UbSsUgYT2uy1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+ +l2oBlKN8W4UdKjk60FSh0Tlxnf0h+bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YK +TE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsGxVd7GYYKecsAyVKvQv83j+Gj +Hno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwIDAQABo2MwYTAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e +i9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEw +DQYJKoZIhvcNAQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG +7BJ8dNVI0lkUmcDrudHr9EgwW62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCk +MpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWldy8joRTnU+kLBEUx3XZL7av9YROXr +gZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov+BS5gLNdTaqX4fnk +GMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDceqFS +3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJm +Ozj/2ZQw9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+ +l6mc1X5VTMbeRRAc6uk7nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6c +JfTzPV4e0hz5sy229zdcxsshTrD3mUcYhcErulWuBurQB7Lcq9CClnXO0lD+mefP +L5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB60PZ2Pierc+xYw5F9KBa +LJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fqdBb9HxEG +mpv0 +-----END CERTIFICATE----- + +# Issuer: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation +# Subject: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation +# Label: "Microsoft ECC Root Certificate Authority 2017" +# Serial: 136839042543790627607696632466672567020 +# MD5 Fingerprint: dd:a1:03:e6:4a:93:10:d1:bf:f0:19:42:cb:fe:ed:67 +# SHA1 Fingerprint: 99:9a:64:c3:7f:f4:7d:9f:ab:95:f1:47:69:89:14:60:ee:c4:c3:c5 +# SHA256 Fingerprint: 35:8d:f3:9d:76:4a:f9:e1:b7:66:e9:c9:72:df:35:2e:e1:5c:fa:c2:27:af:6a:d1:d7:0e:8e:4a:6e:dc:ba:02 +-----BEGIN CERTIFICATE----- +MIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw +CQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD +VQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw +MTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV +UzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy +b3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR +ogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb +hGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E +BTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3 +FQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV +L8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB +iudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M= +-----END CERTIFICATE----- + +# Issuer: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation +# Subject: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation +# Label: "Microsoft RSA Root Certificate Authority 2017" +# Serial: 40975477897264996090493496164228220339 +# MD5 Fingerprint: 10:ff:00:ff:cf:c9:f8:c7:7a:c0:ee:35:8e:c9:0f:47 +# SHA1 Fingerprint: 73:a5:e6:4a:3b:ff:83:16:ff:0e:dc:cc:61:8a:90:6e:4e:ae:4d:74 +# SHA256 Fingerprint: c7:41:f7:0f:4b:2a:8d:88:bf:2e:71:c1:41:22:ef:53:ef:10:eb:a0:cf:a5:e6:4c:fa:20:f4:18:85:30:73:e0 +-----BEGIN CERTIFICATE----- +MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl +MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw +NAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 +IDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG +EwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N +aWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ +Nt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0 +ZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1 +HLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm +gGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ +jEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc +aDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG +YaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6 +W6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K +UGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH ++FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q +W5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC +NxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC +LgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC +gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6 +tZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh +SnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2 +TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3 +pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR +xpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp +GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9 +dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN +AHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB +RA+GsCyRxj3qrg+E +-----END CERTIFICATE----- + +# Issuer: CN=e-Szigno Root CA 2017 O=Microsec Ltd. +# Subject: CN=e-Szigno Root CA 2017 O=Microsec Ltd. +# Label: "e-Szigno Root CA 2017" +# Serial: 411379200276854331539784714 +# MD5 Fingerprint: de:1f:f6:9e:84:ae:a7:b4:21:ce:1e:58:7d:d1:84:98 +# SHA1 Fingerprint: 89:d4:83:03:4f:9e:9a:48:80:5f:72:37:d4:a9:a6:ef:cb:7c:1f:d1 +# SHA256 Fingerprint: be:b0:0b:30:83:9b:9b:c3:2c:32:e4:44:79:05:95:06:41:f2:64:21:b1:5e:d0:89:19:8b:51:8a:e2:ea:1b:99 +-----BEGIN CERTIFICATE----- +MIICQDCCAeWgAwIBAgIMAVRI7yH9l1kN9QQKMAoGCCqGSM49BAMCMHExCzAJBgNV +BAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMgTHRk +LjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25vIFJv +b3QgQ0EgMjAxNzAeFw0xNzA4MjIxMjA3MDZaFw00MjA4MjIxMjA3MDZaMHExCzAJ +BgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMg +THRkLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25v +IFJvb3QgQ0EgMjAxNzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJbcPYrYsHtv +xie+RJCxs1YVe45DJH0ahFnuY2iyxl6H0BVIHqiQrb1TotreOpCmYF9oMrWGQd+H +Wyx7xf58etqjYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G +A1UdDgQWBBSHERUI0arBeAyxr87GyZDvvzAEwDAfBgNVHSMEGDAWgBSHERUI0arB +eAyxr87GyZDvvzAEwDAKBggqhkjOPQQDAgNJADBGAiEAtVfd14pVCzbhhkT61Nlo +jbjcI4qKDdQvfepz7L9NbKgCIQDLpbQS+ue16M9+k/zzNY9vTlp8tLxOsvxyqltZ ++efcMQ== +-----END CERTIFICATE----- + +# Issuer: O=CERTSIGN SA OU=certSIGN ROOT CA G2 +# Subject: O=CERTSIGN SA OU=certSIGN ROOT CA G2 +# Label: "certSIGN Root CA G2" +# Serial: 313609486401300475190 +# MD5 Fingerprint: 8c:f1:75:8a:c6:19:cf:94:b7:f7:65:20:87:c3:97:c7 +# SHA1 Fingerprint: 26:f9:93:b4:ed:3d:28:27:b0:b9:4b:a7:e9:15:1d:a3:8d:92:e5:32 +# SHA256 Fingerprint: 65:7c:fe:2f:a7:3f:aa:38:46:25:71:f3:32:a2:36:3a:46:fc:e7:02:09:51:71:07:02:cd:fb:b6:ee:da:33:05 +-----BEGIN CERTIFICATE----- +MIIFRzCCAy+gAwIBAgIJEQA0tk7GNi02MA0GCSqGSIb3DQEBCwUAMEExCzAJBgNV +BAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJR04g +Uk9PVCBDQSBHMjAeFw0xNzAyMDYwOTI3MzVaFw00MjAyMDYwOTI3MzVaMEExCzAJ +BgNVBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJ +R04gUk9PVCBDQSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDF +dRmRfUR0dIf+DjuW3NgBFszuY5HnC2/OOwppGnzC46+CjobXXo9X69MhWf05N0Iw +vlDqtg+piNguLWkh59E3GE59kdUWX2tbAMI5Qw02hVK5U2UPHULlj88F0+7cDBrZ +uIt4ImfkabBoxTzkbFpG583H+u/E7Eu9aqSs/cwoUe+StCmrqzWaTOTECMYmzPhp +n+Sc8CnTXPnGFiWeI8MgwT0PPzhAsP6CRDiqWhqKa2NYOLQV07YRaXseVO6MGiKs +cpc/I1mbySKEwQdPzH/iV8oScLumZfNpdWO9lfsbl83kqK/20U6o2YpxJM02PbyW +xPFsqa7lzw1uKA2wDrXKUXt4FMMgL3/7FFXhEZn91QqhngLjYl/rNUssuHLoPj1P +rCy7Lobio3aP5ZMqz6WryFyNSwb/EkaseMsUBzXgqd+L6a8VTxaJW732jcZZroiF +DsGJ6x9nxUWO/203Nit4ZoORUSs9/1F3dmKh7Gc+PoGD4FapUB8fepmrY7+EF3fx +DTvf95xhszWYijqy7DwaNz9+j5LP2RIUZNoQAhVB/0/E6xyjyfqZ90bp4RjZsbgy +LcsUDFDYg2WD7rlcz8sFWkz6GZdr1l0T08JcVLwyc6B49fFtHsufpaafItzRUZ6C +eWRgKRM+o/1Pcmqr4tTluCRVLERLiohEnMqE0yo7AgMBAAGjQjBAMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSCIS1mxteg4BXrzkwJ +d8RgnlRuAzANBgkqhkiG9w0BAQsFAAOCAgEAYN4auOfyYILVAzOBywaK8SJJ6ejq +kX/GM15oGQOGO0MBzwdw5AgeZYWR5hEit/UCI46uuR59H35s5r0l1ZUa8gWmr4UC +b6741jH/JclKyMeKqdmfS0mbEVeZkkMR3rYzpMzXjWR91M08KCy0mpbqTfXERMQl +qiCA2ClV9+BB/AYm/7k29UMUA2Z44RGx2iBfRgB4ACGlHgAoYXhvqAEBj500mv/0 +OJD7uNGzcgbJceaBxXntC6Z58hMLnPddDnskk7RI24Zf3lCGeOdA5jGokHZwYa+c +NywRtYK3qq4kNFtyDGkNzVmf9nGvnAvRCjj5BiKDUyUM/FHE5r7iOZULJK2v0ZXk +ltd0ZGtxTgI8qoXzIKNDOXZbbFD+mpwUHmUUihW9o4JFWklWatKcsWMy5WHgUyIO +pwpJ6st+H6jiYoD2EEVSmAYY3qXNL3+q1Ok+CHLsIwMCPKaq2LxndD0UF/tUSxfj +03k9bWtJySgOLnRQvwzZRjoQhsmnP+mg7H/rpXdYaXHmgwo38oZJar55CJD2AhZk +PuXaTH4MNMn5X7azKFGnpyuqSfqNZSlO42sTp5SjLVFteAxEy9/eCG/Oo2Sr05WE +1LlSVHJ7liXMvGnjSG4N0MedJ5qq+BOS3R7fY581qRY27Iy4g/Q9iY/NtBde17MX +QRBdJ3NghVdJIgc= +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global Certification Authority" +# Serial: 1846098327275375458322922162 +# MD5 Fingerprint: f8:1c:18:2d:2f:ba:5f:6d:a1:6c:bc:c7:ab:91:c7:0e +# SHA1 Fingerprint: 2f:8f:36:4f:e1:58:97:44:21:59:87:a5:2a:9a:d0:69:95:26:7f:b5 +# SHA256 Fingerprint: 97:55:20:15:f5:dd:fc:3c:87:88:c0:06:94:45:55:40:88:94:45:00:84:f1:00:86:70:86:bc:1a:2b:b5:8d:c8 +-----BEGIN CERTIFICATE----- +MIIF2jCCA8KgAwIBAgIMBfcOhtpJ80Y1LrqyMA0GCSqGSIb3DQEBCwUAMIGIMQsw +CQYDVQQGEwJVUzERMA8GA1UECAwISWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28x +ITAfBgNVBAoMGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1 +c3R3YXZlIEdsb2JhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0xNzA4MjMx +OTM0MTJaFw00MjA4MjMxOTM0MTJaMIGIMQswCQYDVQQGEwJVUzERMA8GA1UECAwI +SWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28xITAfBgNVBAoMGFRydXN0d2F2ZSBI +b2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1c3R3YXZlIEdsb2JhbCBDZXJ0aWZp +Y2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB +ALldUShLPDeS0YLOvR29zd24q88KPuFd5dyqCblXAj7mY2Hf8g+CY66j96xz0Xzn +swuvCAAJWX/NKSqIk4cXGIDtiLK0thAfLdZfVaITXdHG6wZWiYj+rDKd/VzDBcdu +7oaJuogDnXIhhpCujwOl3J+IKMujkkkP7NAP4m1ET4BqstTnoApTAbqOl5F2brz8 +1Ws25kCI1nsvXwXoLG0R8+eyvpJETNKXpP7ScoFDB5zpET71ixpZfR9oWN0EACyW +80OzfpgZdNmcc9kYvkHHNHnZ9GLCQ7mzJ7Aiy/k9UscwR7PJPrhq4ufogXBeQotP +JqX+OsIgbrv4Fo7NDKm0G2x2EOFYeUY+VM6AqFcJNykbmROPDMjWLBz7BegIlT1l +RtzuzWniTY+HKE40Cz7PFNm73bZQmq131BnW2hqIyE4bJ3XYsgjxroMwuREOzYfw +hI0Vcnyh78zyiGG69Gm7DIwLdVcEuE4qFC49DxweMqZiNu5m4iK4BUBjECLzMx10 +coos9TkpoNPnG4CELcU9402x/RpvumUHO1jsQkUm+9jaJXLE9gCxInm943xZYkqc +BW89zubWR2OZxiRvchLIrH+QtAuRcOi35hYQcRfO3gZPSEF9NUqjifLJS3tBEW1n +twiYTOURGa5CgNz7kAXU+FDKvuStx8KU1xad5hePrzb7AgMBAAGjQjBAMA8GA1Ud +EwEB/wQFMAMBAf8wHQYDVR0OBBYEFJngGWcNYtt2s9o9uFvo/ULSMQ6HMA4GA1Ud +DwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAmHNw4rDT7TnsTGDZqRKGFx6W +0OhUKDtkLSGm+J1WE2pIPU/HPinbbViDVD2HfSMF1OQc3Og4ZYbFdada2zUFvXfe +uyk3QAUHw5RSn8pk3fEbK9xGChACMf1KaA0HZJDmHvUqoai7PF35owgLEQzxPy0Q +lG/+4jSHg9bP5Rs1bdID4bANqKCqRieCNqcVtgimQlRXtpla4gt5kNdXElE1GYhB +aCXUNxeEFfsBctyV3lImIJgm4nb1J2/6ADtKYdkNy1GTKv0WBpanI5ojSP5RvbbE +sLFUzt5sQa0WZ37b/TjNuThOssFgy50X31ieemKyJo90lZvkWx3SD92YHJtZuSPT +MaCm/zjdzyBP6VhWOmfD0faZmZ26NraAL4hHT4a/RDqA5Dccprrql5gR0IRiR2Qe +qu5AvzSxnI9O4fKSTx+O856X3vOmeWqJcU9LJxdI/uz0UA9PSX3MReO9ekDFQdxh +VicGaeVyQYHTtgGJoC86cnn+OjC/QezHYj6RS8fZMXZC+fc8Y+wmjHMMfRod6qh8 +h6jCJ3zhM0EPz8/8AKAigJ5Kp28AsEFFtyLKaEjFQqKu3R3y4G5OBVixwJAWKqQ9 +EEC+j2Jjg6mcgn0tAumDMHzLJ8n9HmYAsC7TIS+OMxZsmO0QqAfWzJPP29FpHOTK +yeC2nOnOcXHebD8WpHk= +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global ECC P256 Certification Authority" +# Serial: 4151900041497450638097112925 +# MD5 Fingerprint: 5b:44:e3:8d:5d:36:86:26:e8:0d:05:d2:59:a7:83:54 +# SHA1 Fingerprint: b4:90:82:dd:45:0c:be:8b:5b:b1:66:d3:e2:a4:08:26:cd:ed:42:cf +# SHA256 Fingerprint: 94:5b:bc:82:5e:a5:54:f4:89:d1:fd:51:a7:3d:df:2e:a6:24:ac:70:19:a0:52:05:22:5c:22:a7:8c:cf:a8:b4 +-----BEGIN CERTIFICATE----- +MIICYDCCAgegAwIBAgIMDWpfCD8oXD5Rld9dMAoGCCqGSM49BAMCMIGRMQswCQYD +VQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf +BgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3 +YXZlIEdsb2JhbCBFQ0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x +NzA4MjMxOTM1MTBaFw00MjA4MjMxOTM1MTBaMIGRMQswCQYDVQQGEwJVUzERMA8G +A1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0 +d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF +Q0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTBZMBMGByqGSM49AgEGCCqG +SM49AwEHA0IABH77bOYj43MyCMpg5lOcunSNGLB4kFKA3TjASh3RqMyTpJcGOMoN +FWLGjgEqZZ2q3zSRLoHB5DOSMcT9CTqmP62jQzBBMA8GA1UdEwEB/wQFMAMBAf8w +DwYDVR0PAQH/BAUDAwcGADAdBgNVHQ4EFgQUo0EGrJBt0UrrdaVKEJmzsaGLSvcw +CgYIKoZIzj0EAwIDRwAwRAIgB+ZU2g6gWrKuEZ+Hxbb/ad4lvvigtwjzRM4q3wgh +DDcCIC0mA6AFvWvR9lz4ZcyGbbOcNEhjhAnFjXca4syc4XR7 +-----END CERTIFICATE----- + +# Issuer: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc. +# Subject: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc. +# Label: "Trustwave Global ECC P384 Certification Authority" +# Serial: 2704997926503831671788816187 +# MD5 Fingerprint: ea:cf:60:c4:3b:b9:15:29:40:a1:97:ed:78:27:93:d6 +# SHA1 Fingerprint: e7:f3:a3:c8:cf:6f:c3:04:2e:6d:0e:67:32:c5:9e:68:95:0d:5e:d2 +# SHA256 Fingerprint: 55:90:38:59:c8:c0:c3:eb:b8:75:9e:ce:4e:25:57:22:5f:f5:75:8b:bd:38:eb:d4:82:76:60:1e:1b:d5:80:97 +-----BEGIN CERTIFICATE----- +MIICnTCCAiSgAwIBAgIMCL2Fl2yZJ6SAaEc7MAoGCCqGSM49BAMDMIGRMQswCQYD +VQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf +BgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3 +YXZlIEdsb2JhbCBFQ0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x +NzA4MjMxOTM2NDNaFw00MjA4MjMxOTM2NDNaMIGRMQswCQYDVQQGEwJVUzERMA8G +A1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0 +d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF +Q0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTB2MBAGByqGSM49AgEGBSuB +BAAiA2IABGvaDXU1CDFHBa5FmVXxERMuSvgQMSOjfoPTfygIOiYaOs+Xgh+AtycJ +j9GOMMQKmw6sWASr9zZ9lCOkmwqKi6vr/TklZvFe/oyujUF5nQlgziip04pt89ZF +1PKYhDhloKNDMEEwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwYAMB0G +A1UdDgQWBBRVqYSJ0sEyvRjLbKYHTsjnnb6CkDAKBggqhkjOPQQDAwNnADBkAjA3 +AZKXRRJ+oPM+rRk6ct30UJMDEr5E0k9BpIycnR+j9sKS50gU/k6bpZFXrsY3crsC +MGclCrEMXu6pY5Jv5ZAL/mYiykf9ijH3g/56vxC+GCsej/YpHpRZ744hN8tRmKVu +Sw== +-----END CERTIFICATE----- + +# Issuer: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. +# Subject: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp. +# Label: "NAVER Global Root Certification Authority" +# Serial: 9013692873798656336226253319739695165984492813 +# MD5 Fingerprint: c8:7e:41:f6:25:3b:f5:09:b3:17:e8:46:3d:bf:d0:9b +# SHA1 Fingerprint: 8f:6b:f2:a9:27:4a:da:14:a0:c4:f4:8e:61:27:f9:c0:1e:78:5d:d1 +# SHA256 Fingerprint: 88:f4:38:dc:f8:ff:d1:fa:8f:42:91:15:ff:e5:f8:2a:e1:e0:6e:0c:70:c3:75:fa:ad:71:7b:34:a4:9e:72:65 +-----BEGIN CERTIFICATE----- +MIIFojCCA4qgAwIBAgIUAZQwHqIL3fXFMyqxQ0Rx+NZQTQ0wDQYJKoZIhvcNAQEM +BQAwaTELMAkGA1UEBhMCS1IxJjAkBgNVBAoMHU5BVkVSIEJVU0lORVNTIFBMQVRG +T1JNIENvcnAuMTIwMAYDVQQDDClOQVZFUiBHbG9iYWwgUm9vdCBDZXJ0aWZpY2F0 +aW9uIEF1dGhvcml0eTAeFw0xNzA4MTgwODU4NDJaFw0zNzA4MTgyMzU5NTlaMGkx +CzAJBgNVBAYTAktSMSYwJAYDVQQKDB1OQVZFUiBCVVNJTkVTUyBQTEFURk9STSBD +b3JwLjEyMDAGA1UEAwwpTkFWRVIgR2xvYmFsIFJvb3QgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC21PGTXLVA +iQqrDZBbUGOukJR0F0Vy1ntlWilLp1agS7gvQnXp2XskWjFlqxcX0TM62RHcQDaH +38dq6SZeWYp34+hInDEW+j6RscrJo+KfziFTowI2MMtSAuXaMl3Dxeb57hHHi8lE +HoSTGEq0n+USZGnQJoViAbbJAh2+g1G7XNr4rRVqmfeSVPc0W+m/6imBEtRTkZaz +kVrd/pBzKPswRrXKCAfHcXLJZtM0l/aM9BhK4dA9WkW2aacp+yPOiNgSnABIqKYP +szuSjXEOdMWLyEz59JuOuDxp7W87UC9Y7cSw0BwbagzivESq2M0UXZR4Yb8Obtoq +vC8MC3GmsxY/nOb5zJ9TNeIDoKAYv7vxvvTWjIcNQvcGufFt7QSUqP620wbGQGHf +nZ3zVHbOUzoBppJB7ASjjw2i1QnK1sua8e9DXcCrpUHPXFNwcMmIpi3Ua2FzUCaG +YQ5fG8Ir4ozVu53BA0K6lNpfqbDKzE0K70dpAy8i+/Eozr9dUGWokG2zdLAIx6yo +0es+nPxdGoMuK8u180SdOqcXYZaicdNwlhVNt0xz7hlcxVs+Qf6sdWA7G2POAN3a +CJBitOUt7kinaxeZVL6HSuOpXgRM6xBtVNbv8ejyYhbLgGvtPe31HzClrkvJE+2K +AQHJuFFYwGY6sWZLxNUxAmLpdIQM201GLQIDAQABo0IwQDAdBgNVHQ4EFgQU0p+I +36HNLL3s9TsBAZMzJ7LrYEswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMB +Af8wDQYJKoZIhvcNAQEMBQADggIBADLKgLOdPVQG3dLSLvCkASELZ0jKbY7gyKoN +qo0hV4/GPnrK21HUUrPUloSlWGB/5QuOH/XcChWB5Tu2tyIvCZwTFrFsDDUIbatj +cu3cvuzHV+YwIHHW1xDBE1UBjCpD5EHxzzp6U5LOogMFDTjfArsQLtk70pt6wKGm ++LUx5vR1yblTmXVHIloUFcd4G7ad6Qz4G3bxhYTeodoS76TiEJd6eN4MUZeoIUCL +hr0N8F5OSza7OyAfikJW4Qsav3vQIkMsRIz75Sq0bBwcupTgE34h5prCy8VCZLQe +lHsIJchxzIdFV4XTnyliIoNRlwAYl3dqmJLJfGBs32x9SuRwTMKeuB330DTHD8z7 +p/8Dvq1wkNoL3chtl1+afwkyQf3NosxabUzyqkn+Zvjp2DXrDige7kgvOtB5CTh8 +piKCk5XQA76+AqAF3SAi428diDRgxuYKuQl1C/AH6GmWNcf7I4GOODm4RStDeKLR +LBT/DShycpWbXgnbiUSYqqFJu3FS8r/2/yehNq+4tneI3TqkbZs0kNwUXTC/t+sX +5Ie3cdCh13cV1ELX8vMxmV2b3RZtP+oGI/hGoiLtk/bdmuYqh7GYVPEi92tF4+KO +dh2ajcQGjTa3FPOdVGm3jjzVpG2Tgbet9r1ke8LJaDmgkpzNNIaRkPpkUZ3+/uul +9XXeifdy +-----END CERTIFICATE----- + +# Issuer: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres +# Subject: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres +# Label: "AC RAIZ FNMT-RCM SERVIDORES SEGUROS" +# Serial: 131542671362353147877283741781055151509 +# MD5 Fingerprint: 19:36:9c:52:03:2f:d2:d1:bb:23:cc:dd:1e:12:55:bb +# SHA1 Fingerprint: 62:ff:d9:9e:c0:65:0d:03:ce:75:93:d2:ed:3f:2d:32:c9:e3:e5:4a +# SHA256 Fingerprint: 55:41:53:b1:3d:2c:f9:dd:b7:53:bf:be:1a:4e:0a:e0:8d:0a:a4:18:70:58:fe:60:a2:b8:62:b2:e4:b8:7b:cb +-----BEGIN CERTIFICATE----- +MIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQsw +CQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgw +FgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1S +Q00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5 +MzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4wDAYDVQQL +DAVDZXJlczEYMBYGA1UEYQwPVkFURVMtUTI4MjYwMDRKMSwwKgYDVQQDDCNBQyBS +QUlaIEZOTVQtUkNNIFNFUlZJRE9SRVMgU0VHVVJPUzB2MBAGByqGSM49AgEGBSuB +BAAiA2IABPa6V1PIyqvfNkpSIeSX0oNnnvBlUdBeh8dHsVnyV0ebAAKTRBdp20LH +sbI6GA60XYyzZl2hNPk2LEnb80b8s0RpRBNm/dfF/a82Tc4DTQdxz69qBdKiQ1oK +Um8BA06Oi6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD +VR0OBBYEFAG5L++/EYZg8k/QQW6rcx/n0m5JMAoGCCqGSM49BAMDA2kAMGYCMQCu +SuMrQMN0EfKVrRYj3k4MGuZdpSRea0R7/DjiT8ucRRcRTBQnJlU5dUoDzBOQn5IC +MQD6SmxgiHPz7riYYqnOK8LZiqZwMR2vsJRM60/G49HzYqc8/5MuB1xJAWdpEgJy +v+c= +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign Root R46 O=GlobalSign nv-sa +# Subject: CN=GlobalSign Root R46 O=GlobalSign nv-sa +# Label: "GlobalSign Root R46" +# Serial: 1552617688466950547958867513931858518042577 +# MD5 Fingerprint: c4:14:30:e4:fa:66:43:94:2a:6a:1b:24:5f:19:d0:ef +# SHA1 Fingerprint: 53:a2:b0:4b:ca:6b:d6:45:e6:39:8a:8e:c4:0d:d2:bf:77:c3:a2:90 +# SHA256 Fingerprint: 4f:a3:12:6d:8d:3a:11:d1:c4:85:5a:4f:80:7c:ba:d6:cf:91:9d:3a:5a:88:b0:3b:ea:2c:63:72:d9:3c:40:c9 +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA +MEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD +VQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy +MDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt +c2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ +OaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG +vGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud +316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo +0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE +y132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF +zXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE ++cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN +I/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs +x2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa +ByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC +4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4 +7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg +JuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti +2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk +pnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF +FRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt +rWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk +ZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5 +u+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP +4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6 +N3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3 +vouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6 +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign Root E46 O=GlobalSign nv-sa +# Subject: CN=GlobalSign Root E46 O=GlobalSign nv-sa +# Label: "GlobalSign Root E46" +# Serial: 1552617690338932563915843282459653771421763 +# MD5 Fingerprint: b5:b8:66:ed:de:08:83:e3:c9:e2:01:34:06:ac:51:6f +# SHA1 Fingerprint: 39:b4:6c:d5:fe:80:06:eb:e2:2f:4a:bb:08:33:a0:af:db:b9:dd:84 +# SHA256 Fingerprint: cb:b9:c4:4d:84:b8:04:3e:10:50:ea:31:a6:9f:51:49:55:d7:bf:d2:e2:c6:b4:93:01:01:9a:d6:1d:9f:50:58 +-----BEGIN CERTIFICATE----- +MIICCzCCAZGgAwIBAgISEdK7ujNu1LzmJGjFDYQdmOhDMAoGCCqGSM49BAMDMEYx +CzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYDVQQD +ExNHbG9iYWxTaWduIFJvb3QgRTQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMyMDAw +MDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2Ex +HDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAScDrHPt+ieUnd1NPqlRqetMhkytAepJ8qUuwzSChDH2omwlwxwEwkBjtjq +R+q+soArzfwoDdusvKSGN+1wCAB16pMLey5SnCNoIwZD7JIvU4Tb+0cUB+hflGdd +yXqBPCCjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud +DgQWBBQxCpCPtsad0kRLgLWi5h+xEk8blTAKBggqhkjOPQQDAwNoADBlAjEA31SQ +7Zvvi5QCkxeCmb6zniz2C5GMn0oUsfZkvLtoURMMA/cVi4RguYv/Uo7njLwcAjA8 ++RHUjE7AwWHCFUyqqx0LMV87HOIAl0Qx5v5zli/altP+CAezNIm8BZ/3Hobui3A= +-----END CERTIFICATE----- + +# Issuer: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz +# Subject: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz +# Label: "ANF Secure Server Root CA" +# Serial: 996390341000653745 +# MD5 Fingerprint: 26:a6:44:5a:d9:af:4e:2f:b2:1d:b6:65:b0:4e:e8:96 +# SHA1 Fingerprint: 5b:6e:68:d0:cc:15:b6:a0:5f:1e:c1:5f:ae:02:fc:6b:2f:5d:6f:74 +# SHA256 Fingerprint: fb:8f:ec:75:91:69:b9:10:6b:1e:51:16:44:c6:18:c5:13:04:37:3f:6c:06:43:08:8d:8b:ef:fd:1b:99:75:99 +-----BEGIN CERTIFICATE----- +MIIF7zCCA9egAwIBAgIIDdPjvGz5a7EwDQYJKoZIhvcNAQELBQAwgYQxEjAQBgNV +BAUTCUc2MzI4NzUxMDELMAkGA1UEBhMCRVMxJzAlBgNVBAoTHkFORiBBdXRvcmlk +YWQgZGUgQ2VydGlmaWNhY2lvbjEUMBIGA1UECxMLQU5GIENBIFJhaXoxIjAgBgNV +BAMTGUFORiBTZWN1cmUgU2VydmVyIFJvb3QgQ0EwHhcNMTkwOTA0MTAwMDM4WhcN +MzkwODMwMTAwMDM4WjCBhDESMBAGA1UEBRMJRzYzMjg3NTEwMQswCQYDVQQGEwJF +UzEnMCUGA1UEChMeQU5GIEF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uMRQwEgYD +VQQLEwtBTkYgQ0EgUmFpejEiMCAGA1UEAxMZQU5GIFNlY3VyZSBTZXJ2ZXIgUm9v +dCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANvrayvmZFSVgpCj +cqQZAZ2cC4Ffc0m6p6zzBE57lgvsEeBbphzOG9INgxwruJ4dfkUyYA8H6XdYfp9q +yGFOtibBTI3/TO80sh9l2Ll49a2pcbnvT1gdpd50IJeh7WhM3pIXS7yr/2WanvtH +2Vdy8wmhrnZEE26cLUQ5vPnHO6RYPUG9tMJJo8gN0pcvB2VSAKduyK9o7PQUlrZX +H1bDOZ8rbeTzPvY1ZNoMHKGESy9LS+IsJJ1tk0DrtSOOMspvRdOoiXsezx76W0OL +zc2oD2rKDF65nkeP8Nm2CgtYZRczuSPkdxl9y0oukntPLxB3sY0vaJxizOBQ+OyR +p1RMVwnVdmPF6GUe7m1qzwmd+nxPrWAI/VaZDxUse6mAq4xhj0oHdkLePfTdsiQz +W7i1o0TJrH93PB0j7IKppuLIBkwC/qxcmZkLLxCKpvR/1Yd0DVlJRfbwcVw5Kda/ +SiOL9V8BY9KHcyi1Swr1+KuCLH5zJTIdC2MKF4EA/7Z2Xue0sUDKIbvVgFHlSFJn +LNJhiQcND85Cd8BEc5xEUKDbEAotlRyBr+Qc5RQe8TZBAQIvfXOn3kLMTOmJDVb3 +n5HUA8ZsyY/b2BzgQJhdZpmYgG4t/wHFzstGH6wCxkPmrqKEPMVOHj1tyRRM4y5B +u8o5vzY8KhmqQYdOpc5LMnndkEl/AgMBAAGjYzBhMB8GA1UdIwQYMBaAFJxf0Gxj +o1+TypOYCK2Mh6UsXME3MB0GA1UdDgQWBBScX9BsY6Nfk8qTmAitjIelLFzBNzAO +BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC +AgEATh65isagmD9uw2nAalxJUqzLK114OMHVVISfk/CHGT0sZonrDUL8zPB1hT+L +9IBdeeUXZ701guLyPI59WzbLWoAAKfLOKyzxj6ptBZNscsdW699QIyjlRRA96Gej +rw5VD5AJYu9LWaL2U/HANeQvwSS9eS9OICI7/RogsKQOLHDtdD+4E5UGUcjohybK +pFtqFiGS3XNgnhAY3jyB6ugYw3yJ8otQPr0R4hUDqDZ9MwFsSBXXiJCZBMXM5gf0 +vPSQ7RPi6ovDj6MzD8EpTBNO2hVWcXNyglD2mjN8orGoGjR0ZVzO0eurU+AagNjq +OknkJjCb5RyKqKkVMoaZkgoQI1YS4PbOTOK7vtuNknMBZi9iPrJyJ0U27U1W45eZ +/zo1PqVUSlJZS2Db7v54EX9K3BR5YLZrZAPbFYPhor72I5dQ8AkzNqdxliXzuUJ9 +2zg/LFis6ELhDtjTO0wugumDLmsx2d1Hhk9tl5EuT+IocTUW0fJz/iUrB0ckYyfI ++PbZa/wSMVYIwFNCr5zQM378BvAxRAMU8Vjq8moNqRGyg77FGr8H6lnco4g175x2 +MjxNBiLOFeXdntiP2t7SxDnlF4HPOEfrf4htWRvfn0IUrn7PqLBmZdo3r5+qPeoo +tt7VMVgWglvquxl1AnMaykgaIZOQCo6ThKd9OyMYkomgjaw= +-----END CERTIFICATE----- + +# Issuer: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Subject: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Label: "Certum EC-384 CA" +# Serial: 160250656287871593594747141429395092468 +# MD5 Fingerprint: b6:65:b3:96:60:97:12:a1:ec:4e:e1:3d:a3:c6:c9:f1 +# SHA1 Fingerprint: f3:3e:78:3c:ac:df:f4:a2:cc:ac:67:55:69:56:d7:e5:16:3c:e1:ed +# SHA256 Fingerprint: 6b:32:80:85:62:53:18:aa:50:d1:73:c9:8d:8b:da:09:d5:7e:27:41:3d:11:4c:f7:87:a0:f5:d0:6c:03:0c:f6 +-----BEGIN CERTIFICATE----- +MIICZTCCAeugAwIBAgIQeI8nXIESUiClBNAt3bpz9DAKBggqhkjOPQQDAzB0MQsw +CQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEuMScw +JQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAXBgNVBAMT +EENlcnR1bSBFQy0zODQgQ0EwHhcNMTgwMzI2MDcyNDU0WhcNNDMwMzI2MDcyNDU0 +WjB0MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBT +LkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAX +BgNVBAMTEENlcnR1bSBFQy0zODQgQ0EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATE +KI6rGFtqvm5kN2PkzeyrOvfMobgOgknXhimfoZTy42B4mIF4Bk3y7JoOV2CDn7Tm +Fy8as10CW4kjPMIRBSqniBMY81CE1700LCeJVf/OTOffph8oxPBUw7l8t1Ot68Kj +QjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI0GZnQkdjrzife81r1HfS+8 +EF9LMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNoADBlAjADVS2m5hjEfO/J +UG7BJw+ch69u1RsIGL2SKcHvlJF40jocVYli5RsJHrpka/F2tNQCMQC0QoSZ/6vn +nvuRlydd3LBbMHHOXjgaatkl5+r3YZJW+OraNsKHZZYuciUvf9/DE8k= +-----END CERTIFICATE----- + +# Issuer: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Subject: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority +# Label: "Certum Trusted Root CA" +# Serial: 40870380103424195783807378461123655149 +# MD5 Fingerprint: 51:e1:c2:e7:fe:4c:84:af:59:0e:2f:f4:54:6f:ea:29 +# SHA1 Fingerprint: c8:83:44:c0:18:ae:9f:cc:f1:87:b7:8f:22:d1:c5:d7:45:84:ba:e5 +# SHA256 Fingerprint: fe:76:96:57:38:55:77:3e:37:a9:5e:7a:d4:d9:cc:96:c3:01:57:c1:5d:31:76:5b:a9:b1:57:04:e1:ae:78:fd +-----BEGIN CERTIFICATE----- +MIIFwDCCA6igAwIBAgIQHr9ZULjJgDdMBvfrVU+17TANBgkqhkiG9w0BAQ0FADB6 +MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEu +MScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxHzAdBgNV +BAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwHhcNMTgwMzE2MTIxMDEzWhcNNDMw +MzE2MTIxMDEzWjB6MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEg +U3lzdGVtcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRo +b3JpdHkxHzAdBgNVBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwggIiMA0GCSqG +SIb3DQEBAQUAA4ICDwAwggIKAoICAQDRLY67tzbqbTeRn06TpwXkKQMlzhyC93yZ +n0EGze2jusDbCSzBfN8pfktlL5On1AFrAygYo9idBcEq2EXxkd7fO9CAAozPOA/q +p1x4EaTByIVcJdPTsuclzxFUl6s1wB52HO8AU5853BSlLCIls3Jy/I2z5T4IHhQq +NwuIPMqw9MjCoa68wb4pZ1Xi/K1ZXP69VyywkI3C7Te2fJmItdUDmj0VDT06qKhF +8JVOJVkdzZhpu9PMMsmN74H+rX2Ju7pgE8pllWeg8xn2A1bUatMn4qGtg/BKEiJ3 +HAVz4hlxQsDsdUaakFjgao4rpUYwBI4Zshfjvqm6f1bxJAPXsiEodg42MEx51UGa +mqi4NboMOvJEGyCI98Ul1z3G4z5D3Yf+xOr1Uz5MZf87Sst4WmsXXw3Hw09Omiqi +7VdNIuJGmj8PkTQkfVXjjJU30xrwCSss0smNtA0Aq2cpKNgB9RkEth2+dv5yXMSF +ytKAQd8FqKPVhJBPC/PgP5sZ0jeJP/J7UhyM9uH3PAeXjA6iWYEMspA90+NZRu0P +qafegGtaqge2Gcu8V/OXIXoMsSt0Puvap2ctTMSYnjYJdmZm/Bo/6khUHL4wvYBQ +v3y1zgD2DGHZ5yQD4OMBgQ692IU0iL2yNqh7XAjlRICMb/gv1SHKHRzQ+8S1h9E6 +Tsd2tTVItQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSM+xx1 +vALTn04uSNn5YFSqxLNP+jAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQENBQAD +ggIBAEii1QALLtA/vBzVtVRJHlpr9OTy4EA34MwUe7nJ+jW1dReTagVphZzNTxl4 +WxmB82M+w85bj/UvXgF2Ez8sALnNllI5SW0ETsXpD4YN4fqzX4IS8TrOZgYkNCvo +zMrnadyHncI013nR03e4qllY/p0m+jiGPp2Kh2RX5Rc64vmNueMzeMGQ2Ljdt4NR +5MTMI9UGfOZR0800McD2RrsLrfw9EAUqO0qRJe6M1ISHgCq8CYyqOhNf6DR5UMEQ +GfnTKB7U0VEwKbOukGfWHwpjscWpxkIxYxeU72nLL/qMFH3EQxiJ2fAyQOaA4kZf +5ePBAFmo+eggvIksDkc0C+pXwlM2/KfUrzHN/gLldfq5Jwn58/U7yn2fqSLLiMmq +0Uc9NneoWWRrJ8/vJ8HjJLWG965+Mk2weWjROeiQWMODvA8s1pfrzgzhIMfatz7D +P78v3DSk+yshzWePS/Tj6tQ/50+6uaWTRRxmHyH6ZF5v4HaUMst19W7l9o/HuKTM +qJZ9ZPskWkoDbGs4xugDQ5r3V7mzKWmTOPQD8rv7gmsHINFSH5pkAnuYZttcTVoP +0ISVoDwUQwbKytu4QTbaakRnh6+v40URFWkIsr4WOZckbxJF0WddCajJFdr60qZf +E2Efv4WstK2tBZQIgx51F9NxO5NQI1mg7TyRVJ12AMXDuDjb +-----END CERTIFICATE----- + +# Issuer: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique +# Subject: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique +# Label: "TunTrust Root CA" +# Serial: 108534058042236574382096126452369648152337120275 +# MD5 Fingerprint: 85:13:b9:90:5b:36:5c:b6:5e:b8:5a:f8:e0:31:57:b4 +# SHA1 Fingerprint: cf:e9:70:84:0f:e0:73:0f:9d:f6:0c:7f:2c:4b:ee:20:46:34:9c:bb +# SHA256 Fingerprint: 2e:44:10:2a:b5:8c:b8:54:19:45:1c:8e:19:d9:ac:f3:66:2c:af:bc:61:4b:6a:53:96:0a:30:f7:d0:e2:eb:41 +-----BEGIN CERTIFICATE----- +MIIFszCCA5ugAwIBAgIUEwLV4kBMkkaGFmddtLu7sms+/BMwDQYJKoZIhvcNAQEL +BQAwYTELMAkGA1UEBhMCVE4xNzA1BgNVBAoMLkFnZW5jZSBOYXRpb25hbGUgZGUg +Q2VydGlmaWNhdGlvbiBFbGVjdHJvbmlxdWUxGTAXBgNVBAMMEFR1blRydXN0IFJv +b3QgQ0EwHhcNMTkwNDI2MDg1NzU2WhcNNDQwNDI2MDg1NzU2WjBhMQswCQYDVQQG +EwJUTjE3MDUGA1UECgwuQWdlbmNlIE5hdGlvbmFsZSBkZSBDZXJ0aWZpY2F0aW9u +IEVsZWN0cm9uaXF1ZTEZMBcGA1UEAwwQVHVuVHJ1c3QgUm9vdCBDQTCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAMPN0/y9BFPdDCA61YguBUtB9YOCfvdZ +n56eY+hz2vYGqU8ftPkLHzmMmiDQfgbU7DTZhrx1W4eI8NLZ1KMKsmwb60ksPqxd +2JQDoOw05TDENX37Jk0bbjBU2PWARZw5rZzJJQRNmpA+TkBuimvNKWfGzC3gdOgF +VwpIUPp6Q9p+7FuaDmJ2/uqdHYVy7BG7NegfJ7/Boce7SBbdVtfMTqDhuazb1YMZ +GoXRlJfXyqNlC/M4+QKu3fZnz8k/9YosRxqZbwUN/dAdgjH8KcwAWJeRTIAAHDOF +li/LQcKLEITDCSSJH7UP2dl3RxiSlGBcx5kDPP73lad9UKGAwqmDrViWVSHbhlnU +r8a83YFuB9tgYv7sEG7aaAH0gxupPqJbI9dkxt/con3YS7qC0lH4Zr8GRuR5KiY2 +eY8fTpkdso8MDhz/yV3A/ZAQprE38806JG60hZC/gLkMjNWb1sjxVj8agIl6qeIb +MlEsPvLfe/ZdeikZjuXIvTZxi11Mwh0/rViizz1wTaZQmCXcI/m4WEEIcb9PuISg +jwBUFfyRbVinljvrS5YnzWuioYasDXxU5mZMZl+QviGaAkYt5IPCgLnPSz7ofzwB +7I9ezX/SKEIBlYrilz0QIX32nRzFNKHsLA4KUiwSVXAkPcvCFDVDXSdOvsC9qnyW +5/yeYa1E0wCXAgMBAAGjYzBhMB0GA1UdDgQWBBQGmpsfU33x9aTI04Y+oXNZtPdE +ITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFAaamx9TffH1pMjThj6hc1m0 +90QhMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAqgVutt0Vyb+z +xiD2BkewhpMl0425yAA/l/VSJ4hxyXT968pk21vvHl26v9Hr7lxpuhbI87mP0zYu +QEkHDVneixCwSQXi/5E/S7fdAo74gShczNxtr18UnH1YeA32gAm56Q6XKRm4t+v4 +FstVEuTGfbvE7Pi1HE4+Z7/FXxttbUcoqgRYYdZ2vyJ/0Adqp2RT8JeNnYA/u8EH +22Wv5psymsNUk8QcCMNE+3tjEUPRahphanltkE8pjkcFwRJpadbGNjHh/PqAulxP +xOu3Mqz4dWEX1xAZufHSCe96Qp1bWgvUxpVOKs7/B9dPfhgGiPEZtdmYu65xxBzn +dFlY7wyJz4sfdZMaBBSSSFCp61cpABbjNhzI+L/wM9VBD8TMPN3pM0MBkRArHtG5 +Xc0yGYuPjCB31yLEQtyEFpslbei0VXF/sHyz03FJuc9SpAQ/3D2gu68zngowYI7b +nV2UqL1g52KAdoGDDIzMMEZJ4gzSqK/rYXHv5yJiqfdcZGyfFoxnNidF9Ql7v/YQ +CvGwjVRDjAS6oz/v4jXH+XTgbzRB0L9zZVcg+ZtnemZoJE6AZb0QmQZZ8mWvuMZH +u/2QeItBcy6vVR/cO5JyboTT0GFMDcx2V+IthSIVNg3rAZ3r2OvEhJn7wAzMMujj +d9qDRIueVSjAi1jTkD5OGwDxFa2DK5o= +-----END CERTIFICATE----- + +# Issuer: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Subject: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Label: "HARICA TLS RSA Root CA 2021" +# Serial: 76817823531813593706434026085292783742 +# MD5 Fingerprint: 65:47:9b:58:86:dd:2c:f0:fc:a2:84:1f:1e:96:c4:91 +# SHA1 Fingerprint: 02:2d:05:82:fa:88:ce:14:0c:06:79:de:7f:14:10:e9:45:d7:a5:6d +# SHA256 Fingerprint: d9:5d:0e:8e:da:79:52:5b:f9:be:b1:1b:14:d2:10:0d:32:94:98:5f:0c:62:d9:fa:bd:9c:d9:99:ec:cb:7b:1d +-----BEGIN CERTIFICATE----- +MIIFpDCCA4ygAwIBAgIQOcqTHO9D88aOk8f0ZIk4fjANBgkqhkiG9w0BAQsFADBs +MQswCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl +c2VhcmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBSU0Eg +Um9vdCBDQSAyMDIxMB4XDTIxMDIxOTEwNTUzOFoXDTQ1MDIxMzEwNTUzN1owbDEL +MAkGA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl +YXJjaCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgUlNBIFJv +b3QgQ0EgMjAyMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAIvC569l +mwVnlskNJLnQDmT8zuIkGCyEf3dRywQRNrhe7Wlxp57kJQmXZ8FHws+RFjZiPTgE +4VGC/6zStGndLuwRo0Xua2s7TL+MjaQenRG56Tj5eg4MmOIjHdFOY9TnuEFE+2uv +a9of08WRiFukiZLRgeaMOVig1mlDqa2YUlhu2wr7a89o+uOkXjpFc5gH6l8Cct4M +pbOfrqkdtx2z/IpZ525yZa31MJQjB/OCFks1mJxTuy/K5FrZx40d/JiZ+yykgmvw +Kh+OC19xXFyuQnspiYHLA6OZyoieC0AJQTPb5lh6/a6ZcMBaD9YThnEvdmn8kN3b +LW7R8pv1GmuebxWMevBLKKAiOIAkbDakO/IwkfN4E8/BPzWr8R0RI7VDIp4BkrcY +AuUR0YLbFQDMYTfBKnya4dC6s1BG7oKsnTH4+yPiAwBIcKMJJnkVU2DzOFytOOqB +AGMUuTNe3QvboEUHGjMJ+E20pwKmafTCWQWIZYVWrkvL4N48fS0ayOn7H6NhStYq +E613TBoYm5EPWNgGVMWX+Ko/IIqmhaZ39qb8HOLubpQzKoNQhArlT4b4UEV4AIHr +W2jjJo3Me1xR9BQsQL4aYB16cmEdH2MtiKrOokWQCPxrvrNQKlr9qEgYRtaQQJKQ +CoReaDH46+0N0x3GfZkYVVYnZS6NRcUk7M7jAgMBAAGjQjBAMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFApII6ZgpJIKM+qTW8VX6iVNvRLuMA4GA1UdDwEB/wQE +AwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAPpBIqm5iFSVmewzVjIuJndftTgfvnNAU +X15QvWiWkKQUEapobQk1OUAJ2vQJLDSle1mESSmXdMgHHkdt8s4cUCbjnj1AUz/3 +f5Z2EMVGpdAgS1D0NTsY9FVqQRtHBmg8uwkIYtlfVUKqrFOFrJVWNlar5AWMxaja +H6NpvVMPxP/cyuN+8kyIhkdGGvMA9YCRotxDQpSbIPDRzbLrLFPCU3hKTwSUQZqP +JzLB5UkZv/HywouoCjkxKLR9YjYsTewfM7Z+d21+UPCfDtcRj88YxeMn/ibvBZ3P +zzfF0HvaO7AWhAw6k9a+F9sPPg4ZeAnHqQJyIkv3N3a6dcSFA1pj1bF1BcK5vZSt +jBWZp5N99sXzqnTPBIWUmAD04vnKJGW/4GKvyMX6ssmeVkjaef2WdhW+o45WxLM0 +/L5H9MG0qPzVMIho7suuyWPEdr6sOBjhXlzPrjoiUevRi7PzKzMHVIf6tLITe7pT +BGIBnfHAT+7hOtSLIBD6Alfm78ELt5BGnBkpjNxvoEppaZS3JGWg/6w/zgH7IS79 +aPib8qXPMThcFarmlwDB31qlpzmq6YR/PFGoOtmUW4y/Twhx5duoXNTSpv4Ao8YW +xw/ogM4cKGR0GQjTQuPOAF1/sdwTsOEFy9EgqoZ0njnnkf3/W9b3raYvAwtt41dU +63ZTGI0RmLo= +-----END CERTIFICATE----- + +# Issuer: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Subject: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA +# Label: "HARICA TLS ECC Root CA 2021" +# Serial: 137515985548005187474074462014555733966 +# MD5 Fingerprint: ae:f7:4c:e5:66:35:d1:b7:9b:8c:22:93:74:d3:4b:b0 +# SHA1 Fingerprint: bc:b0:c1:9d:e9:98:92:70:19:38:57:e9:8d:a7:b4:5d:6e:ee:01:48 +# SHA256 Fingerprint: 3f:99:cc:47:4a:cf:ce:4d:fe:d5:87:94:66:5e:47:8d:15:47:73:9f:2e:78:0f:1b:b4:ca:9b:13:30:97:d4:01 +-----BEGIN CERTIFICATE----- +MIICVDCCAdugAwIBAgIQZ3SdjXfYO2rbIvT/WeK/zjAKBggqhkjOPQQDAzBsMQsw +CQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2Vh +cmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBFQ0MgUm9v +dCBDQSAyMDIxMB4XDTIxMDIxOTExMDExMFoXDTQ1MDIxMzExMDEwOVowbDELMAkG +A1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj +aCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgRUNDIFJvb3Qg +Q0EgMjAyMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABDgI/rGgltJ6rK9JOtDA4MM7 +KKrxcm1lAEeIhPyaJmuqS7psBAqIXhfyVYf8MLA04jRYVxqEU+kw2anylnTDUR9Y +STHMmE5gEYd103KUkE+bECUqqHgtvpBBWJAVcqeht6NCMEAwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUyRtTgRL+BNUW0aq8mm+3oJUZbsowDgYDVR0PAQH/BAQD +AgGGMAoGCCqGSM49BAMDA2cAMGQCMBHervjcToiwqfAircJRQO9gcS3ujwLEXQNw +SaSS6sUUiHCm0w2wqsosQJz76YJumgIwK0eaB8bRwoF8yguWGEEbo/QwCZ61IygN +nxS2PFOiTAZpffpskcYqSUXm7LcT4Tps +-----END CERTIFICATE----- + +# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 +# Label: "Autoridad de Certificacion Firmaprofesional CIF A62634068" +# Serial: 1977337328857672817 +# MD5 Fingerprint: 4e:6e:9b:54:4c:ca:b7:fa:48:e4:90:b1:15:4b:1c:a3 +# SHA1 Fingerprint: 0b:be:c2:27:22:49:cb:39:aa:db:35:5c:53:e3:8c:ae:78:ff:b6:fe +# SHA256 Fingerprint: 57:de:05:83:ef:d2:b2:6e:03:61:da:99:da:9d:f4:64:8d:ef:7e:e8:44:1c:3b:72:8a:fa:9b:cd:e0:f9:b2:6a +-----BEGIN CERTIFICATE----- +MIIGFDCCA/ygAwIBAgIIG3Dp0v+ubHEwDQYJKoZIhvcNAQELBQAwUTELMAkGA1UE +BhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h +cHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0xNDA5MjMxNTIyMDdaFw0zNjA1 +MDUxNTIyMDdaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg +Q2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9 +thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM +cas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG +L9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i +NA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h +X68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b +m8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy +Z/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja +EbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T +KI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF +6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh +OSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMB0GA1UdDgQWBBRlzeurNR4APn7VdMAc +tHNHDhpkLzASBgNVHRMBAf8ECDAGAQH/AgEBMIGmBgNVHSAEgZ4wgZswgZgGBFUd +IAAwgY8wLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuZmlybWFwcm9mZXNpb25hbC5j +b20vY3BzMFwGCCsGAQUFBwICMFAeTgBQAGEAcwBlAG8AIABkAGUAIABsAGEAIABC +AG8AbgBhAG4AbwB2AGEAIAA0ADcAIABCAGEAcgBjAGUAbABvAG4AYQAgADAAOAAw +ADEANzAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggIBAHSHKAIrdx9m +iWTtj3QuRhy7qPj4Cx2Dtjqn6EWKB7fgPiDL4QjbEwj4KKE1soCzC1HA01aajTNF +Sa9J8OA9B3pFE1r/yJfY0xgsfZb43aJlQ3CTkBW6kN/oGbDbLIpgD7dvlAceHabJ +hfa9NPhAeGIQcDq+fUs5gakQ1JZBu/hfHAsdCPKxsIl68veg4MSPi3i1O1ilI45P +Vf42O+AMt8oqMEEgtIDNrvx2ZnOorm7hfNoD6JQg5iKj0B+QXSBTFCZX2lSX3xZE +EAEeiGaPcjiT3SC3NL7X8e5jjkd5KAb881lFJWAiMxujX6i6KtoaPc1A6ozuBRWV +1aUsIC+nmCjuRfzxuIgALI9C2lHVnOUTaHFFQ4ueCyE8S1wF3BqfmI7avSKecs2t +CsvMo2ebKHTEm9caPARYpoKdrcd7b/+Alun4jWq9GJAd/0kakFI3ky88Al2CdgtR +5xbHV/g4+afNmyJU72OwFW1TZQNKXkqgsqeOSQBZONXH9IBk9W6VULgRfhVwOEqw +f9DEMnDAGf/JOC0ULGb0QkTmVXYbgBVX/8Cnp6o5qtjTcNAuuuuUavpfNIbnYrX9 +ivAwhZTJryQCL2/W3Wf+47BVTwSYT6RBVuKT0Gro1vP7ZeDOdcQxWQzugsgMYDNK +GbqEZycPvEJdvSRUDewdcAZfpLz6IHxV +-----END CERTIFICATE----- + +# Issuer: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. +# Subject: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd. +# Label: "vTrus ECC Root CA" +# Serial: 630369271402956006249506845124680065938238527194 +# MD5 Fingerprint: de:4b:c1:f5:52:8c:9b:43:e1:3e:8f:55:54:17:8d:85 +# SHA1 Fingerprint: f6:9c:db:b0:fc:f6:02:13:b6:52:32:a6:a3:91:3f:16:70:da:c3:e1 +# SHA256 Fingerprint: 30:fb:ba:2c:32:23:8e:2a:98:54:7a:f9:79:31:e5:50:42:8b:9b:3f:1c:8e:eb:66:33:dc:fa:86:c5:b2:7d:d3 +-----BEGIN CERTIFICATE----- +MIICDzCCAZWgAwIBAgIUbmq8WapTvpg5Z6LSa6Q75m0c1towCgYIKoZIzj0EAwMw +RzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4xGjAY +BgNVBAMTEXZUcnVzIEVDQyBSb290IENBMB4XDTE4MDczMTA3MjY0NFoXDTQzMDcz +MTA3MjY0NFowRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28u +LEx0ZC4xGjAYBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMHYwEAYHKoZIzj0CAQYF +K4EEACIDYgAEZVBKrox5lkqqHAjDo6LN/llWQXf9JpRCux3NCNtzslt188+cToL0 +v/hhJoVs1oVbcnDS/dtitN9Ti72xRFhiQgnH+n9bEOf+QP3A2MMrMudwpremIFUd +e4BdS49nTPEQo0IwQDAdBgNVHQ4EFgQUmDnNvtiyjPeyq+GtJK97fKHbH88wDwYD +VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIw +V53dVvHH4+m4SVBrm2nDb+zDfSXkV5UTQJtS0zvzQBm8JsctBp61ezaf9SXUY2sA +AjEA6dPGnlaaKsyh2j/IZivTWJwghfqrkYpwcBE4YGQLYgmRWAD5Tfs0aNoJrSEG +GJTO +-----END CERTIFICATE----- + +# Issuer: CN=vTrus Root CA O=iTrusChina Co.,Ltd. +# Subject: CN=vTrus Root CA O=iTrusChina Co.,Ltd. +# Label: "vTrus Root CA" +# Serial: 387574501246983434957692974888460947164905180485 +# MD5 Fingerprint: b8:c9:37:df:fa:6b:31:84:64:c5:ea:11:6a:1b:75:fc +# SHA1 Fingerprint: 84:1a:69:fb:f5:cd:1a:25:34:13:3d:e3:f8:fc:b8:99:d0:c9:14:b7 +# SHA256 Fingerprint: 8a:71:de:65:59:33:6f:42:6c:26:e5:38:80:d0:0d:88:a1:8d:a4:c6:a9:1f:0d:cb:61:94:e2:06:c5:c9:63:87 +-----BEGIN CERTIFICATE----- +MIIFVjCCAz6gAwIBAgIUQ+NxE9izWRRdt86M/TX9b7wFjUUwDQYJKoZIhvcNAQEL +BQAwQzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4x +FjAUBgNVBAMTDXZUcnVzIFJvb3QgQ0EwHhcNMTgwNzMxMDcyNDA1WhcNNDMwNzMx +MDcyNDA1WjBDMQswCQYDVQQGEwJDTjEcMBoGA1UEChMTaVRydXNDaGluYSBDby4s +THRkLjEWMBQGA1UEAxMNdlRydXMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAL1VfGHTuB0EYgWgrmy3cLRB6ksDXhA/kFocizuwZotsSKYc +IrrVQJLuM7IjWcmOvFjai57QGfIvWcaMY1q6n6MLsLOaXLoRuBLpDLvPbmyAhykU +AyyNJJrIZIO1aqwTLDPxn9wsYTwaP3BVm60AUn/PBLn+NvqcwBauYv6WTEN+VRS+ +GrPSbcKvdmaVayqwlHeFXgQPYh1jdfdr58tbmnDsPmcF8P4HCIDPKNsFxhQnL4Z9 +8Cfe/+Z+M0jnCx5Y0ScrUw5XSmXX+6KAYPxMvDVTAWqXcoKv8R1w6Jz1717CbMdH +flqUhSZNO7rrTOiwCcJlwp2dCZtOtZcFrPUGoPc2BX70kLJrxLT5ZOrpGgrIDajt +J8nU57O5q4IikCc9Kuh8kO+8T/3iCiSn3mUkpF3qwHYw03dQ+A0Em5Q2AXPKBlim +0zvc+gRGE1WKyURHuFE5Gi7oNOJ5y1lKCn+8pu8fA2dqWSslYpPZUxlmPCdiKYZN +pGvu/9ROutW04o5IWgAZCfEF2c6Rsffr6TlP9m8EQ5pV9T4FFL2/s1m02I4zhKOQ +UqqzApVg+QxMaPnu1RcN+HFXtSXkKe5lXa/R7jwXC1pDxaWG6iSe4gUH3DRCEpHW +OXSuTEGC2/KmSNGzm/MzqvOmwMVO9fSddmPmAsYiS8GVP1BkLFTltvA8Kc9XAgMB +AAGjQjBAMB0GA1UdDgQWBBRUYnBj8XWEQ1iO0RYgscasGrz2iTAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAKbqSSaet +8PFww+SX8J+pJdVrnjT+5hpk9jprUrIQeBqfTNqK2uwcN1LgQkv7bHbKJAs5EhWd +nxEt/Hlk3ODg9d3gV8mlsnZwUKT+twpw1aA08XXXTUm6EdGz2OyC/+sOxL9kLX1j +bhd47F18iMjrjld22VkE+rxSH0Ws8HqA7Oxvdq6R2xCOBNyS36D25q5J08FsEhvM +Kar5CKXiNxTKsbhm7xqC5PD48acWabfbqWE8n/Uxy+QARsIvdLGx14HuqCaVvIiv +TDUHKgLKeBRtRytAVunLKmChZwOgzoy8sHJnxDHO2zTlJQNgJXtxmOTAGytfdELS +S8VZCAeHvsXDf+eW2eHcKJfWjwXj9ZtOyh1QRwVTsMo554WgicEFOwE30z9J4nfr +I8iIZjs9OXYhRvHsXyO466JmdXTBQPfYaJqT4i2pLr0cox7IdMakLXogqzu4sEb9 +b91fUlV1YvCXoHzXOP0l382gmxDPi7g4Xl7FtKYCNqEeXxzP4padKar9mK5S4fNB +UvupLnKWnyfjqnN9+BojZns7q2WwMgFLFT49ok8MKzWixtlnEjUwzXYuFrOZnk1P +Ti07NEPhmg4NpGaXutIcSkwsKouLgU9xGqndXHt7CMUADTdA43x7VF8vhV929ven +sBxXVsFy6K2ir40zSbofitzmdHxghm+Hl3s= +-----END CERTIFICATE----- + +# Issuer: CN=ISRG Root X2 O=Internet Security Research Group +# Subject: CN=ISRG Root X2 O=Internet Security Research Group +# Label: "ISRG Root X2" +# Serial: 87493402998870891108772069816698636114 +# MD5 Fingerprint: d3:9e:c4:1e:23:3c:a6:df:cf:a3:7e:6d:e0:14:e6:e5 +# SHA1 Fingerprint: bd:b1:b9:3c:d5:97:8d:45:c6:26:14:55:f8:db:95:c7:5a:d1:53:af +# SHA256 Fingerprint: 69:72:9b:8e:15:a8:6e:fc:17:7a:57:af:b7:17:1d:fc:64:ad:d2:8c:2f:ca:8c:f1:50:7e:34:45:3c:cb:14:70 +-----BEGIN CERTIFICATE----- +MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw +CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg +R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 +MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT +ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw +EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW ++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 +ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI +zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW +tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 +/q4AaOeMSQ+2b1tbFfLn +-----END CERTIFICATE----- + +# Issuer: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. +# Subject: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd. +# Label: "HiPKI Root CA - G1" +# Serial: 60966262342023497858655262305426234976 +# MD5 Fingerprint: 69:45:df:16:65:4b:e8:68:9a:8f:76:5f:ff:80:9e:d3 +# SHA1 Fingerprint: 6a:92:e4:a8:ee:1b:ec:96:45:37:e3:29:57:49:cd:96:e3:e5:d2:60 +# SHA256 Fingerprint: f0:15:ce:3c:c2:39:bf:ef:06:4b:e9:f1:d2:c4:17:e1:a0:26:4a:0a:94:be:1f:0c:8d:12:18:64:eb:69:49:cc +-----BEGIN CERTIFICATE----- +MIIFajCCA1KgAwIBAgIQLd2szmKXlKFD6LDNdmpeYDANBgkqhkiG9w0BAQsFADBP +MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 +ZC4xGzAZBgNVBAMMEkhpUEtJIFJvb3QgQ0EgLSBHMTAeFw0xOTAyMjIwOTQ2MDRa +Fw0zNzEyMzExNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3 +YSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQS0kgUm9vdCBDQSAtIEcx +MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA9B5/UnMyDHPkvRN0o9Qw +qNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh8Ge6zCFovkRTv4354twv +Vcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux55199QmQ5eiY29yTw1S+6 +lZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEuiAU+TCK72h8q3VJGZDnz +Qs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRtU6M9/Aes1MU3guvklQgZ +KILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfdhSi8MEyr48KxRURHH+CK +FgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXTT3OUM3ECoWqj1jOXTyFj +HluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK9p/7qxj3ccC2HTHsOyDr +y+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8b3ti6RZsR1pl8w4Rm0bZ +/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8PgcSojt/ewsTu8mL3WmKgM +a/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NVvxaXxA/VLGGEqnKG/uY6 +fsI/fe78LxQ+5oXdUG+3Se0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNV +HQ4EFgQU8ncX+l6o/vY9cdVouslGDDjYr7AwDgYDVR0PAQH/BAQDAgGGMA0GCSqG +SIb3DQEBCwUAA4ICAQBQUfB13HAE4/+qddRxosuej6ip0691x1TPOhwEmSKsxBHi +7zNKpiMdDg1H2DfHb680f0+BazVP6XKlMeJ45/dOlBhbQH3PayFUhuaVevvGyuqc +SE5XCV0vrPSltJczWNWseanMX/mF+lLFjfiRFOs6DRfQUsJ748JzjkZ4Bjgs6Fza +ZsT0pPBWGTMpWmWSBUdGSquEwx4noR8RkpkndZMPvDY7l1ePJlsMu5wP1G4wB9Tc +XzZoZjmDlicmisjEOf6aIW/Vcobpf2Lll07QJNBAsNB1CI69aO4I1258EHBGG3zg +iLKecoaZAeO/n0kZtCW+VmWuF2PlHt/o/0elv+EmBYTksMCv5wiZqAxeJoBF1Pho +L5aPruJKHJwWDBNvOIf2u8g0X5IDUXlwpt/L9ZlNec1OvFefQ05rLisY+GpzjLrF +Ne85akEez3GoorKGB1s6yeHvP2UEgEcyRHCVTjFnanRbEEV16rCf0OY1/k6fi8wr +kkVbbiVghUbN0aqwdmaTd5a+g744tiROJgvM7XpWGuDpWsZkrUx6AEhEL7lAuxM+ +vhV4nYWBSipX3tUZQ9rbyltHhoMLP7YNdnhzeSJesYAfz77RP1YQmCuVh6EfnWQU +YDksswBVLuT1sw5XxJFBAJw/6KXf6vb/yPCtbVKoF6ubYfwSUTXkJf2vqmqGOQ== +-----END CERTIFICATE----- + +# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 +# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4 +# Label: "GlobalSign ECC Root CA - R4" +# Serial: 159662223612894884239637590694 +# MD5 Fingerprint: 26:29:f8:6d:e1:88:bf:a2:65:7f:aa:c4:cd:0f:7f:fc +# SHA1 Fingerprint: 6b:a0:b0:98:e1:71:ef:5a:ad:fe:48:15:80:77:10:f4:bd:6f:0b:28 +# SHA256 Fingerprint: b0:85:d7:0b:96:4f:19:1a:73:e4:af:0d:54:ae:7a:0e:07:aa:fd:af:9b:71:dd:08:62:13:8a:b7:32:5a:24:a2 +-----BEGIN CERTIFICATE----- +MIIB3DCCAYOgAwIBAgINAgPlfvU/k/2lCSGypjAKBggqhkjOPQQDAjBQMSQwIgYD +VQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0gUjQxEzARBgNVBAoTCkdsb2Jh +bFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTIxMTEzMDAwMDAwWhcNMzgw +MTE5MDMxNDA3WjBQMSQwIgYDVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0g +UjQxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAAS4xnnTj2wlDp8uORkcA6SumuU5BwkWymOx +uYb4ilfBV85C+nOh92VC/x7BALJucw7/xyHlGKSq2XE/qNS5zowdo0IwQDAOBgNV +HQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVLB7rUW44kB/ ++wpu+74zyTyjhNUwCgYIKoZIzj0EAwIDRwAwRAIgIk90crlgr/HmnKAWBVBfw147 +bmF0774BxL4YSFlhgjICICadVGNA3jdgUM/I2O2dgq43mLyjj0xMqTQrbO/7lZsm +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R1 O=Google Trust Services LLC +# Subject: CN=GTS Root R1 O=Google Trust Services LLC +# Label: "GTS Root R1" +# Serial: 159662320309726417404178440727 +# MD5 Fingerprint: 05:fe:d0:bf:71:a8:a3:76:63:da:01:e0:d8:52:dc:40 +# SHA1 Fingerprint: e5:8c:1c:c4:91:3b:38:63:4b:e9:10:6e:e3:ad:8e:6b:9d:d9:81:4a +# SHA256 Fingerprint: d9:47:43:2a:bd:e7:b7:fa:90:fc:2e:6b:59:10:1b:12:80:e0:e1:c7:e4:e4:0f:a3:c6:88:7f:ff:57:a7:f4:cf +-----BEGIN CERTIFICATE----- +MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw +CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU +MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw +MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp +Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo +27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w +Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw +TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl +qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH +szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8 +Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk +MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92 +wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p +aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN +VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID +AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb +C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe +QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy +h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4 +7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J +ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef +MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/ +Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT +6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ +0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm +2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb +bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R2 O=Google Trust Services LLC +# Subject: CN=GTS Root R2 O=Google Trust Services LLC +# Label: "GTS Root R2" +# Serial: 159662449406622349769042896298 +# MD5 Fingerprint: 1e:39:c0:53:e6:1e:29:82:0b:ca:52:55:36:5d:57:dc +# SHA1 Fingerprint: 9a:44:49:76:32:db:de:fa:d0:bc:fb:5a:7b:17:bd:9e:56:09:24:94 +# SHA256 Fingerprint: 8d:25:cd:97:22:9d:bf:70:35:6b:da:4e:b3:cc:73:40:31:e2:4c:f0:0f:af:cf:d3:2d:c7:6e:b5:84:1c:7e:a8 +-----BEGIN CERTIFICATE----- +MIIFVzCCAz+gAwIBAgINAgPlrsWNBCUaqxElqjANBgkqhkiG9w0BAQwFADBHMQsw +CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU +MBIGA1UEAxMLR1RTIFJvb3QgUjIwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw +MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp +Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQDO3v2m++zsFDQ8BwZabFn3GTXd98GdVarTzTukk3LvCvpt +nfbwhYBboUhSnznFt+4orO/LdmgUud+tAWyZH8QiHZ/+cnfgLFuv5AS/T3KgGjSY +6Dlo7JUle3ah5mm5hRm9iYz+re026nO8/4Piy33B0s5Ks40FnotJk9/BW9BuXvAu +MC6C/Pq8tBcKSOWIm8Wba96wyrQD8Nr0kLhlZPdcTK3ofmZemde4wj7I0BOdre7k +RXuJVfeKH2JShBKzwkCX44ofR5GmdFrS+LFjKBC4swm4VndAoiaYecb+3yXuPuWg +f9RhD1FLPD+M2uFwdNjCaKH5wQzpoeJ/u1U8dgbuak7MkogwTZq9TwtImoS1mKPV ++3PBV2HdKFZ1E66HjucMUQkQdYhMvI35ezzUIkgfKtzra7tEscszcTJGr61K8Yzo +dDqs5xoic4DSMPclQsciOzsSrZYuxsN2B6ogtzVJV+mSSeh2FnIxZyuWfoqjx5RW +Ir9qS34BIbIjMt/kmkRtWVtd9QCgHJvGeJeNkP+byKq0rxFROV7Z+2et1VsRnTKa +G73VululycslaVNVJ1zgyjbLiGH7HrfQy+4W+9OmTN6SpdTi3/UGVN4unUu0kzCq +gc7dGtxRcw1PcOnlthYhGXmy5okLdWTK1au8CcEYof/UVKGFPP0UJAOyh9OktwID +AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQUu//KjiOfT5nK2+JopqUVJxce2Q4wDQYJKoZIhvcNAQEMBQADggIBAB/Kzt3H +vqGf2SdMC9wXmBFqiN495nFWcrKeGk6c1SuYJF2ba3uwM4IJvd8lRuqYnrYb/oM8 +0mJhwQTtzuDFycgTE1XnqGOtjHsB/ncw4c5omwX4Eu55MaBBRTUoCnGkJE+M3DyC +B19m3H0Q/gxhswWV7uGugQ+o+MePTagjAiZrHYNSVc61LwDKgEDg4XSsYPWHgJ2u +NmSRXbBoGOqKYcl3qJfEycel/FVL8/B/uWU9J2jQzGv6U53hkRrJXRqWbTKH7QMg +yALOWr7Z6v2yTcQvG99fevX4i8buMTolUVVnjWQye+mew4K6Ki3pHrTgSAai/Gev +HyICc/sgCq+dVEuhzf9gR7A/Xe8bVr2XIZYtCtFenTgCR2y59PYjJbigapordwj6 +xLEokCZYCDzifqrXPW+6MYgKBesntaFJ7qBFVHvmJ2WZICGoo7z7GJa7Um8M7YNR +TOlZ4iBgxcJlkoKM8xAfDoqXvneCbT+PHV28SSe9zE8P4c52hgQjxcCMElv924Sg +JPFI/2R80L5cFtHvma3AH/vLrrw4IgYmZNralw4/KBVEqE8AyvCazM90arQ+POuV +7LXTWtiBmelDGDfrs7vRWGJB82bSj6p4lVQgw1oudCvV0b4YacCs1aTPObpRhANl +6WLAYv7YTVWW4tAR+kg0Eeye7QUd5MjWHYbL +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R3 O=Google Trust Services LLC +# Subject: CN=GTS Root R3 O=Google Trust Services LLC +# Label: "GTS Root R3" +# Serial: 159662495401136852707857743206 +# MD5 Fingerprint: 3e:e7:9d:58:02:94:46:51:94:e5:e0:22:4a:8b:e7:73 +# SHA1 Fingerprint: ed:e5:71:80:2b:c8:92:b9:5b:83:3c:d2:32:68:3f:09:cd:a0:1e:46 +# SHA256 Fingerprint: 34:d8:a7:3e:e2:08:d9:bc:db:0d:95:65:20:93:4b:4e:40:e6:94:82:59:6e:8b:6f:73:c8:42:6b:01:0a:6f:48 +-----BEGIN CERTIFICATE----- +MIICCTCCAY6gAwIBAgINAgPluILrIPglJ209ZjAKBggqhkjOPQQDAzBHMQswCQYD +VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG +A1UEAxMLR1RTIFJvb3QgUjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw +WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz +IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUURout736G +jOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL2 +4CejQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBTB8Sa6oC2uhYHP0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEA9uEglRR7 +VKOQFhG/hMjqb2sXnh5GmCCbn9MN2azTL818+FsuVbu/3ZL3pAzcMeGiAjEA/Jdm +ZuVDFhOD3cffL74UOO0BzrEXGhF16b0DjyZ+hOXJYKaV11RZt+cRLInUue4X +-----END CERTIFICATE----- + +# Issuer: CN=GTS Root R4 O=Google Trust Services LLC +# Subject: CN=GTS Root R4 O=Google Trust Services LLC +# Label: "GTS Root R4" +# Serial: 159662532700760215368942768210 +# MD5 Fingerprint: 43:96:83:77:19:4d:76:b3:9d:65:52:e4:1d:22:a5:e8 +# SHA1 Fingerprint: 77:d3:03:67:b5:e0:0c:15:f6:0c:38:61:df:7c:e1:3b:92:46:4d:47 +# SHA256 Fingerprint: 34:9d:fa:40:58:c5:e2:63:12:3b:39:8a:e7:95:57:3c:4e:13:13:c8:3f:e6:8f:93:55:6c:d5:e8:03:1b:3c:7d +-----BEGIN CERTIFICATE----- +MIICCTCCAY6gAwIBAgINAgPlwGjvYxqccpBQUjAKBggqhkjOPQQDAzBHMQswCQYD +VQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG +A1UEAxMLR1RTIFJvb3QgUjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw +WjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz +IExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa6zzuhXyi +QHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvR +HYqjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW +BBSATNbrdP9JNqPV2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNpADBmAjEA6ED/g94D +9J+uHXqnLrmvT/aDHQ4thQEd0dlq7A/Cr8deVl5c1RxYIigL9zC2L7F8AjEA8GE8 +p/SgguMh1YQdc4acLa/KNJvxn7kjNuK8YAOdgLOaVsjh4rsUecrNIdSUtUlD +-----END CERTIFICATE----- + +# Issuer: CN=Telia Root CA v2 O=Telia Finland Oyj +# Subject: CN=Telia Root CA v2 O=Telia Finland Oyj +# Label: "Telia Root CA v2" +# Serial: 7288924052977061235122729490515358 +# MD5 Fingerprint: 0e:8f:ac:aa:82:df:85:b1:f4:dc:10:1c:fc:99:d9:48 +# SHA1 Fingerprint: b9:99:cd:d1:73:50:8a:c4:47:05:08:9c:8c:88:fb:be:a0:2b:40:cd +# SHA256 Fingerprint: 24:2b:69:74:2f:cb:1e:5b:2a:bf:98:89:8b:94:57:21:87:54:4e:5b:4d:99:11:78:65:73:62:1f:6a:74:b8:2c +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx +CzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE +AwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1 +NTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ +MBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP +ADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq +AMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9 +vVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9 +lRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD +n3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT +7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o +6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC +TEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6 +WT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R +DolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI +pEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj +YzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy +rOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw +AwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ +8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi +0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM +A8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS +SRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K +TTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF +6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er +3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt +Ty3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT +VmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW +ysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA +rBPuUBQemMc= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH +# Subject: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH +# Label: "D-TRUST BR Root CA 1 2020" +# Serial: 165870826978392376648679885835942448534 +# MD5 Fingerprint: b5:aa:4b:d5:ed:f7:e3:55:2e:8f:72:0a:f3:75:b8:ed +# SHA1 Fingerprint: 1f:5b:98:f0:e3:b5:f7:74:3c:ed:e6:b0:36:7d:32:cd:f4:09:41:67 +# SHA256 Fingerprint: e5:9a:aa:81:60:09:c2:2b:ff:5b:25:ba:d3:7d:f3:06:f0:49:79:7c:1f:81:d8:5a:b0:89:e6:57:bd:8f:00:44 +-----BEGIN CERTIFICATE----- +MIIC2zCCAmCgAwIBAgIQfMmPK4TX3+oPyWWa00tNljAKBggqhkjOPQQDAzBIMQsw +CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS +VVNUIEJSIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTA5NDUwMFoXDTM1MDIxMTA5 +NDQ1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG +A1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB +BAAiA2IABMbLxyjR+4T1mu9CFCDhQ2tuda38KwOE1HaTJddZO0Flax7mNCq7dPYS +zuht56vkPE4/RAiLzRZxy7+SmfSk1zxQVFKQhYN4lGdnoxwJGT11NIXe7WB9xwy0 +QVK5buXuQqOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHOREKv/ +VbNafAkl1bK6CKBrqx9tMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g +PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2JyX3Jvb3Rf +Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l +dC9DTj1ELVRSVVNUJTIwQlIlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 +c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO +PQQDAwNpADBmAjEAlJAtE/rhY/hhY+ithXhUkZy4kzg+GkHaQBZTQgjKL47xPoFW +wKrY7RjEsK70PvomAjEA8yjixtsrmfu3Ubgko6SUeho/5jbiA1czijDLgsfWFBHV +dWNbFJWcHwHP2NVypw87 +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH +# Subject: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH +# Label: "D-TRUST EV Root CA 1 2020" +# Serial: 126288379621884218666039612629459926992 +# MD5 Fingerprint: 8c:2d:9d:70:9f:48:99:11:06:11:fb:e9:cb:30:c0:6e +# SHA1 Fingerprint: 61:db:8c:21:59:69:03:90:d8:7c:9c:12:86:54:cf:9d:3d:f4:dd:07 +# SHA256 Fingerprint: 08:17:0d:1a:a3:64:53:90:1a:2f:95:92:45:e3:47:db:0c:8d:37:ab:aa:bc:56:b8:1a:a1:00:dc:95:89:70:db +-----BEGIN CERTIFICATE----- +MIIC2zCCAmCgAwIBAgIQXwJB13qHfEwDo6yWjfv/0DAKBggqhkjOPQQDAzBIMQsw +CQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS +VVNUIEVWIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTEwMDAwMFoXDTM1MDIxMTA5 +NTk1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG +A1UEAxMZRC1UUlVTVCBFViBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB +BAAiA2IABPEL3YZDIBnfl4XoIkqbz52Yv7QFJsnL46bSj8WeeHsxiamJrSc8ZRCC +/N/DnU7wMyPE0jL1HLDfMxddxfCxivnvubcUyilKwg+pf3VlSSowZ/Rk99Yad9rD +wpdhQntJraOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFH8QARY3 +OqQo5FD4pPfsazK2/umLMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g +PKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2V2X3Jvb3Rf +Y2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l +dC9DTj1ELVRSVVNUJTIwRVYlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1 +c3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO +PQQDAwNpADBmAjEAyjzGKnXCXnViOTYAYFqLwZOZzNnbQTs7h5kXO9XMT8oi96CA +y/m0sRtW9XLS/BnRAjEAkfcwkz8QRitxpNA7RJvAKQIFskF3UfN5Wp6OFKBOQtJb +gfM0agPnIjhQW+0ZT0MW +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. +# Subject: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc. +# Label: "DigiCert TLS ECC P384 Root G5" +# Serial: 13129116028163249804115411775095713523 +# MD5 Fingerprint: d3:71:04:6a:43:1c:db:a6:59:e1:a8:a3:aa:c5:71:ed +# SHA1 Fingerprint: 17:f3:de:5e:9f:0f:19:e9:8e:f6:1f:32:26:6e:20:c4:07:ae:30:ee +# SHA256 Fingerprint: 01:8e:13:f0:77:25:32:cf:80:9b:d1:b1:72:81:86:72:83:fc:48:c6:e1:3b:e9:c6:98:12:85:4a:49:0c:1b:05 +-----BEGIN CERTIFICATE----- +MIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp +Z2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2 +MDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ +bmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS +7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp +0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS +B4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49 +BAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ +LgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4 +DXZDjC5Ty3zfDBeWUA== +-----END CERTIFICATE----- + +# Issuer: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. +# Subject: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc. +# Label: "DigiCert TLS RSA4096 Root G5" +# Serial: 11930366277458970227240571539258396554 +# MD5 Fingerprint: ac:fe:f7:34:96:a9:f2:b3:b4:12:4b:e4:27:41:6f:e1 +# SHA1 Fingerprint: a7:88:49:dc:5d:7c:75:8c:8c:de:39:98:56:b3:aa:d0:b2:a5:71:35 +# SHA256 Fingerprint: 37:1a:00:dc:05:33:b3:72:1a:7e:eb:40:e8:41:9e:70:79:9d:2b:0a:0f:2c:1d:80:69:31:65:f7:ce:c4:ad:75 +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN +MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT +HERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN +NDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs +IEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+ +ajWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0 +2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp +wgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM +pG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD +nU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po +sMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx +Zre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd +Lvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX +KyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe +XoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL +tgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv +TiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN +AQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw +GXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H +PNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF +O4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ +REtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik +AdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv +/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+ +p6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw +MUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF +qUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK +ovfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+ +-----END CERTIFICATE----- + +# Issuer: CN=Certainly Root R1 O=Certainly +# Subject: CN=Certainly Root R1 O=Certainly +# Label: "Certainly Root R1" +# Serial: 188833316161142517227353805653483829216 +# MD5 Fingerprint: 07:70:d4:3e:82:87:a0:fa:33:36:13:f4:fa:33:e7:12 +# SHA1 Fingerprint: a0:50:ee:0f:28:71:f4:27:b2:12:6d:6f:50:96:25:ba:cc:86:42:af +# SHA256 Fingerprint: 77:b8:2c:d8:64:4c:43:05:f7:ac:c5:cb:15:6b:45:67:50:04:03:3d:51:c6:0c:62:02:a8:e0:c3:34:67:d3:a0 +-----BEGIN CERTIFICATE----- +MIIFRzCCAy+gAwIBAgIRAI4P+UuQcWhlM1T01EQ5t+AwDQYJKoZIhvcNAQELBQAw +PTELMAkGA1UEBhMCVVMxEjAQBgNVBAoTCUNlcnRhaW5seTEaMBgGA1UEAxMRQ2Vy +dGFpbmx5IFJvb3QgUjEwHhcNMjEwNDAxMDAwMDAwWhcNNDYwNDAxMDAwMDAwWjA9 +MQswCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0 +YWlubHkgUm9vdCBSMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANA2 +1B/q3avk0bbm+yLA3RMNansiExyXPGhjZjKcA7WNpIGD2ngwEc/csiu+kr+O5MQT +vqRoTNoCaBZ0vrLdBORrKt03H2As2/X3oXyVtwxwhi7xOu9S98zTm/mLvg7fMbed +aFySpvXl8wo0tf97ouSHocavFwDvA5HtqRxOcT3Si2yJ9HiG5mpJoM610rCrm/b0 +1C7jcvk2xusVtyWMOvwlDbMicyF0yEqWYZL1LwsYpfSt4u5BvQF5+paMjRcCMLT5 +r3gajLQ2EBAHBXDQ9DGQilHFhiZ5shGIXsXwClTNSaa/ApzSRKft43jvRl5tcdF5 +cBxGX1HpyTfcX35pe0HfNEXgO4T0oYoKNp43zGJS4YkNKPl6I7ENPT2a/Z2B7yyQ +wHtETrtJ4A5KVpK8y7XdeReJkd5hiXSSqOMyhb5OhaRLWcsrxXiOcVTQAjeZjOVJ +6uBUcqQRBi8LjMFbvrWhsFNunLhgkR9Za/kt9JQKl7XsxXYDVBtlUrpMklZRNaBA +2CnbrlJ2Oy0wQJuK0EJWtLeIAaSHO1OWzaMWj/Nmqhexx2DgwUMFDO6bW2BvBlyH +Wyf5QBGenDPBt+U1VwV/J84XIIwc/PH72jEpSe31C4SnT8H2TsIonPru4K8H+zMR +eiFPCyEQtkA6qyI6BJyLm4SGcprSp6XEtHWRqSsjAgMBAAGjQjBAMA4GA1UdDwEB +/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTgqj8ljZ9EXME66C6u +d0yEPmcM9DANBgkqhkiG9w0BAQsFAAOCAgEAuVevuBLaV4OPaAszHQNTVfSVcOQr +PbA56/qJYv331hgELyE03fFo8NWWWt7CgKPBjcZq91l3rhVkz1t5BXdm6ozTaw3d +8VkswTOlMIAVRQdFGjEitpIAq5lNOo93r6kiyi9jyhXWx8bwPWz8HA2YEGGeEaIi +1wrykXprOQ4vMMM2SZ/g6Q8CRFA3lFV96p/2O7qUpUzpvD5RtOjKkjZUbVwlKNrd +rRT90+7iIgXr0PK3aBLXWopBGsaSpVo7Y0VPv+E6dyIvXL9G+VoDhRNCX8reU9di +taY1BMJH/5n9hN9czulegChB8n3nHpDYT3Y+gjwN/KUD+nsa2UUeYNrEjvn8K8l7 +lcUq/6qJ34IxD3L/DCfXCh5WAFAeDJDBlrXYFIW7pw0WwfgHJBu6haEaBQmAupVj +yTrsJZ9/nbqkRxWbRHDxakvWOF5D8xh+UG7pWijmZeZ3Gzr9Hb4DJqPb1OG7fpYn +Kx3upPvaJVQTA945xsMfTZDsjxtK0hzthZU4UHlG1sGQUDGpXJpuHfUzVounmdLy +yCwzk5Iwx06MZTMQZBf9JBeW0Y3COmor6xOLRPIh80oat3df1+2IpHLlOR+Vnb5n +wXARPbv0+Em34yaXOp/SX3z7wJl8OSngex2/DaeP0ik0biQVy96QXr8axGbqwua6 +OV+KmalBWQewLK8= +-----END CERTIFICATE----- + +# Issuer: CN=Certainly Root E1 O=Certainly +# Subject: CN=Certainly Root E1 O=Certainly +# Label: "Certainly Root E1" +# Serial: 8168531406727139161245376702891150584 +# MD5 Fingerprint: 0a:9e:ca:cd:3e:52:50:c6:36:f3:4b:a3:ed:a7:53:e9 +# SHA1 Fingerprint: f9:e1:6d:dc:01:89:cf:d5:82:45:63:3e:c5:37:7d:c2:eb:93:6f:2b +# SHA256 Fingerprint: b4:58:5f:22:e4:ac:75:6a:4e:86:12:a1:36:1c:5d:9d:03:1a:93:fd:84:fe:bb:77:8f:a3:06:8b:0f:c4:2d:c2 +-----BEGIN CERTIFICATE----- +MIIB9zCCAX2gAwIBAgIQBiUzsUcDMydc+Y2aub/M+DAKBggqhkjOPQQDAzA9MQsw +CQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0YWlu +bHkgUm9vdCBFMTAeFw0yMTA0MDEwMDAwMDBaFw00NjA0MDEwMDAwMDBaMD0xCzAJ +BgNVBAYTAlVTMRIwEAYDVQQKEwlDZXJ0YWlubHkxGjAYBgNVBAMTEUNlcnRhaW5s +eSBSb290IEUxMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3m/4fxzf7flHh4axpMCK ++IKXgOqPyEpeKn2IaKcBYhSRJHpcnqMXfYqGITQYUBsQ3tA3SybHGWCA6TS9YBk2 +QNYphwk8kXr2vBMj3VlOBF7PyAIcGFPBMdjaIOlEjeR2o0IwQDAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU8ygYy2R17ikq6+2uI1g4 +hevIIgcwCgYIKoZIzj0EAwMDaAAwZQIxALGOWiDDshliTd6wT99u0nCK8Z9+aozm +ut6Dacpps6kFtZaSF4fC0urQe87YQVt8rgIwRt7qy12a7DLCZRawTDBcMPPaTnOG +BtjOiQRINzf43TNRnXCve1XYAS59BWQOhriR +-----END CERTIFICATE----- + +# Issuer: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. +# Subject: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD. +# Label: "Security Communication ECC RootCA1" +# Serial: 15446673492073852651 +# MD5 Fingerprint: 7e:43:b0:92:68:ec:05:43:4c:98:ab:5d:35:2e:7e:86 +# SHA1 Fingerprint: b8:0e:26:a9:bf:d2:b2:3b:c0:ef:46:c9:ba:c7:bb:f6:1d:0d:41:41 +# SHA256 Fingerprint: e7:4f:bd:a5:5b:d5:64:c4:73:a3:6b:44:1a:a7:99:c8:a6:8e:07:74:40:e8:28:8b:9f:a1:e5:0e:4b:ba:ca:11 +-----BEGIN CERTIFICATE----- +MIICODCCAb6gAwIBAgIJANZdm7N4gS7rMAoGCCqGSM49BAMDMGExCzAJBgNVBAYT +AkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMSswKQYD +VQQDEyJTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVDQyBSb290Q0ExMB4XDTE2MDYx +NjA1MTUyOFoXDTM4MDExODA1MTUyOFowYTELMAkGA1UEBhMCSlAxJTAjBgNVBAoT +HFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKzApBgNVBAMTIlNlY3VyaXR5 +IENvbW11bmljYXRpb24gRUNDIFJvb3RDQTEwdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AASkpW9gAwPDvTH00xecK4R1rOX9PVdu12O/5gSJko6BnOPpR27KkBLIE+Cnnfdl +dB9sELLo5OnvbYUymUSxXv3MdhDYW72ixvnWQuRXdtyQwjWpS4g8EkdtXP9JTxpK +ULGjQjBAMB0GA1UdDgQWBBSGHOf+LaVKiwj+KBH6vqNm+GBZLzAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjAVXUI9/Lbu +9zuxNuie9sRGKEkz0FhDKmMpzE2xtHqiuQ04pV1IKv3LsnNdo4gIxwwCMQDAqy0O +be0YottT6SXbVQjgUMzfRGEWgqtJsLKB7HOHeLRMsmIbEvoWTSVLY70eN9k= +-----END CERTIFICATE----- + +# Issuer: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY +# Subject: CN=BJCA Global Root CA1 O=BEIJING CERTIFICATE AUTHORITY +# Label: "BJCA Global Root CA1" +# Serial: 113562791157148395269083148143378328608 +# MD5 Fingerprint: 42:32:99:76:43:33:36:24:35:07:82:9b:28:f9:d0:90 +# SHA1 Fingerprint: d5:ec:8d:7b:4c:ba:79:f4:e7:e8:cb:9d:6b:ae:77:83:10:03:21:6a +# SHA256 Fingerprint: f3:89:6f:88:fe:7c:0a:88:27:66:a7:fa:6a:d2:74:9f:b5:7a:7f:3e:98:fb:76:9c:1f:a7:b0:9c:2c:44:d5:ae +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIQVW9l47TZkGobCdFsPsBsIDANBgkqhkiG9w0BAQsFADBU +MQswCQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRI +T1JJVFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0ExMB4XDTE5MTIxOTAz +MTYxN1oXDTQ0MTIxMjAzMTYxN1owVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJF +SUpJTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2Jh +bCBSb290IENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPFmCL3Z +xRVhy4QEQaVpN3cdwbB7+sN3SJATcmTRuHyQNZ0YeYjjlwE8R4HyDqKYDZ4/N+AZ +spDyRhySsTphzvq3Rp4Dhtczbu33RYx2N95ulpH3134rhxfVizXuhJFyV9xgw8O5 +58dnJCNPYwpj9mZ9S1WnP3hkSWkSl+BMDdMJoDIwOvqfwPKcxRIqLhy1BDPapDgR +at7GGPZHOiJBhyL8xIkoVNiMpTAK+BcWyqw3/XmnkRd4OJmtWO2y3syJfQOcs4ll +5+M7sSKGjwZteAf9kRJ/sGsciQ35uMt0WwfCyPQ10WRjeulumijWML3mG90Vr4Tq +nMfK9Q7q8l0ph49pczm+LiRvRSGsxdRpJQaDrXpIhRMsDQa4bHlW/KNnMoH1V6XK +V0Jp6VwkYe/iMBhORJhVb3rCk9gZtt58R4oRTklH2yiUAguUSiz5EtBP6DF+bHq/ +pj+bOT0CFqMYs2esWz8sgytnOYFcuX6U1WTdno9uruh8W7TXakdI136z1C2OVnZO +z2nxbkRs1CTqjSShGL+9V/6pmTW12xB3uD1IutbB5/EjPtffhZ0nPNRAvQoMvfXn +jSXWgXSHRtQpdaJCbPdzied9v3pKH9MiyRVVz99vfFXQpIsHETdfg6YmV6YBW37+ +WGgHqel62bno/1Afq8K0wM7o6v0PvY1NuLxxAgMBAAGjQjBAMB0GA1UdDgQWBBTF +7+3M2I0hxkjk49cULqcWk+WYATAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE +AwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAUoKsITQfI/Ki2Pm4rzc2IInRNwPWaZ+4 +YRC6ojGYWUfo0Q0lHhVBDOAqVdVXUsv45Mdpox1NcQJeXyFFYEhcCY5JEMEE3Kli +awLwQ8hOnThJdMkycFRtwUf8jrQ2ntScvd0g1lPJGKm1Vrl2i5VnZu69mP6u775u ++2D2/VnGKhs/I0qUJDAnyIm860Qkmss9vk/Ves6OF8tiwdneHg56/0OGNFK8YT88 +X7vZdrRTvJez/opMEi4r89fO4aL/3Xtw+zuhTaRjAv04l5U/BXCga99igUOLtFkN +SoxUnMW7gZ/NfaXvCyUeOiDbHPwfmGcCCtRzRBPbUYQaVQNW4AB+dAb/OMRyHdOo +P2gxXdMJxy6MW2Pg6Nwe0uxhHvLe5e/2mXZgLR6UcnHGCyoyx5JO1UbXHfmpGQrI ++pXObSOYqgs4rZpWDW+N8TEAiMEXnM0ZNjX+VVOg4DwzX5Ze4jLp3zO7Bkqp2IRz +znfSxqxx4VyjHQy7Ct9f4qNx2No3WqB4K/TUfet27fJhcKVlmtOJNBir+3I+17Q9 +eVzYH6Eze9mCUAyTF6ps3MKCuwJXNq+YJyo5UOGwifUll35HaBC07HPKs5fRJNz2 +YqAo07WjuGS3iGJCz51TzZm+ZGiPTx4SSPfSKcOYKMryMguTjClPPGAyzQWWYezy +r/6zcCwupvI= +-----END CERTIFICATE----- + +# Issuer: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY +# Subject: CN=BJCA Global Root CA2 O=BEIJING CERTIFICATE AUTHORITY +# Label: "BJCA Global Root CA2" +# Serial: 58605626836079930195615843123109055211 +# MD5 Fingerprint: 5e:0a:f6:47:5f:a6:14:e8:11:01:95:3f:4d:01:eb:3c +# SHA1 Fingerprint: f4:27:86:eb:6e:b8:6d:88:31:67:02:fb:ba:66:a4:53:00:aa:7a:a6 +# SHA256 Fingerprint: 57:4d:f6:93:1e:27:80:39:66:7b:72:0a:fd:c1:60:0f:c2:7e:b6:6d:d3:09:29:79:fb:73:85:64:87:21:28:82 +-----BEGIN CERTIFICATE----- +MIICJTCCAaugAwIBAgIQLBcIfWQqwP6FGFkGz7RK6zAKBggqhkjOPQQDAzBUMQsw +CQYDVQQGEwJDTjEmMCQGA1UECgwdQkVJSklORyBDRVJUSUZJQ0FURSBBVVRIT1JJ +VFkxHTAbBgNVBAMMFEJKQ0EgR2xvYmFsIFJvb3QgQ0EyMB4XDTE5MTIxOTAzMTgy +MVoXDTQ0MTIxMjAzMTgyMVowVDELMAkGA1UEBhMCQ04xJjAkBgNVBAoMHUJFSUpJ +TkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZMR0wGwYDVQQDDBRCSkNBIEdsb2JhbCBS +b290IENBMjB2MBAGByqGSM49AgEGBSuBBAAiA2IABJ3LgJGNU2e1uVCxA/jlSR9B +IgmwUVJY1is0j8USRhTFiy8shP8sbqjV8QnjAyEUxEM9fMEsxEtqSs3ph+B99iK+ ++kpRuDCK/eHeGBIK9ke35xe/J4rUQUyWPGCWwf0VHKNCMEAwHQYDVR0OBBYEFNJK +sVF/BvDRgh9Obl+rg/xI1LCRMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgEGMAoGCCqGSM49BAMDA2gAMGUCMBq8W9f+qdJUDkpd0m2xQNz0Q9XSSpkZElaA +94M04TVOSG0ED1cxMDAtsaqdAzjbBgIxAMvMh1PLet8gUXOQwKhbYdDFUDn9hf7B +43j4ptZLvZuHjw/l1lOWqzzIQNph91Oj9w== +-----END CERTIFICATE----- + +# Issuer: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited +# Subject: CN=Sectigo Public Server Authentication Root E46 O=Sectigo Limited +# Label: "Sectigo Public Server Authentication Root E46" +# Serial: 88989738453351742415770396670917916916 +# MD5 Fingerprint: 28:23:f8:b2:98:5c:37:16:3b:3e:46:13:4e:b0:b3:01 +# SHA1 Fingerprint: ec:8a:39:6c:40:f0:2e:bc:42:75:d4:9f:ab:1c:1a:5b:67:be:d2:9a +# SHA256 Fingerprint: c9:0f:26:f0:fb:1b:40:18:b2:22:27:51:9b:5c:a2:b5:3e:2c:a5:b3:be:5c:f1:8e:fe:1b:ef:47:38:0c:53:83 +-----BEGIN CERTIFICATE----- +MIICOjCCAcGgAwIBAgIQQvLM2htpN0RfFf51KBC49DAKBggqhkjOPQQDAzBfMQsw +CQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1T +ZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwHhcN +MjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEYMBYG +A1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1YmxpYyBT +ZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAR2+pmpbiDt+dd34wc7qNs9Xzjoq1WmVk/WSOrsfy2qw7LFeeyZYX8QeccC +WvkEN/U0NSt3zn8gj1KjAIns1aeibVvjS5KToID1AZTc8GgHHs3u/iVStSBDHBv+ +6xnOQ6OjQjBAMB0GA1UdDgQWBBTRItpMWfFLXyY4qp3W7usNw/upYTAOBgNVHQ8B +Af8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNnADBkAjAn7qRa +qCG76UeXlImldCBteU/IvZNeWBj7LRoAasm4PdCkT0RHlAFWovgzJQxC36oCMB3q +4S6ILuH5px0CMk7yn2xVdOOurvulGu7t0vzCAxHrRVxgED1cf5kDW21USAGKcw== +-----END CERTIFICATE----- + +# Issuer: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited +# Subject: CN=Sectigo Public Server Authentication Root R46 O=Sectigo Limited +# Label: "Sectigo Public Server Authentication Root R46" +# Serial: 156256931880233212765902055439220583700 +# MD5 Fingerprint: 32:10:09:52:00:d5:7e:6c:43:df:15:c0:b1:16:93:e5 +# SHA1 Fingerprint: ad:98:f9:f3:e4:7d:75:3b:65:d4:82:b3:a4:52:17:bb:6e:f5:e4:38 +# SHA256 Fingerprint: 7b:b6:47:a6:2a:ee:ac:88:bf:25:7a:a5:22:d0:1f:fe:a3:95:e0:ab:45:c7:3f:93:f6:56:54:ec:38:f2:5a:06 +-----BEGIN CERTIFICATE----- +MIIFijCCA3KgAwIBAgIQdY39i658BwD6qSWn4cetFDANBgkqhkiG9w0BAQwFADBf +MQswCQYDVQQGEwJHQjEYMBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQD +Ey1TZWN0aWdvIFB1YmxpYyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYw +HhcNMjEwMzIyMDAwMDAwWhcNNDYwMzIxMjM1OTU5WjBfMQswCQYDVQQGEwJHQjEY +MBYGA1UEChMPU2VjdGlnbyBMaW1pdGVkMTYwNAYDVQQDEy1TZWN0aWdvIFB1Ymxp +YyBTZXJ2ZXIgQXV0aGVudGljYXRpb24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB +AQUAA4ICDwAwggIKAoICAQCTvtU2UnXYASOgHEdCSe5jtrch/cSV1UgrJnwUUxDa +ef0rty2k1Cz66jLdScK5vQ9IPXtamFSvnl0xdE8H/FAh3aTPaE8bEmNtJZlMKpnz +SDBh+oF8HqcIStw+KxwfGExxqjWMrfhu6DtK2eWUAtaJhBOqbchPM8xQljeSM9xf +iOefVNlI8JhD1mb9nxc4Q8UBUQvX4yMPFF1bFOdLvt30yNoDN9HWOaEhUTCDsG3X +ME6WW5HwcCSrv0WBZEMNvSE6Lzzpng3LILVCJ8zab5vuZDCQOc2TZYEhMbUjUDM3 +IuM47fgxMMxF/mL50V0yeUKH32rMVhlATc6qu/m1dkmU8Sf4kaWD5QazYw6A3OAS +VYCmO2a0OYctyPDQ0RTp5A1NDvZdV3LFOxxHVp3i1fuBYYzMTYCQNFu31xR13NgE +SJ/AwSiItOkcyqex8Va3e0lMWeUgFaiEAin6OJRpmkkGj80feRQXEgyDet4fsZfu ++Zd4KKTIRJLpfSYFplhym3kT2BFfrsU4YjRosoYwjviQYZ4ybPUHNs2iTG7sijbt +8uaZFURww3y8nDnAtOFr94MlI1fZEoDlSfB1D++N6xybVCi0ITz8fAr/73trdf+L +HaAZBav6+CuBQug4urv7qv094PPK306Xlynt8xhW6aWWrL3DkJiy4Pmi1KZHQ3xt +zwIDAQABo0IwQDAdBgNVHQ4EFgQUVnNYZJX5khqwEioEYnmhQBWIIUkwDgYDVR0P +AQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAC9c +mTz8Bl6MlC5w6tIyMY208FHVvArzZJ8HXtXBc2hkeqK5Duj5XYUtqDdFqij0lgVQ +YKlJfp/imTYpE0RHap1VIDzYm/EDMrraQKFz6oOht0SmDpkBm+S8f74TlH7Kph52 +gDY9hAaLMyZlbcp+nv4fjFg4exqDsQ+8FxG75gbMY/qB8oFM2gsQa6H61SilzwZA +Fv97fRheORKkU55+MkIQpiGRqRxOF3yEvJ+M0ejf5lG5Nkc/kLnHvALcWxxPDkjB +JYOcCj+esQMzEhonrPcibCTRAUH4WAP+JWgiH5paPHxsnnVI84HxZmduTILA7rpX +DhjvLpr3Etiga+kFpaHpaPi8TD8SHkXoUsCjvxInebnMMTzD9joiFgOgyY9mpFui +TdaBJQbpdqQACj7LzTWb4OE4y2BThihCQRxEV+ioratF4yUQvNs+ZUH7G6aXD+u5 +dHn5HrwdVw1Hr8Mvn4dGp+smWg9WY7ViYG4A++MnESLn/pmPNPW56MORcr3Ywx65 +LvKRRFHQV80MNNVIIb/bE/FmJUNS0nAiNs2fxBx1IK1jcmMGDw4nztJqDby1ORrp +0XZ60Vzk50lJLVU3aPAaOpg+VBeHVOmmJ1CJeyAvP/+/oYtKR5j/K3tJPsMpRmAY +QqszKbrAKbkTidOIijlBO8n9pu0f9GBj39ItVQGL +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation +# Subject: CN=SSL.com TLS RSA Root CA 2022 O=SSL Corporation +# Label: "SSL.com TLS RSA Root CA 2022" +# Serial: 148535279242832292258835760425842727825 +# MD5 Fingerprint: d8:4e:c6:59:30:d8:fe:a0:d6:7a:5a:2c:2c:69:78:da +# SHA1 Fingerprint: ec:2c:83:40:72:af:26:95:10:ff:0e:f2:03:ee:31:70:f6:78:9d:ca +# SHA256 Fingerprint: 8f:af:7d:2e:2c:b4:70:9b:b8:e0:b3:36:66:bf:75:a5:dd:45:b5:de:48:0f:8e:a8:d4:bf:e6:be:bc:17:f2:ed +-----BEGIN CERTIFICATE----- +MIIFiTCCA3GgAwIBAgIQb77arXO9CEDii02+1PdbkTANBgkqhkiG9w0BAQsFADBO +MQswCQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQD +DBxTU0wuY29tIFRMUyBSU0EgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzQyMloX +DTQ2MDgxOTE2MzQyMVowTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jw +b3JhdGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgUlNBIFJvb3QgQ0EgMjAyMjCC +AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANCkCXJPQIgSYT41I57u9nTP +L3tYPc48DRAokC+X94xI2KDYJbFMsBFMF3NQ0CJKY7uB0ylu1bUJPiYYf7ISf5OY +t6/wNr/y7hienDtSxUcZXXTzZGbVXcdotL8bHAajvI9AI7YexoS9UcQbOcGV0ins +S657Lb85/bRi3pZ7QcacoOAGcvvwB5cJOYF0r/c0WRFXCsJbwST0MXMwgsadugL3 +PnxEX4MN8/HdIGkWCVDi1FW24IBydm5MR7d1VVm0U3TZlMZBrViKMWYPHqIbKUBO +L9975hYsLfy/7PO0+r4Y9ptJ1O4Fbtk085zx7AGL0SDGD6C1vBdOSHtRwvzpXGk3 +R2azaPgVKPC506QVzFpPulJwoxJF3ca6TvvC0PeoUidtbnm1jPx7jMEWTO6Af77w +dr5BUxIzrlo4QqvXDz5BjXYHMtWrifZOZ9mxQnUjbvPNQrL8VfVThxc7wDNY8VLS ++YCk8OjwO4s4zKTGkH8PnP2L0aPP2oOnaclQNtVcBdIKQXTbYxE3waWglksejBYS +d66UNHsef8JmAOSqg+qKkK3ONkRN0VHpvB/zagX9wHQfJRlAUW7qglFA35u5CCoG +AtUjHBPW6dvbxrB6y3snm/vg1UYk7RBLY0ulBY+6uB0rpvqR4pJSvezrZ5dtmi2f +gTIFZzL7SAg/2SW4BCUvAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j +BBgwFoAU+y437uOEeicuzRk1sTN8/9REQrkwHQYDVR0OBBYEFPsuN+7jhHonLs0Z +NbEzfP/UREK5MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAjYlt +hEUY8U+zoO9opMAdrDC8Z2awms22qyIZZtM7QbUQnRC6cm4pJCAcAZli05bg4vsM +QtfhWsSWTVTNj8pDU/0quOr4ZcoBwq1gaAafORpR2eCNJvkLTqVTJXojpBzOCBvf +R4iyrT7gJ4eLSYwfqUdYe5byiB0YrrPRpgqU+tvT5TgKa3kSM/tKWTcWQA673vWJ +DPFs0/dRa1419dvAJuoSc06pkZCmF8NsLzjUo3KUQyxi4U5cMj29TH0ZR6LDSeeW +P4+a0zvkEdiLA9z2tmBVGKaBUfPhqBVq6+AL8BQx1rmMRTqoENjwuSfr98t67wVy +lrXEj5ZzxOhWc5y8aVFjvO9nHEMaX3cZHxj4HCUp+UmZKbaSPaKDN7EgkaibMOlq +bLQjk2UEqxHzDh1TJElTHaE/nUiSEeJ9DU/1172iWD54nR4fK/4huxoTtrEoZP2w +AgDHbICivRZQIA9ygV/MlP+7mea6kMvq+cYMwq7FGc4zoWtcu358NFcXrfA/rs3q +r5nsLFR+jM4uElZI7xc7P0peYNLcdDa8pUNjyw9bowJWCZ4kLOGGgYz+qxcs+sji +Mho6/4UIyYOf8kpIEFR3N+2ivEC+5BB09+Rbu7nzifmPQdjH5FCQNYA+HLhNkNPU +98OwoX6EyneSMSy4kLGCenROmxMmtNVQZlR4rmA= +-----END CERTIFICATE----- + +# Issuer: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation +# Subject: CN=SSL.com TLS ECC Root CA 2022 O=SSL Corporation +# Label: "SSL.com TLS ECC Root CA 2022" +# Serial: 26605119622390491762507526719404364228 +# MD5 Fingerprint: 99:d7:5c:f1:51:36:cc:e9:ce:d9:19:2e:77:71:56:c5 +# SHA1 Fingerprint: 9f:5f:d9:1a:54:6d:f5:0c:71:f0:ee:7a:bd:17:49:98:84:73:e2:39 +# SHA256 Fingerprint: c3:2f:fd:9f:46:f9:36:d1:6c:36:73:99:09:59:43:4b:9a:d6:0a:af:bb:9e:7c:f3:36:54:f1:44:cc:1b:a1:43 +-----BEGIN CERTIFICATE----- +MIICOjCCAcCgAwIBAgIQFAP1q/s3ixdAW+JDsqXRxDAKBggqhkjOPQQDAzBOMQsw +CQYDVQQGEwJVUzEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMSUwIwYDVQQDDBxT +U0wuY29tIFRMUyBFQ0MgUm9vdCBDQSAyMDIyMB4XDTIyMDgyNTE2MzM0OFoXDTQ2 +MDgxOTE2MzM0N1owTjELMAkGA1UEBhMCVVMxGDAWBgNVBAoMD1NTTCBDb3Jwb3Jh +dGlvbjElMCMGA1UEAwwcU1NMLmNvbSBUTFMgRUNDIFJvb3QgQ0EgMjAyMjB2MBAG +ByqGSM49AgEGBSuBBAAiA2IABEUpNXP6wrgjzhR9qLFNoFs27iosU8NgCTWyJGYm +acCzldZdkkAZDsalE3D07xJRKF3nzL35PIXBz5SQySvOkkJYWWf9lCcQZIxPBLFN +SeR7T5v15wj4A4j3p8OSSxlUgaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSME +GDAWgBSJjy+j6CugFFR781a4Jl9nOAuc0DAdBgNVHQ4EFgQUiY8vo+groBRUe/NW +uCZfZzgLnNAwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2gAMGUCMFXjIlbp +15IkWE8elDIPDAI2wv2sdDJO4fscgIijzPvX6yv/N33w7deedWo1dlJF4AIxAMeN +b0Igj762TVntd00pxCAgRWSGOlDGxK0tk/UYfXLtqc/ErFc2KAhl3zx5Zn6g6g== +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos +# Subject: CN=Atos TrustedRoot Root CA ECC TLS 2021 O=Atos +# Label: "Atos TrustedRoot Root CA ECC TLS 2021" +# Serial: 81873346711060652204712539181482831616 +# MD5 Fingerprint: 16:9f:ad:f1:70:ad:79:d6:ed:29:b4:d1:c5:79:70:a8 +# SHA1 Fingerprint: 9e:bc:75:10:42:b3:02:f3:81:f4:f7:30:62:d4:8f:c3:a7:51:b2:dd +# SHA256 Fingerprint: b2:fa:e5:3e:14:cc:d7:ab:92:12:06:47:01:ae:27:9c:1d:89:88:fa:cb:77:5f:a8:a0:08:91:4e:66:39:88:a8 +-----BEGIN CERTIFICATE----- +MIICFTCCAZugAwIBAgIQPZg7pmY9kGP3fiZXOATvADAKBggqhkjOPQQDAzBMMS4w +LAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgRUNDIFRMUyAyMDIxMQ0w +CwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTI2MjNaFw00MTA0 +MTcwOTI2MjJaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBDQSBF +Q0MgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMHYwEAYHKoZI +zj0CAQYFK4EEACIDYgAEloZYKDcKZ9Cg3iQZGeHkBQcfl+3oZIK59sRxUM6KDP/X +tXa7oWyTbIOiaG6l2b4siJVBzV3dscqDY4PMwL502eCdpO5KTlbgmClBk1IQ1SQ4 +AjJn8ZQSb+/Xxd4u/RmAo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR2 +KCXWfeBmmnoJsmo7jjPXNtNPojAOBgNVHQ8BAf8EBAMCAYYwCgYIKoZIzj0EAwMD +aAAwZQIwW5kp85wxtolrbNa9d+F851F+uDrNozZffPc8dz7kUK2o59JZDCaOMDtu +CCrCp1rIAjEAmeMM56PDr9NJLkaCI2ZdyQAUEv049OGYa3cpetskz2VAv9LcjBHo +9H1/IISpQuQo +-----END CERTIFICATE----- + +# Issuer: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos +# Subject: CN=Atos TrustedRoot Root CA RSA TLS 2021 O=Atos +# Label: "Atos TrustedRoot Root CA RSA TLS 2021" +# Serial: 111436099570196163832749341232207667876 +# MD5 Fingerprint: d4:d3:46:b8:9a:c0:9c:76:5d:9e:3a:c3:b9:99:31:d2 +# SHA1 Fingerprint: 18:52:3b:0d:06:37:e4:d6:3a:df:23:e4:98:fb:5b:16:fb:86:74:48 +# SHA256 Fingerprint: 81:a9:08:8e:a5:9f:b3:64:c5:48:a6:f8:55:59:09:9b:6f:04:05:ef:bf:18:e5:32:4e:c9:f4:57:ba:00:11:2f +-----BEGIN CERTIFICATE----- +MIIFZDCCA0ygAwIBAgIQU9XP5hmTC/srBRLYwiqipDANBgkqhkiG9w0BAQwFADBM +MS4wLAYDVQQDDCVBdG9zIFRydXN0ZWRSb290IFJvb3QgQ0EgUlNBIFRMUyAyMDIx +MQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0yMTA0MjIwOTIxMTBaFw00 +MTA0MTcwOTIxMDlaMEwxLjAsBgNVBAMMJUF0b3MgVHJ1c3RlZFJvb3QgUm9vdCBD +QSBSU0EgVExTIDIwMjExDTALBgNVBAoMBEF0b3MxCzAJBgNVBAYTAkRFMIICIjAN +BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAtoAOxHm9BYx9sKOdTSJNy/BBl01Z +4NH+VoyX8te9j2y3I49f1cTYQcvyAh5x5en2XssIKl4w8i1mx4QbZFc4nXUtVsYv +Ye+W/CBGvevUez8/fEc4BKkbqlLfEzfTFRVOvV98r61jx3ncCHvVoOX3W3WsgFWZ +kmGbzSoXfduP9LVq6hdKZChmFSlsAvFr1bqjM9xaZ6cF4r9lthawEO3NUDPJcFDs +GY6wx/J0W2tExn2WuZgIWWbeKQGb9Cpt0xU6kGpn8bRrZtkh68rZYnxGEFzedUln +nkL5/nWpo63/dgpnQOPF943HhZpZnmKaau1Fh5hnstVKPNe0OwANwI8f4UDErmwh +3El+fsqyjW22v5MvoVw+j8rtgI5Y4dtXz4U2OLJxpAmMkokIiEjxQGMYsluMWuPD +0xeqqxmjLBvk1cbiZnrXghmmOxYsL3GHX0WelXOTwkKBIROW1527k2gV+p2kHYzy +geBYBr3JtuP2iV2J+axEoctr+hbxx1A9JNr3w+SH1VbxT5Aw+kUJWdo0zuATHAR8 +ANSbhqRAvNncTFd+rrcztl524WWLZt+NyteYr842mIycg5kDcPOvdO3GDjbnvezB +c6eUWsuSZIKmAMFwoW4sKeFYV+xafJlrJaSQOoD0IJ2azsct+bJLKZWD6TWNp0lI +pw9MGZHQ9b8Q4HECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU +dEmZ0f+0emhFdcN+tNzMzjkz2ggwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB +DAUAA4ICAQAjQ1MkYlxt/T7Cz1UAbMVWiLkO3TriJQ2VSpfKgInuKs1l+NsW4AmS +4BjHeJi78+xCUvuppILXTdiK/ORO/auQxDh1MoSf/7OwKwIzNsAQkG8dnK/haZPs +o0UvFJ/1TCplQ3IM98P4lYsU84UgYt1UU90s3BiVaU+DR3BAM1h3Egyi61IxHkzJ +qM7F78PRreBrAwA0JrRUITWXAdxfG/F851X6LWh3e9NpzNMOa7pNdkTWwhWaJuyw +xfW70Xp0wmzNxbVe9kzmWy2B27O3Opee7c9GslA9hGCZcbUztVdF5kJHdWoOsAgM +rr3e97sPWD2PAzHoPYJQyi9eDF20l74gNAf0xBLh7tew2VktafcxBPTy+av5EzH4 +AXcOPUIjJsyacmdRIXrMPIWo6iFqO9taPKU0nprALN+AnCng33eU0aKAQv9qTFsR +0PXNor6uzFFcw9VUewyu1rkGd4Di7wcaaMxZUa1+XGdrudviB0JbuAEFWDlN5LuY +o7Ey7Nmj1m+UI/87tyll5gfp77YZ6ufCOB0yiJA8EytuzO+rdwY0d4RPcuSBhPm5 +dDTedk+SKlOxJTnbPP/lPqYO5Wue/9vsL3SD3460s6neFE3/MaNFcyT6lSnMEpcE +oji2jbDwN/zIIX8/syQbPYtuzE2wFg2WHYMfRsCbvUOZ58SWLs5fyQ== +-----END CERTIFICATE----- + +# Issuer: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc. +# Subject: CN=TrustAsia Global Root CA G3 O=TrustAsia Technologies, Inc. +# Label: "TrustAsia Global Root CA G3" +# Serial: 576386314500428537169965010905813481816650257167 +# MD5 Fingerprint: 30:42:1b:b7:bb:81:75:35:e4:16:4f:53:d2:94:de:04 +# SHA1 Fingerprint: 63:cf:b6:c1:27:2b:56:e4:88:8e:1c:23:9a:b6:2e:81:47:24:c3:c7 +# SHA256 Fingerprint: e0:d3:22:6a:eb:11:63:c2:e4:8f:f9:be:3b:50:b4:c6:43:1b:e7:bb:1e:ac:c5:c3:6b:5d:5e:c5:09:03:9a:08 +-----BEGIN CERTIFICATE----- +MIIFpTCCA42gAwIBAgIUZPYOZXdhaqs7tOqFhLuxibhxkw8wDQYJKoZIhvcNAQEM +BQAwWjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dp +ZXMsIEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHMzAe +Fw0yMTA1MjAwMjEwMTlaFw00NjA1MTkwMjEwMTlaMFoxCzAJBgNVBAYTAkNOMSUw +IwYDVQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtU +cnVzdEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzMwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQDAMYJhkuSUGwoqZdC+BqmHO1ES6nBBruL7dOoKjbmzTNyPtxNS +T1QY4SxzlZHFZjtqz6xjbYdT8PfxObegQ2OwxANdV6nnRM7EoYNl9lA+sX4WuDqK +AtCWHwDNBSHvBm3dIZwZQ0WhxeiAysKtQGIXBsaqvPPW5vxQfmZCHzyLpnl5hkA1 +nyDvP+uLRx+PjsXUjrYsyUQE49RDdT/VP68czH5GX6zfZBCK70bwkPAPLfSIC7Ep +qq+FqklYqL9joDiR5rPmd2jE+SoZhLsO4fWvieylL1AgdB4SQXMeJNnKziyhWTXA +yB1GJ2Faj/lN03J5Zh6fFZAhLf3ti1ZwA0pJPn9pMRJpxx5cynoTi+jm9WAPzJMs +hH/x/Gr8m0ed262IPfN2dTPXS6TIi/n1Q1hPy8gDVI+lhXgEGvNz8teHHUGf59gX +zhqcD0r83ERoVGjiQTz+LISGNzzNPy+i2+f3VANfWdP3kXjHi3dqFuVJhZBFcnAv +kV34PmVACxmZySYgWmjBNb9Pp1Hx2BErW+Canig7CjoKH8GB5S7wprlppYiU5msT +f9FkPz2ccEblooV7WIQn3MSAPmeamseaMQ4w7OYXQJXZRe0Blqq/DPNL0WP3E1jA +uPP6Z92bfW1K/zJMtSU7/xxnD4UiWQWRkUF3gdCFTIcQcf+eQxuulXUtgQIDAQAB +o2MwYTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEDk5PIj7zjKsK5Xf/Ih +MBY027ySMB0GA1UdDgQWBBRA5OTyI+84yrCuV3/yITAWNNu8kjAOBgNVHQ8BAf8E +BAMCAQYwDQYJKoZIhvcNAQEMBQADggIBACY7UeFNOPMyGLS0XuFlXsSUT9SnYaP4 +wM8zAQLpw6o1D/GUE3d3NZ4tVlFEbuHGLige/9rsR82XRBf34EzC4Xx8MnpmyFq2 +XFNFV1pF1AWZLy4jVe5jaN/TG3inEpQGAHUNcoTpLrxaatXeL1nHo+zSh2bbt1S1 +JKv0Q3jbSwTEb93mPmY+KfJLaHEih6D4sTNjduMNhXJEIlU/HHzp/LgV6FL6qj6j +ITk1dImmasI5+njPtqzn59ZW/yOSLlALqbUHM/Q4X6RJpstlcHboCoWASzY9M/eV +VHUl2qzEc4Jl6VL1XP04lQJqaTDFHApXB64ipCz5xUG3uOyfT0gA+QEEVcys+TIx +xHWVBqB/0Y0n3bOppHKH/lmLmnp0Ft0WpWIp6zqW3IunaFnT63eROfjXy9mPX1on +AX1daBli2MjN9LdyR75bl87yraKZk62Uy5P2EgmVtqvXO9A/EcswFi55gORngS1d +7XB4tmBZrOFdRWOPyN9yaFvqHbgB8X7754qz41SgOAngPN5C8sLtLpvzHzW2Ntjj +gKGLzZlkD8Kqq7HK9W+eQ42EVJmzbsASZthwEPEGNTNDqJwuuhQxzhB/HIbjj9LV ++Hfsm6vxL2PZQl/gZ4FkkfGXL/xuJvYz+NO1+MRiqzFRJQJ6+N1rZdVtTTDIZbpo +FGWsJwt0ivKH +-----END CERTIFICATE----- + +# Issuer: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc. +# Subject: CN=TrustAsia Global Root CA G4 O=TrustAsia Technologies, Inc. +# Label: "TrustAsia Global Root CA G4" +# Serial: 451799571007117016466790293371524403291602933463 +# MD5 Fingerprint: 54:dd:b2:d7:5f:d8:3e:ed:7c:e0:0b:2e:cc:ed:eb:eb +# SHA1 Fingerprint: 57:73:a5:61:5d:80:b2:e6:ac:38:82:fc:68:07:31:ac:9f:b5:92:5a +# SHA256 Fingerprint: be:4b:56:cb:50:56:c0:13:6a:52:6d:f4:44:50:8d:aa:36:a0:b5:4f:42:e4:ac:38:f7:2a:f4:70:e4:79:65:4c +-----BEGIN CERTIFICATE----- +MIICVTCCAdygAwIBAgIUTyNkuI6XY57GU4HBdk7LKnQV1tcwCgYIKoZIzj0EAwMw +WjELMAkGA1UEBhMCQ04xJTAjBgNVBAoMHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs +IEluYy4xJDAiBgNVBAMMG1RydXN0QXNpYSBHbG9iYWwgUm9vdCBDQSBHNDAeFw0y +MTA1MjAwMjEwMjJaFw00NjA1MTkwMjEwMjJaMFoxCzAJBgNVBAYTAkNOMSUwIwYD +VQQKDBxUcnVzdEFzaWEgVGVjaG5vbG9naWVzLCBJbmMuMSQwIgYDVQQDDBtUcnVz +dEFzaWEgR2xvYmFsIFJvb3QgQ0EgRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATx +s8045CVD5d4ZCbuBeaIVXxVjAd7Cq92zphtnS4CDr5nLrBfbK5bKfFJV4hrhPVbw +LxYI+hW8m7tH5j/uqOFMjPXTNvk4XatwmkcN4oFBButJ+bAp3TPsUKV/eSm4IJij +YzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUpbtKl86zK3+kMd6Xg1mD +pm9xy94wHQYDVR0OBBYEFKW7SpfOsyt/pDHel4NZg6ZvccveMA4GA1UdDwEB/wQE +AwIBBjAKBggqhkjOPQQDAwNnADBkAjBe8usGzEkxn0AAbbd+NvBNEU/zy4k6LHiR +UKNbwMp1JvK/kF0LgoxgKJ/GcJpo5PECMFxYDlZ2z1jD1xCMuo6u47xkdUfFVZDj +/bpV6wfEU6s3qe4hsiFbYI89MvHVI5TWWA== +-----END CERTIFICATE----- + +# Issuer: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH +# Subject: CN=Telekom Security TLS ECC Root 2020 O=Deutsche Telekom Security GmbH +# Label: "Telekom Security TLS ECC Root 2020" +# Serial: 72082518505882327255703894282316633856 +# MD5 Fingerprint: c1:ab:fe:6a:10:2c:03:8d:bc:1c:22:32:c0:85:a7:fd +# SHA1 Fingerprint: c0:f8:96:c5:a9:3b:01:06:21:07:da:18:42:48:bc:e9:9d:88:d5:ec +# SHA256 Fingerprint: 57:8a:f4:de:d0:85:3f:4e:59:98:db:4a:ea:f9:cb:ea:8d:94:5f:60:b6:20:a3:8d:1a:3c:13:b2:bc:7b:a8:e1 +-----BEGIN CERTIFICATE----- +MIICQjCCAcmgAwIBAgIQNjqWjMlcsljN0AFdxeVXADAKBggqhkjOPQQDAzBjMQsw +CQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0eSBH +bWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBFQ0MgUm9vdCAyMDIw +MB4XDTIwMDgyNTA3NDgyMFoXDTQ1MDgyNTIzNTk1OVowYzELMAkGA1UEBhMCREUx +JzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkGA1UE +AwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgRUNDIFJvb3QgMjAyMDB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABM6//leov9Wq9xCazbzREaK9Z0LMkOsVGJDZos0MKiXrPk/O +tdKPD/M12kOLAoC+b1EkHQ9rK8qfwm9QMuU3ILYg/4gND21Ju9sGpIeQkpT0CdDP +f8iAC8GXs7s1J8nCG6NCMEAwHQYDVR0OBBYEFONyzG6VmUex5rNhTNHLq+O6zd6f +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA +MGQCMHVSi7ekEE+uShCLsoRbQuHmKjYC2qBuGT8lv9pZMo7k+5Dck2TOrbRBR2Di +z6fLHgIwN0GMZt9Ba9aDAEH9L1r3ULRn0SyocddDypwnJJGDSA3PzfdUga/sf+Rn +27iQ7t0l +-----END CERTIFICATE----- + +# Issuer: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH +# Subject: CN=Telekom Security TLS RSA Root 2023 O=Deutsche Telekom Security GmbH +# Label: "Telekom Security TLS RSA Root 2023" +# Serial: 44676229530606711399881795178081572759 +# MD5 Fingerprint: bf:5b:eb:54:40:cd:48:71:c4:20:8d:7d:de:0a:42:f2 +# SHA1 Fingerprint: 54:d3:ac:b3:bd:57:56:f6:85:9d:ce:e5:c3:21:e2:d4:ad:83:d0:93 +# SHA256 Fingerprint: ef:c6:5c:ad:bb:59:ad:b6:ef:e8:4d:a2:23:11:b3:56:24:b7:1b:3b:1e:a0:da:8b:66:55:17:4e:c8:97:86:46 +-----BEGIN CERTIFICATE----- +MIIFszCCA5ugAwIBAgIQIZxULej27HF3+k7ow3BXlzANBgkqhkiG9w0BAQwFADBj +MQswCQYDVQQGEwJERTEnMCUGA1UECgweRGV1dHNjaGUgVGVsZWtvbSBTZWN1cml0 +eSBHbWJIMSswKQYDVQQDDCJUZWxla29tIFNlY3VyaXR5IFRMUyBSU0EgUm9vdCAy +MDIzMB4XDTIzMDMyODEyMTY0NVoXDTQ4MDMyNzIzNTk1OVowYzELMAkGA1UEBhMC +REUxJzAlBgNVBAoMHkRldXRzY2hlIFRlbGVrb20gU2VjdXJpdHkgR21iSDErMCkG +A1UEAwwiVGVsZWtvbSBTZWN1cml0eSBUTFMgUlNBIFJvb3QgMjAyMzCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAO01oYGA88tKaVvC+1GDrib94W7zgRJ9 +cUD/h3VCKSHtgVIs3xLBGYSJwb3FKNXVS2xE1kzbB5ZKVXrKNoIENqil/Cf2SfHV +cp6R+SPWcHu79ZvB7JPPGeplfohwoHP89v+1VmLhc2o0mD6CuKyVU/QBoCcHcqMA +U6DksquDOFczJZSfvkgdmOGjup5czQRxUX11eKvzWarE4GC+j4NSuHUaQTXtvPM6 +Y+mpFEXX5lLRbtLevOP1Czvm4MS9Q2QTps70mDdsipWol8hHD/BeEIvnHRz+sTug +BTNoBUGCwQMrAcjnj02r6LX2zWtEtefdi+zqJbQAIldNsLGyMcEWzv/9FIS3R/qy +8XDe24tsNlikfLMR0cN3f1+2JeANxdKz+bi4d9s3cXFH42AYTyS2dTd4uaNir73J +co4vzLuu2+QVUhkHM/tqty1LkCiCc/4YizWN26cEar7qwU02OxY2kTLvtkCJkUPg +8qKrBC7m8kwOFjQgrIfBLX7JZkcXFBGk8/ehJImr2BrIoVyxo/eMbcgByU/J7MT8 +rFEz0ciD0cmfHdRHNCk+y7AO+oMLKFjlKdw/fKifybYKu6boRhYPluV75Gp6SG12 +mAWl3G0eQh5C2hrgUve1g8Aae3g1LDj1H/1Joy7SWWO/gLCMk3PLNaaZlSJhZQNg ++y+TS/qanIA7AgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtqeX +gj10hZv3PJ+TmpV5dVKMbUcwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS2 +p5eCPXSFm/c8n5OalXl1UoxtRzANBgkqhkiG9w0BAQwFAAOCAgEAqMxhpr51nhVQ +pGv7qHBFfLp+sVr8WyP6Cnf4mHGCDG3gXkaqk/QeoMPhk9tLrbKmXauw1GLLXrtm +9S3ul0A8Yute1hTWjOKWi0FpkzXmuZlrYrShF2Y0pmtjxrlO8iLpWA1WQdH6DErw +M807u20hOq6OcrXDSvvpfeWxm4bu4uB9tPcy/SKE8YXJN3nptT+/XOR0so8RYgDd +GGah2XsjX/GO1WfoVNpbOms2b/mBsTNHM3dA+VKq3dSDz4V4mZqTuXNnQkYRIer+ +CqkbGmVps4+uFrb2S1ayLfmlyOw7YqPta9BO1UAJpB+Y1zqlklkg5LB9zVtzaL1t +xKITDmcZuI1CfmwMmm6gJC3VRRvcxAIU/oVbZZfKTpBQCHpCNfnqwmbU+AGuHrS+ +w6jv/naaoqYfRvaE7fzbzsQCzndILIyy7MMAo+wsVRjBfhnu4S/yrYObnqsZ38aK +L4x35bcF7DvB7L6Gs4a8wPfc5+pbrrLMtTWGS9DiP7bY+A4A7l3j941Y/8+LN+lj +X273CXE2whJdV/LItM3z7gLfEdxquVeEHVlNjM7IDiPCtyaaEBRx/pOyiriA8A4Q +ntOoUAw3gi/q4Iqd4Sw5/7W0cwDk90imc6y/st53BIe0o82bNSQ3+pCTE4FCxpgm +dTdmQRCsu/WU48IxK63nI1bMNSWSs1A= +-----END CERTIFICATE----- + +# Issuer: CN=FIRMAPROFESIONAL CA ROOT-A WEB O=Firmaprofesional SA +# Subject: CN=FIRMAPROFESIONAL CA ROOT-A WEB O=Firmaprofesional SA +# Label: "FIRMAPROFESIONAL CA ROOT-A WEB" +# Serial: 65916896770016886708751106294915943533 +# MD5 Fingerprint: 82:b2:ad:45:00:82:b0:66:63:f8:5f:c3:67:4e:ce:a3 +# SHA1 Fingerprint: a8:31:11:74:a6:14:15:0d:ca:77:dd:0e:e4:0c:5d:58:fc:a0:72:a5 +# SHA256 Fingerprint: be:f2:56:da:f2:6e:9c:69:bd:ec:16:02:35:97:98:f3:ca:f7:18:21:a0:3e:01:82:57:c5:3c:65:61:7f:3d:4a +-----BEGIN CERTIFICATE----- +MIICejCCAgCgAwIBAgIQMZch7a+JQn81QYehZ1ZMbTAKBggqhkjOPQQDAzBuMQsw +CQYDVQQGEwJFUzEcMBoGA1UECgwTRmlybWFwcm9mZXNpb25hbCBTQTEYMBYGA1UE +YQwPVkFURVMtQTYyNjM0MDY4MScwJQYDVQQDDB5GSVJNQVBST0ZFU0lPTkFMIENB +IFJPT1QtQSBXRUIwHhcNMjIwNDA2MDkwMTM2WhcNNDcwMzMxMDkwMTM2WjBuMQsw +CQYDVQQGEwJFUzEcMBoGA1UECgwTRmlybWFwcm9mZXNpb25hbCBTQTEYMBYGA1UE +YQwPVkFURVMtQTYyNjM0MDY4MScwJQYDVQQDDB5GSVJNQVBST0ZFU0lPTkFMIENB +IFJPT1QtQSBXRUIwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARHU+osEaR3xyrq89Zf +e9MEkVz6iMYiuYMQYneEMy3pA4jU4DP37XcsSmDq5G+tbbT4TIqk5B/K6k84Si6C +cyvHZpsKjECcfIr28jlgst7L7Ljkb+qbXbdTkBgyVcUgt5SjYzBhMA8GA1UdEwEB +/wQFMAMBAf8wHwYDVR0jBBgwFoAUk+FDY1w8ndYn81LsF7Kpryz3dvgwHQYDVR0O +BBYEFJPhQ2NcPJ3WJ/NS7Beyqa8s93b4MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjO +PQQDAwNoADBlAjAdfKR7w4l1M+E7qUW/Runpod3JIha3RxEL2Jq68cgLcFBTApFw +hVmpHqTm6iMxoAACMQD94vizrxa5HnPEluPBMBnYfubDl94cT7iJLzPrSA8Z94dG +XSaQpYXFuXqUPoeovQA= +-----END CERTIFICATE----- + +# Issuer: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA +# Subject: CN=TWCA CYBER Root CA O=TAIWAN-CA OU=Root CA +# Label: "TWCA CYBER Root CA" +# Serial: 85076849864375384482682434040119489222 +# MD5 Fingerprint: 0b:33:a0:97:52:95:d4:a9:fd:bb:db:6e:a3:55:5b:51 +# SHA1 Fingerprint: f6:b1:1c:1a:83:38:e9:7b:db:b3:a8:c8:33:24:e0:2d:9c:7f:26:66 +# SHA256 Fingerprint: 3f:63:bb:28:14:be:17:4e:c8:b6:43:9c:f0:8d:6d:56:f0:b7:c4:05:88:3a:56:48:a3:34:42:4d:6b:3e:c5:58 +-----BEGIN CERTIFICATE----- +MIIFjTCCA3WgAwIBAgIQQAE0jMIAAAAAAAAAATzyxjANBgkqhkiG9w0BAQwFADBQ +MQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FOLUNBMRAwDgYDVQQLEwdSb290 +IENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3QgQ0EwHhcNMjIxMTIyMDY1NDI5 +WhcNNDcxMTIyMTU1OTU5WjBQMQswCQYDVQQGEwJUVzESMBAGA1UEChMJVEFJV0FO +LUNBMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJUV0NBIENZQkVSIFJvb3Qg +Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDG+Moe2Qkgfh1sTs6P +40czRJzHyWmqOlt47nDSkvgEs1JSHWdyKKHfi12VCv7qze33Kc7wb3+szT3vsxxF +avcokPFhV8UMxKNQXd7UtcsZyoC5dc4pztKFIuwCY8xEMCDa6pFbVuYdHNWdZsc/ +34bKS1PE2Y2yHer43CdTo0fhYcx9tbD47nORxc5zb87uEB8aBs/pJ2DFTxnk684i +JkXXYJndzk834H/nY62wuFm40AZoNWDTNq5xQwTxaWV4fPMf88oon1oglWa0zbfu +j3ikRRjpJi+NmykosaS3Om251Bw4ckVYsV7r8Cibt4LK/c/WMw+f+5eesRycnupf +Xtuq3VTpMCEobY5583WSjCb+3MX2w7DfRFlDo7YDKPYIMKoNM+HvnKkHIuNZW0CP +2oi3aQiotyMuRAlZN1vH4xfyIutuOVLF3lSnmMlLIJXcRolftBL5hSmO68gnFSDA +S9TMfAxsNAwmmyYxpjyn9tnQS6Jk/zuZQXLB4HCX8SS7K8R0IrGsayIyJNN4KsDA +oS/xUgXJP+92ZuJF2A09rZXIx4kmyA+upwMu+8Ff+iDhcK2wZSA3M2Cw1a/XDBzC +kHDXShi8fgGwsOsVHkQGzaRP6AzRwyAQ4VRlnrZR0Bp2a0JaWHY06rc3Ga4udfmW +5cFZ95RXKSWNOkyrTZpB0F8mAwIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBSdhWEUfMFib5do5E83QOGt4A1WNzAd +BgNVHQ4EFgQUnYVhFHzBYm+XaORPN0DhreANVjcwDQYJKoZIhvcNAQEMBQADggIB +AGSPesRiDrWIzLjHhg6hShbNcAu3p4ULs3a2D6f/CIsLJc+o1IN1KriWiLb73y0t +tGlTITVX1olNc79pj3CjYcya2x6a4CD4bLubIp1dhDGaLIrdaqHXKGnK/nZVekZn +68xDiBaiA9a5F/gZbG0jAn/xX9AKKSM70aoK7akXJlQKTcKlTfjF/biBzysseKNn +TKkHmvPfXvt89YnNdJdhEGoHK4Fa0o635yDRIG4kqIQnoVesqlVYL9zZyvpoBJ7t +RCT5dEA7IzOrg1oYJkK2bVS1FmAwbLGg+LhBoF1JSdJlBTrq/p1hvIbZv97Tujqx +f36SNI7JAG7cmL3c7IAFrQI932XtCwP39xaEBDG6k5TY8hL4iuO/Qq+n1M0RFxbI +Qh0UqEL20kCGoE8jypZFVmAGzbdVAaYBlGX+bgUJurSkquLvWL69J1bY73NxW0Qz +8ppy6rBePm6pUlvscG21h483XjyMnM7k8M4MZ0HMzvaAq07MTFb1wWFZk7Q+ptq4 +NxKfKjLji7gh7MMrZQzvIt6IKTtM1/r+t+FHvpw+PoP7UV31aPcuIYXcv/Fa4nzX +xeSDwWrruoBa3lwtcHb4yOWHh8qgnaHlIhInD0Q9HWzq1MKLL295q39QpsQZp6F6 +t5b5wR9iWqJDB0BeJsas7a5wFsWqynKKTbDPAYsDP27X +-----END CERTIFICATE----- + +# Issuer: CN=SecureSign Root CA12 O=Cybertrust Japan Co., Ltd. +# Subject: CN=SecureSign Root CA12 O=Cybertrust Japan Co., Ltd. +# Label: "SecureSign Root CA12" +# Serial: 587887345431707215246142177076162061960426065942 +# MD5 Fingerprint: c6:89:ca:64:42:9b:62:08:49:0b:1e:7f:e9:07:3d:e8 +# SHA1 Fingerprint: 7a:22:1e:3d:de:1b:06:ac:9e:c8:47:70:16:8e:3c:e5:f7:6b:06:f4 +# SHA256 Fingerprint: 3f:03:4b:b5:70:4d:44:b2:d0:85:45:a0:20:57:de:93:eb:f3:90:5f:ce:72:1a:cb:c7:30:c0:6d:da:ee:90:4e +-----BEGIN CERTIFICATE----- +MIIDcjCCAlqgAwIBAgIUZvnHwa/swlG07VOX5uaCwysckBYwDQYJKoZIhvcNAQEL +BQAwUTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28u +LCBMdGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExMjAeFw0yMDA0MDgw +NTM2NDZaFw00MDA0MDgwNTM2NDZaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpD +eWJlcnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBS +b290IENBMTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6OcE3emhF +KxS06+QT61d1I02PJC0W6K6OyX2kVzsqdiUzg2zqMoqUm048luT9Ub+ZyZN+v/mt +p7JIKwccJ/VMvHASd6SFVLX9kHrko+RRWAPNEHl57muTH2SOa2SroxPjcf59q5zd +J1M3s6oYwlkm7Fsf0uZlfO+TvdhYXAvA42VvPMfKWeP+bl+sg779XSVOKik71gur +FzJ4pOE+lEa+Ym6b3kaosRbnhW70CEBFEaCeVESE99g2zvVQR9wsMJvuwPWW0v4J +hscGWa5Pro4RmHvzC1KqYiaqId+OJTN5lxZJjfU+1UefNzFJM3IFTQy2VYzxV4+K +h9GtxRESOaCtAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgEGMB0GA1UdDgQWBBRXNPN0zwRL1SXm8UC2LEzZLemgrTANBgkqhkiG9w0BAQsF +AAOCAQEAPrvbFxbS8hQBICw4g0utvsqFepq2m2um4fylOqyttCg6r9cBg0krY6Ld +mmQOmFxv3Y67ilQiLUoT865AQ9tPkbeGGuwAtEGBpE/6aouIs3YIcipJQMPTw4WJ +mBClnW8Zt7vPemVV2zfrPIpyMpcemik+rY3moxtt9XUa5rBouVui7mlHJzWhhpmA +8zNL4WukJsPvdFlseqJkth5Ew1DgDzk9qTPxpfPSvWKErI4cqc1avTc7bgoitPQV +55FYxTpE05Uo2cBl6XLK0A+9H7MV2anjpEcJnuDLN/v9vZfVvhgaaaI5gdka9at/ +yOPiZwud9AzqVN/Ssq+xIvEg37xEHA== +-----END CERTIFICATE----- + +# Issuer: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd. +# Subject: CN=SecureSign Root CA14 O=Cybertrust Japan Co., Ltd. +# Label: "SecureSign Root CA14" +# Serial: 575790784512929437950770173562378038616896959179 +# MD5 Fingerprint: 71:0d:72:fa:92:19:65:5e:89:04:ac:16:33:f0:bc:d5 +# SHA1 Fingerprint: dd:50:c0:f7:79:b3:64:2e:74:a2:b8:9d:9f:d3:40:dd:bb:f0:f2:4f +# SHA256 Fingerprint: 4b:00:9c:10:34:49:4f:9a:b5:6b:ba:3b:a1:d6:27:31:fc:4d:20:d8:95:5a:dc:ec:10:a9:25:60:72:61:e3:38 +-----BEGIN CERTIFICATE----- +MIIFcjCCA1qgAwIBAgIUZNtaDCBO6Ncpd8hQJ6JaJ90t8sswDQYJKoZIhvcNAQEM +BQAwUTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28u +LCBMdGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNDAeFw0yMDA0MDgw +NzA2MTlaFw00NTA0MDgwNzA2MTlaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpD +eWJlcnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBS +b290IENBMTQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDF0nqh1oq/ +FjHQmNE6lPxauG4iwWL3pwon71D2LrGeaBLwbCRjOfHw3xDG3rdSINVSW0KZnvOg +vlIfX8xnbacuUKLBl422+JX1sLrcneC+y9/3OPJH9aaakpUqYllQC6KxNedlsmGy +6pJxaeQp8E+BgQQ8sqVb1MWoWWd7VRxJq3qdwudzTe/NCcLEVxLbAQ4jeQkHO6Lo +/IrPj8BGJJw4J+CDnRugv3gVEOuGTgpa/d/aLIJ+7sr2KeH6caH3iGicnPCNvg9J +kdjqOvn90Ghx2+m1K06Ckm9mH+Dw3EzsytHqunQG+bOEkJTRX45zGRBdAuVwpcAQ +0BB8b8VYSbSwbprafZX1zNoCr7gsfXmPvkPx+SgojQlD+Ajda8iLLCSxjVIHvXib +y8posqTdDEx5YMaZ0ZPxMBoH064iwurO8YQJzOAUbn8/ftKChazcqRZOhaBgy/ac +18izju3Gm5h1DVXoX+WViwKkrkMpKBGk5hIwAUt1ax5mnXkvpXYvHUC0bcl9eQjs +0Wq2XSqypWa9a4X0dFbD9ed1Uigspf9mR6XU/v6eVL9lfgHWMI+lNpyiUBzuOIAB +SMbHdPTGrMNASRZhdCyvjG817XsYAFs2PJxQDcqSMxDxJklt33UkN4Ii1+iW/RVL +ApY+B3KVfqs9TC7XyvDf4Fg/LS8EmjijAQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUBpOjCl4oaTeqYR3r6/wtbyPk +86AwDQYJKoZIhvcNAQEMBQADggIBAJaAcgkGfpzMkwQWu6A6jZJOtxEaCnFxEM0E +rX+lRVAQZk5KQaID2RFPeje5S+LGjzJmdSX7684/AykmjbgWHfYfM25I5uj4V7Ib +ed87hwriZLoAymzvftAj63iP/2SbNDefNWWipAA9EiOWWF3KY4fGoweITedpdopT +zfFP7ELyk+OZpDc8h7hi2/DsHzc/N19DzFGdtfCXwreFamgLRB7lUe6TzktuhsHS +DCRZNhqfLJGP4xjblJUK7ZGqDpncllPjYYPGFrojutzdfhrGe0K22VoF3Jpf1d+4 +2kd92jjbrDnVHmtsKheMYc2xbXIBw8MgAGJoFjHVdqqGuw6qnsb58Nn4DSEC5MUo +FlkRudlpcyqSeLiSV5sI8jrlL5WwWLdrIBRtFO8KvH7YVdiI2i/6GaX7i+B/OfVy +K4XELKzvGUWSTLNhB9xNH27SgRNcmvMSZ4PPmz+Ln52kuaiWA3rF7iDeM9ovnhp6 +dB7h7sxaOgTdsxoEqBRjrLdHEoOabPXm6RUVkRqEGQ6UROcSjiVbgGcZ3GOTEAtl +Lor6CZpO2oYofaphNdgOpygau1LgePhsumywbrmHXumZNTfxPWQrqaA0k89jL9WB +365jJ6UeTo3cKXhZ+PmhIIynJkBugnLNeLLIjzwec+fBH7/PzqUqm9tEZDKgu39c +JRNItX+S +-----END CERTIFICATE----- + +# Issuer: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd. +# Subject: CN=SecureSign Root CA15 O=Cybertrust Japan Co., Ltd. +# Label: "SecureSign Root CA15" +# Serial: 126083514594751269499665114766174399806381178503 +# MD5 Fingerprint: 13:30:fc:c4:62:a6:a9:de:b5:c1:68:af:b5:d2:31:47 +# SHA1 Fingerprint: cb:ba:83:c8:c1:5a:5d:f1:f9:73:6f:ca:d7:ef:28:13:06:4a:07:7d +# SHA256 Fingerprint: e7:78:f0:f0:95:fe:84:37:29:cd:1a:00:82:17:9e:53:14:a9:c2:91:44:28:05:e1:fb:1d:8f:b6:b8:88:6c:3a +-----BEGIN CERTIFICATE----- +MIICIzCCAamgAwIBAgIUFhXHw9hJp75pDIqI7fBw+d23PocwCgYIKoZIzj0EAwMw +UTELMAkGA1UEBhMCSlAxIzAhBgNVBAoTGkN5YmVydHJ1c3QgSmFwYW4gQ28uLCBM +dGQuMR0wGwYDVQQDExRTZWN1cmVTaWduIFJvb3QgQ0ExNTAeFw0yMDA0MDgwODMy +NTZaFw00NTA0MDgwODMyNTZaMFExCzAJBgNVBAYTAkpQMSMwIQYDVQQKExpDeWJl +cnRydXN0IEphcGFuIENvLiwgTHRkLjEdMBsGA1UEAxMUU2VjdXJlU2lnbiBSb290 +IENBMTUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQLUHSNZDKZmbPSYAi4Io5GdCx4 +wCtELW1fHcmuS1Iggz24FG1Th2CeX2yF2wYUleDHKP+dX+Sq8bOLbe1PL0vJSpSR +ZHX+AezB2Ot6lHhWGENfa4HL9rzatAy2KZMIaY+jQjBAMA8GA1UdEwEB/wQFMAMB +Af8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTrQciu/NWeUUj1vYv0hyCTQSvT +9DAKBggqhkjOPQQDAwNoADBlAjEA2S6Jfl5OpBEHvVnCB96rMjhTKkZEBhd6zlHp +4P9mLQlO4E/0BdGF9jVg3PVys0Z9AjBEmEYagoUeYWmJSwdLZrWeqrqgHkHZAXQ6 +bkU6iYAZezKYVWOr62Nuk22rGwlgMU4= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH +# Subject: CN=D-TRUST BR Root CA 2 2023 O=D-Trust GmbH +# Label: "D-TRUST BR Root CA 2 2023" +# Serial: 153168538924886464690566649552453098598 +# MD5 Fingerprint: e1:09:ed:d3:60:d4:56:1b:47:1f:b7:0c:5f:1b:5f:85 +# SHA1 Fingerprint: 2d:b0:70:ee:71:94:af:69:68:17:db:79:ce:58:9f:a0:6b:96:f7:87 +# SHA256 Fingerprint: 05:52:e6:f8:3f:df:65:e8:fa:96:70:e6:66:df:28:a4:e2:13:40:b5:10:cb:e5:25:66:f9:7c:4f:b9:4b:2b:d1 +-----BEGIN CERTIFICATE----- +MIIFqTCCA5GgAwIBAgIQczswBEhb2U14LnNLyaHcZjANBgkqhkiG9w0BAQ0FADBI +MQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE +LVRSVVNUIEJSIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA4NTYzMVoXDTM4MDUw +OTA4NTYzMFowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi +MCAGA1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN +AQEBBQADggIPADCCAgoCggIBAK7/CVmRgApKaOYkP7in5Mg6CjoWzckjYaCTcfKr +i3OPoGdlYNJUa2NRb0kz4HIHE304zQaSBylSa053bATTlfrdTIzZXcFhfUvnKLNE +gXtRr90zsWh81k5M/itoucpmacTsXld/9w3HnDY25QdgrMBM6ghs7wZ8T1soegj8 +k12b9py0i4a6Ibn08OhZWiihNIQaJZG2tY/vsvmA+vk9PBFy2OMvhnbFeSzBqZCT +Rphny4NqoFAjpzv2gTng7fC5v2Xx2Mt6++9zA84A9H3X4F07ZrjcjrqDy4d2A/wl +2ecjbwb9Z/Pg/4S8R7+1FhhGaRTMBffb00msa8yr5LULQyReS2tNZ9/WtT5PeB+U +cSTq3nD88ZP+npNa5JRal1QMNXtfbO4AHyTsA7oC9Xb0n9Sa7YUsOCIvx9gvdhFP +/Wxc6PWOJ4d/GUohR5AdeY0cW/jPSoXk7bNbjb7EZChdQcRurDhaTyN0dKkSw/bS +uREVMweR2Ds3OmMwBtHFIjYoYiMQ4EbMl6zWK11kJNXuHA7e+whadSr2Y23OC0K+ +0bpwHJwh5Q8xaRfX/Aq03u2AnMuStIv13lmiWAmlY0cL4UEyNEHZmrHZqLAbWt4N +DfTisl01gLmB1IRpkQLLddCNxbU9CZEJjxShFHR5PtbJFR2kWVki3PaKRT08EtY+ +XTIvAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUZ5Dw1t61 +GNVGKX5cq/ieCLxklRAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG +OGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfYnJfcm9vdF9jYV8y +XzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQA097N3U9swFrktpSHxQCF16+tI +FoE9c+CeJyrrd6kTpGoKWloUMz1oH4Guaf2Mn2VsNELZLdB/eBaxOqwjMa1ef67n +riv6uvw8l5VAk1/DLQOj7aRvU9f6QA4w9QAgLABMjDu0ox+2v5Eyq6+SmNMW5tTR +VFxDWy6u71cqqLRvpO8NVhTaIasgdp4D/Ca4nj8+AybmTNudX0KEPUUDAxxZiMrc +LmEkWqTqJwtzEr5SswrPMhfiHocaFpVIbVrg0M8JkiZmkdijYQ6qgYF/6FKC0ULn +4B0Y+qSFNueG4A3rvNTJ1jxD8V1Jbn6Bm2m1iWKPiFLY1/4nwSPFyysCu7Ff/vtD +hQNGvl3GyiEm/9cCnnRK3PgTFbGBVzbLZVzRHTF36SXDw7IyN9XxmAnkbWOACKsG +koHU6XCPpz+y7YaMgmo1yEJagtFSGkUPFaUA8JR7ZSdXOUPPfH/mvTWze/EZTN46 +ls/pdu4D58JDUjxqgejBWoC9EV2Ta/vH5mQ/u2kc6d0li690yVRAysuTEwrt+2aS +Ecr1wPrYg1UDfNPFIkZ1cGt5SAYqgpq/5usWDiJFAbzdNpQ0qTUmiteXue4Icr80 +knCDgKs4qllo3UCkGJCy89UDyibK79XH4I9TjvAA46jtn/mtd+ArY0+ew+43u3gJ +hJ65bvspmZDogNOfJA== +-----END CERTIFICATE----- + +# Issuer: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc. +# Subject: CN=TrustAsia TLS ECC Root CA O=TrustAsia Technologies, Inc. +# Label: "TrustAsia TLS ECC Root CA" +# Serial: 310892014698942880364840003424242768478804666567 +# MD5 Fingerprint: 09:48:04:77:d2:fc:65:93:71:66:b1:11:95:4f:06:8c +# SHA1 Fingerprint: b5:ec:39:f3:a1:66:37:ae:c3:05:94:57:e2:be:11:be:b7:a1:7f:36 +# SHA256 Fingerprint: c0:07:6b:9e:f0:53:1f:b1:a6:56:d6:7c:4e:be:97:cd:5d:ba:a4:1e:f4:45:98:ac:c2:48:98:78:c9:2d:87:11 +-----BEGIN CERTIFICATE----- +MIICMTCCAbegAwIBAgIUNnThTXxlE8msg1UloD5Sfi9QaMcwCgYIKoZIzj0EAwMw +WDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dpZXMs +IEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgRUNDIFJvb3QgQ0EwHhcNMjQw +NTE1MDU0MTU2WhcNNDQwNTE1MDU0MTU1WjBYMQswCQYDVQQGEwJDTjElMCMGA1UE +ChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1c3RB +c2lhIFRMUyBFQ0MgUm9vdCBDQTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLh/pVs/ +AT598IhtrimY4ZtcU5nb9wj/1WrgjstEpvDBjL1P1M7UiFPoXlfXTr4sP/MSpwDp +guMqWzJ8S5sUKZ74LYO1644xST0mYekdcouJtgq7nDM1D9rs3qlKH8kzsaNCMEAw +DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQULIVTu7FDzTLqnqOH/qKYqKaT6RAw +DgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gAMGUCMFRH18MtYYZI9HlaVQ01 +L18N9mdsd0AaRuf4aFtOJx24mH1/k78ITcTaRTChD15KeAIxAKORh/IRM4PDwYqR +OkwrULG9IpRdNYlzg8WbGf60oenUoWa2AaU2+dhoYSi3dOGiMQ== +-----END CERTIFICATE----- + +# Issuer: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc. +# Subject: CN=TrustAsia TLS RSA Root CA O=TrustAsia Technologies, Inc. +# Label: "TrustAsia TLS RSA Root CA" +# Serial: 160405846464868906657516898462547310235378010780 +# MD5 Fingerprint: 3b:9e:c3:86:0f:34:3c:6b:c5:46:c4:8e:1d:e7:19:12 +# SHA1 Fingerprint: a5:46:50:c5:62:ea:95:9a:1a:a7:04:6f:17:58:c7:29:53:3d:03:fa +# SHA256 Fingerprint: 06:c0:8d:7d:af:d8:76:97:1e:b1:12:4f:e6:7f:84:7e:c0:c7:a1:58:d3:ea:53:cb:e9:40:e2:ea:97:91:f4:c3 +-----BEGIN CERTIFICATE----- +MIIFgDCCA2igAwIBAgIUHBjYz+VTPyI1RlNUJDxsR9FcSpwwDQYJKoZIhvcNAQEM +BQAwWDELMAkGA1UEBhMCQ04xJTAjBgNVBAoTHFRydXN0QXNpYSBUZWNobm9sb2dp +ZXMsIEluYy4xIjAgBgNVBAMTGVRydXN0QXNpYSBUTFMgUlNBIFJvb3QgQ0EwHhcN +MjQwNTE1MDU0MTU3WhcNNDQwNTE1MDU0MTU2WjBYMQswCQYDVQQGEwJDTjElMCMG +A1UEChMcVHJ1c3RBc2lhIFRlY2hub2xvZ2llcywgSW5jLjEiMCAGA1UEAxMZVHJ1 +c3RBc2lhIFRMUyBSU0EgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC +AgoCggIBAMMWuBtqpERz5dZO9LnPWwvB0ZqB9WOwj0PBuwhaGnrhB3YmH49pVr7+ +NmDQDIPNlOrnxS1cLwUWAp4KqC/lYCZUlviYQB2srp10Zy9U+5RjmOMmSoPGlbYJ +Q1DNDX3eRA5gEk9bNb2/mThtfWza4mhzH/kxpRkQcwUqwzIZheo0qt1CHjCNP561 +HmHVb70AcnKtEj+qpklz8oYVlQwQX1Fkzv93uMltrOXVmPGZLmzjyUT5tUMnCE32 +ft5EebuyjBza00tsLtbDeLdM1aTk2tyKjg7/D8OmYCYozza/+lcK7Fs/6TAWe8Tb +xNRkoDD75f0dcZLdKY9BWN4ArTr9PXwaqLEX8E40eFgl1oUh63kd0Nyrz2I8sMeX +i9bQn9P+PN7F4/w6g3CEIR0JwqH8uyghZVNgepBtljhb//HXeltt08lwSUq6HTrQ +UNoyIBnkiz/r1RYmNzz7dZ6wB3C4FGB33PYPXFIKvF1tjVEK2sUYyJtt3LCDs3+j +TnhMmCWr8n4uIF6CFabW2I+s5c0yhsj55NqJ4js+k8UTav/H9xj8Z7XvGCxUq0DT +bE3txci3OE9kxJRMT6DNrqXGJyV1J23G2pyOsAWZ1SgRxSHUuPzHlqtKZFlhaxP8 +S8ySpg+kUb8OWJDZgoM5pl+z+m6Ss80zDoWo8SnTq1mt1tve1CuBAgMBAAGjQjBA +MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFLgHkXlcBvRG/XtZylomkadFK/hT +MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQwFAAOCAgEAIZtqBSBdGBanEqT3 +Rz/NyjuujsCCztxIJXgXbODgcMTWltnZ9r96nBO7U5WS/8+S4PPFJzVXqDuiGev4 +iqME3mmL5Dw8veWv0BIb5Ylrc5tvJQJLkIKvQMKtuppgJFqBTQUYo+IzeXoLH5Pt +7DlK9RME7I10nYEKqG/odv6LTytpEoYKNDbdgptvT+Bz3Ul/KD7JO6NXBNiT2Twp +2xIQaOHEibgGIOcberyxk2GaGUARtWqFVwHxtlotJnMnlvm5P1vQiJ3koP26TpUJ +g3933FEFlJ0gcXax7PqJtZwuhfG5WyRasQmr2soaB82G39tp27RIGAAtvKLEiUUj +pQ7hRGU+isFqMB3iYPg6qocJQrmBktwliJiJ8Xw18WLK7nn4GS/+X/jbh87qqA8M +pugLoDzga5SYnH+tBuYc6kIQX+ImFTw3OffXvO645e8D7r0i+yiGNFjEWn9hongP +XvPKnbwbPKfILfanIhHKA9jnZwqKDss1jjQ52MjqjZ9k4DewbNfFj8GQYSbbJIwe +SsCI3zWQzj8C9GRh3sfIB5XeMhg6j6JCQCTl1jNdfK7vsU1P1FeQNWrcrgSXSYk0 +ly4wBOeY99sLAZDBHwo/+ML+TvrbmnNzFrwFuHnYWa8G5z9nODmxfKuU4CkUpijy +323imttUQ/hHWKNddBWcwauwxzQ= +-----END CERTIFICATE----- + +# Issuer: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH +# Subject: CN=D-TRUST EV Root CA 2 2023 O=D-Trust GmbH +# Label: "D-TRUST EV Root CA 2 2023" +# Serial: 139766439402180512324132425437959641711 +# MD5 Fingerprint: 96:b4:78:09:f0:09:cb:77:eb:bb:1b:4d:6f:36:bc:b6 +# SHA1 Fingerprint: a5:5b:d8:47:6c:8f:19:f7:4c:f4:6d:6b:b6:c2:79:82:22:df:54:8b +# SHA256 Fingerprint: 8e:82:21:b2:e7:d4:00:78:36:a1:67:2f:0d:cc:29:9c:33:bc:07:d3:16:f1:32:fa:1a:20:6d:58:71:50:f1:ce +-----BEGIN CERTIFICATE----- +MIIFqTCCA5GgAwIBAgIQaSYJfoBLTKCnjHhiU19abzANBgkqhkiG9w0BAQ0FADBI +MQswCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlE +LVRSVVNUIEVWIFJvb3QgQ0EgMiAyMDIzMB4XDTIzMDUwOTA5MTAzM1oXDTM4MDUw +OTA5MTAzMlowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEi +MCAGA1UEAxMZRC1UUlVTVCBFViBSb290IENBIDIgMjAyMzCCAiIwDQYJKoZIhvcN +AQEBBQADggIPADCCAgoCggIBANiOo4mAC7JXUtypU0w3uX9jFxPvp1sjW2l1sJkK +F8GLxNuo4MwxusLyzV3pt/gdr2rElYfXR8mV2IIEUD2BCP/kPbOx1sWy/YgJ25yE +7CUXFId/MHibaljJtnMoPDT3mfd/06b4HEV8rSyMlD/YZxBTfiLNTiVR8CUkNRFe +EMbsh2aJgWi6zCudR3Mfvc2RpHJqnKIbGKBv7FD0fUDCqDDPvXPIEysQEx6Lmqg6 +lHPTGGkKSv/BAQP/eX+1SH977ugpbzZMlWGG2Pmic4ruri+W7mjNPU0oQvlFKzIb +RlUWaqZLKfm7lVa/Rh3sHZMdwGWyH6FDrlaeoLGPaxK3YG14C8qKXO0elg6DpkiV +jTujIcSuWMYAsoS0I6SWhjW42J7YrDRJmGOVxcttSEfi8i4YHtAxq9107PncjLgc +jmgjutDzUNzPZY9zOjLHfP7KgiJPvo5iR2blzYfi6NUPGJ/lBHJLRjwQ8kTCZFZx +TnXonMkmdMV9WdEKWw9t/p51HBjGGjp82A0EzM23RWV6sY+4roRIPrN6TagD4uJ+ +ARZZaBhDM7DS3LAaQzXupdqpRlyuhoFBAUp0JuyfBr/CBTdkdXgpaP3F9ev+R/nk +hbDhezGdpn9yo7nELC7MmVcOIQxFAZRl62UJxmMiCzNJkkg8/M3OsD6Onov4/knF +NXJHAgMBAAGjgY4wgYswDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUqvyREBuH +kV8Wub9PS5FeAByxMoAwDgYDVR0PAQH/BAQDAgEGMEkGA1UdHwRCMEAwPqA8oDqG +OGh0dHA6Ly9jcmwuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3RfZXZfcm9vdF9jYV8y +XzIwMjMuY3JsMA0GCSqGSIb3DQEBDQUAA4ICAQCTy6UfmRHsmg1fLBWTxj++EI14 +QvBukEdHjqOSMo1wj/Zbjb6JzkcBahsgIIlbyIIQbODnmaprxiqgYzWRaoUlrRc4 +pZt+UPJ26oUFKidBK7GB0aL2QHWpDsvxVUjY7NHss+jOFKE17MJeNRqrphYBBo7q +3C+jisosketSjl8MmxfPy3MHGcRqwnNU73xDUmPBEcrCRbH0O1P1aa4846XerOhU +t7KR/aypH/KH5BfGSah82ApB9PI+53c0BFLd6IHyTS9URZ0V4U/M5d40VxDJI3IX +cI1QcB9WbMy5/zpaT2N6w25lBx2Eof+pDGOJbbJAiDnXH3dotfyc1dZnaVuodNv8 +ifYbMvekJKZ2t0dT741Jj6m2g1qllpBFYfXeA08mD6iL8AOWsKwV0HFaanuU5nCT +2vFp4LJiTZ6P/4mdm13NRemUAiKN4DV/6PEEeXFsVIP4M7kFMhtYVRFP0OUnR3Hs +7dpn1mKmS00PaaLJvOwiS5THaJQXfuKOKD62xur1NGyfN4gHONuGcfrNlUhDbqNP +gofXNJhuS5N5YHVpD/Aa1VP6IQzCP+k/HxiMkl14p3ZnGbuy6n/pcAlWVqOwDAst +Nl7F6cTVg8uGF5csbBNvh1qvSaYd2804BC5f4ko1Di1L+KIkBI3Y4WNeApI02phh +XBxvWHZks/wCuPWdCg== +-----END CERTIFICATE----- + +# Issuer: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG +# Subject: CN=SwissSign RSA TLS Root CA 2022 - 1 O=SwissSign AG +# Label: "SwissSign RSA TLS Root CA 2022 - 1" +# Serial: 388078645722908516278762308316089881486363258315 +# MD5 Fingerprint: 16:2e:e4:19:76:81:85:ba:8e:91:58:f1:15:ef:72:39 +# SHA1 Fingerprint: 81:34:0a:be:4c:cd:ce:cc:e7:7d:cc:8a:d4:57:e2:45:a0:77:5d:ce +# SHA256 Fingerprint: 19:31:44:f4:31:e0:fd:db:74:07:17:d4:de:92:6a:57:11:33:88:4b:43:60:d3:0e:27:29:13:cb:e6:60:ce:41 +-----BEGIN CERTIFICATE----- +MIIFkzCCA3ugAwIBAgIUQ/oMX04bgBhE79G0TzUfRPSA7cswDQYJKoZIhvcNAQEL +BQAwUTELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzErMCkGA1UE +AxMiU3dpc3NTaWduIFJTQSBUTFMgUm9vdCBDQSAyMDIyIC0gMTAeFw0yMjA2MDgx +MTA4MjJaFw00NzA2MDgxMTA4MjJaMFExCzAJBgNVBAYTAkNIMRUwEwYDVQQKEwxT +d2lzc1NpZ24gQUcxKzApBgNVBAMTIlN3aXNzU2lnbiBSU0EgVExTIFJvb3QgQ0Eg +MjAyMiAtIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLKmjiC8NX +vDVjvHClO/OMPE5Xlm7DTjak9gLKHqquuN6orx122ro10JFwB9+zBvKK8i5VUXu7 +LCTLf5ImgKO0lPaCoaTo+nUdWfMHamFk4saMla+ju45vVs9xzF6BYQ1t8qsCLqSX +5XH8irCRIFucdFJtrhUnWXjyCcplDn/L9Ovn3KlMd/YrFgSVrpxxpT8q2kFC5zyE +EPThPYxr4iuRR1VPuFa+Rd4iUU1OKNlfGUEGjw5NBuBwQCMBauTLE5tzrE0USJIt +/m2n+IdreXXhvhCxqohAWVTXz8TQm0SzOGlkjIHRI36qOTw7D59Ke4LKa2/KIj4x +0LDQKhySio/YGZxH5D4MucLNvkEM+KRHBdvBFzA4OmnczcNpI/2aDwLOEGrOyvi5 +KaM2iYauC8BPY7kGWUleDsFpswrzd34unYyzJ5jSmY0lpx+Gs6ZUcDj8fV3oT4MM +0ZPlEuRU2j7yrTrePjxF8CgPBrnh25d7mUWe3f6VWQQvdT/TromZhqwUtKiE+shd +OxtYk8EXlFXIC+OCeYSf8wCENO7cMdWP8vpPlkwGqnj73mSiI80fPsWMvDdUDrta +clXvyFu1cvh43zcgTFeRc5JzrBh3Q4IgaezprClG5QtO+DdziZaKHG29777YtvTK +wP1H8K4LWCDFyB02rpeNUIMmJCn3nTsPBQIDAQABo2MwYTAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBRvjmKLk0Ow4UD2p8P98Q+4 +DxU4pTAdBgNVHQ4EFgQUb45ii5NDsOFA9qfD/fEPuA8VOKUwDQYJKoZIhvcNAQEL +BQADggIBAKwsKUF9+lz1GpUYvyypiqkkVHX1uECry6gkUSsYP2OprphWKwVDIqO3 +10aewCoSPY6WlkDfDDOLazeROpW7OSltwAJsipQLBwJNGD77+3v1dj2b9l4wBlgz +Hqp41eZUBDqyggmNzhYzWUUo8aWjlw5DI/0LIICQ/+Mmz7hkkeUFjxOgdg3XNwwQ +iJb0Pr6VvfHDffCjw3lHC1ySFWPtUnWK50Zpy1FVCypM9fJkT6lc/2cyjlUtMoIc +gC9qkfjLvH4YoiaoLqNTKIftV+Vlek4ASltOU8liNr3CjlvrzG4ngRhZi0Rjn9UM +ZfQpZX+RLOV/fuiJz48gy20HQhFRJjKKLjpHE7iNvUcNCfAWpO2Whi4Z2L6MOuhF +LhG6rlrnub+xzI/goP+4s9GFe3lmozm1O2bYQL7Pt2eLSMkZJVX8vY3PXtpOpvJp +zv1/THfQwUY1mFwjmwJFQ5Ra3bxHrSL+ul4vkSkphnsh3m5kt8sNjzdbowhq6/Td +Ao9QAwKxuDdollDruF/UKIqlIgyKhPBZLtU30WHlQnNYKoH3dtvi4k0NX/a3vgW0 +rk4N3hY9A4GzJl5LuEsAz/+MF7psYC0nhzck5npgL7XTgwSqT0N1osGDsieYK7EO +gLrAhV5Cud+xYJHT6xh+cHiudoO+cVrQkOPKwRYlZ0rwtnu64ZzZ +-----END CERTIFICATE----- + +# Issuer: CN=OISTE Server Root ECC G1 O=OISTE Foundation +# Subject: CN=OISTE Server Root ECC G1 O=OISTE Foundation +# Label: "OISTE Server Root ECC G1" +# Serial: 47819833811561661340092227008453318557 +# MD5 Fingerprint: 42:a7:d2:35:ae:02:92:db:19:76:08:de:2f:05:b4:d4 +# SHA1 Fingerprint: 3b:f6:8b:09:ae:2a:92:7b:ba:e3:8d:3f:11:95:d9:e6:44:0c:45:e2 +# SHA256 Fingerprint: ee:c9:97:c0:c3:0f:21:6f:7e:3b:8b:30:7d:2b:ae:42:41:2d:75:3f:c8:21:9d:af:d1:52:0b:25:72:85:0f:49 +-----BEGIN CERTIFICATE----- +MIICNTCCAbqgAwIBAgIQI/nD1jWvjyhLH/BU6n6XnTAKBggqhkjOPQQDAzBLMQsw +CQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UEAwwY +T0lTVEUgU2VydmVyIFJvb3QgRUNDIEcxMB4XDTIzMDUzMTE0NDIyOFoXDTQ4MDUy +NDE0NDIyN1owSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5kYXRp +b24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IEVDQyBHMTB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABBcv+hK8rBjzCvRE1nZCnrPoH7d5qVi2+GXROiFPqOujvqQy +cvO2Ackr/XeFblPdreqqLiWStukhEaivtUwL85Zgmjvn6hp4LrQ95SjeHIC6XG4N +2xml4z+cKrhAS93mT6NjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBQ3 +TYhlz/w9itWj8UnATgwQb0K0nDAdBgNVHQ4EFgQUN02IZc/8PYrVo/FJwE4MEG9C +tJwwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCpKjAd0MKfkFFR +QD6VVCHNFmb3U2wIFjnQEnx/Yxvf4zgAOdktUyBFCxxgZzFDJe0CMQCSia7pXGKD +YmH5LVerVrkR3SW+ak5KGoJr3M/TvEqzPNcum9v4KGm8ay3sMaE641c= +-----END CERTIFICATE----- + +# Issuer: CN=OISTE Server Root RSA G1 O=OISTE Foundation +# Subject: CN=OISTE Server Root RSA G1 O=OISTE Foundation +# Label: " OISTE Server Root RSA G1" +# Serial: 113845518112613905024960613408179309848 +# MD5 Fingerprint: 23:a7:9e:d4:70:b8:b9:14:57:41:8a:7e:44:59:e2:68 +# SHA1 Fingerprint: f7:00:34:25:94:88:68:31:e4:34:87:3f:70:fe:86:b3:86:9f:f0:6e +# SHA256 Fingerprint: 9a:e3:62:32:a5:18:9f:fd:db:35:3d:fd:26:52:0c:01:53:95:d2:27:77:da:c5:9d:b5:7b:98:c0:89:a6:51:e6 +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIQVaXZZ5Qoxu0M+ifdWwFNGDANBgkqhkiG9w0BAQwFADBL +MQswCQYDVQQGEwJDSDEZMBcGA1UECgwQT0lTVEUgRm91bmRhdGlvbjEhMB8GA1UE +AwwYT0lTVEUgU2VydmVyIFJvb3QgUlNBIEcxMB4XDTIzMDUzMTE0MzcxNloXDTQ4 +MDUyNDE0MzcxNVowSzELMAkGA1UEBhMCQ0gxGTAXBgNVBAoMEE9JU1RFIEZvdW5k +YXRpb24xITAfBgNVBAMMGE9JU1RFIFNlcnZlciBSb290IFJTQSBHMTCCAiIwDQYJ +KoZIhvcNAQEBBQADggIPADCCAgoCggIBAKqu9KuCz/vlNwvn1ZatkOhLKdxVYOPM +vLO8LZK55KN68YG0nnJyQ98/qwsmtO57Gmn7KNByXEptaZnwYx4M0rH/1ow00O7b +rEi56rAUjtgHqSSY3ekJvqgiG1k50SeH3BzN+Puz6+mTeO0Pzjd8JnduodgsIUzk +ik/HEzxux9UTl7Ko2yRpg1bTacuCErudG/L4NPKYKyqOBGf244ehHa1uzjZ0Dl4z +O8vbUZeUapU8zhhabkvG/AePLhq5SvdkNCncpo1Q4Y2LS+VIG24ugBA/5J8bZT8R +tOpXaZ+0AOuFJJkk9SGdl6r7NH8CaxWQrbueWhl/pIzY+m0o/DjH40ytas7ZTpOS +jswMZ78LS5bOZmdTaMsXEY5Z96ycG7mOaES3GK/m5Q9l3JUJsJMStR8+lKXHiHUh +sd4JJCpM4rzsTGdHwimIuQq6+cF0zowYJmXa92/GjHtoXAvuY8BeS/FOzJ8vD+Ho +mnqT8eDI278n5mUpezbgMxVz8p1rhAhoKzYHKyfMeNhqhw5HdPSqoBNdZH702xSu ++zrkL8Fl47l6QGzwBrd7KJvX4V84c5Ss2XCTLdyEr0YconosP4EmQufU2MVshGYR +i3drVByjtdgQ8K4p92cIiBdcuJd5z+orKu5YM+Vt6SmqZQENghPsJQtdLEByFSnT +kCz3GkPVavBpAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAU +8snBDw1jALvsRQ5KH7WxszbNDo0wHQYDVR0OBBYEFPLJwQ8NYwC77EUOSh+1sbM2 +zQ6NMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQwFAAOCAgEANGd5sjrG5T33 +I3K5Ce+SrScfoE4KsvXaFwyihdJ+klH9FWXXXGtkFu6KRcoMQzZENdl//nk6HOjG +5D1rd9QhEOP28yBOqb6J8xycqd+8MDoX0TJD0KqKchxRKEzdNsjkLWd9kYccnbz8 +qyiWXmFcuCIzGEgWUOrKL+mlSdx/PKQZvDatkuK59EvV6wit53j+F8Bdh3foZ3dP +AGav9LEDOr4SfEE15fSmG0eLy3n31r8Xbk5l8PjaV8GUgeV6Vg27Rn9vkf195hfk +gSe7BYhW3SCl95gtkRlpMV+bMPKZrXJAlszYd2abtNUOshD+FKrDgHGdPY3ofRRs +YWSGRqbXVMW215AWRqWFyp464+YTFrYVI8ypKVL9AMb2kI5Wj4kI3Zaq5tNqqYY1 +9tVFeEJKRvwDyF7YZvZFZSS0vod7VSCd9521Kvy5YhnLbDuv0204bKt7ph6N/Ome +/msVuduCmsuY33OhkKCgxeDoAaijFJzIwZqsFVAzje18KotzlUBDJvyBpCpfOZC3 +J8tRd/iWkx7P8nd9H0aTolkelUTFLXVksNb54Dxp6gS1HAviRkRNQzuXSXERvSS2 +wq1yVAb+axj5d9spLFKebXd7Yv0PTY6YMjAwcRLWJTXjn/hvnLXrahut6hDTlhZy +BiElxky8j3C7DOReIoMt0r7+hVu05L0= +-----END CERTIFICATE----- diff --git a/miniconda3/lib/python3.13/site-packages/certifi/core.py b/miniconda3/lib/python3.13/site-packages/certifi/core.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9661cc7c2f6917c2506a30b2710002f81ab23a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/certifi/core.py @@ -0,0 +1,83 @@ +""" +certifi.py +~~~~~~~~~~ + +This module returns the installation location of cacert.pem or its contents. +""" +import sys +import atexit + +def exit_cacert_ctx() -> None: + _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr] + + +if sys.version_info >= (3, 11): + + from importlib.resources import as_file, files + + _CACERT_CTX = None + _CACERT_PATH = None + + def where() -> str: + # This is slightly terrible, but we want to delay extracting the file + # in cases where we're inside of a zipimport situation until someone + # actually calls where(), but we don't want to re-extract the file + # on every call of where(), so we'll do it once then store it in a + # global variable. + global _CACERT_CTX + global _CACERT_PATH + if _CACERT_PATH is None: + # This is slightly janky, the importlib.resources API wants you to + # manage the cleanup of this file, so it doesn't actually return a + # path, it returns a context manager that will give you the path + # when you enter it and will do any cleanup when you leave it. In + # the common case of not needing a temporary file, it will just + # return the file system location and the __exit__() is a no-op. + # + # We also have to hold onto the actual context manager, because + # it will do the cleanup whenever it gets garbage collected, so + # we will also store that at the global level as well. + _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem")) + _CACERT_PATH = str(_CACERT_CTX.__enter__()) + atexit.register(exit_cacert_ctx) + + return _CACERT_PATH + + def contents() -> str: + return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii") + +else: + + from importlib.resources import path as get_path, read_text + + _CACERT_CTX = None + _CACERT_PATH = None + + def where() -> str: + # This is slightly terrible, but we want to delay extracting the + # file in cases where we're inside of a zipimport situation until + # someone actually calls where(), but we don't want to re-extract + # the file on every call of where(), so we'll do it once then store + # it in a global variable. + global _CACERT_CTX + global _CACERT_PATH + if _CACERT_PATH is None: + # This is slightly janky, the importlib.resources API wants you + # to manage the cleanup of this file, so it doesn't actually + # return a path, it returns a context manager that will give + # you the path when you enter it and will do any cleanup when + # you leave it. In the common case of not needing a temporary + # file, it will just return the file system location and the + # __exit__() is a no-op. + # + # We also have to hold onto the actual context manager, because + # it will do the cleanup whenever it gets garbage collected, so + # we will also store that at the global level as well. + _CACERT_CTX = get_path("certifi", "cacert.pem") + _CACERT_PATH = str(_CACERT_CTX.__enter__()) + atexit.register(exit_cacert_ctx) + + return _CACERT_PATH + + def contents() -> str: + return read_text("certifi", "cacert.pem", encoding="ascii") diff --git a/miniconda3/lib/python3.13/site-packages/certifi/py.typed b/miniconda3/lib/python3.13/site-packages/certifi/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..67508e56a537eec8d96a5ceac506648f73529fcc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/METADATA @@ -0,0 +1,68 @@ +Metadata-Version: 2.4 +Name: cffi +Version: 2.0.0 +Summary: Foreign Function Interface for Python calling C code. +Author: Armin Rigo, Maciej Fijalkowski +Maintainer: Matt Davis, Matt Clay, Matti Picus +License-Expression: MIT +Project-URL: Documentation, https://cffi.readthedocs.io/ +Project-URL: Changelog, https://cffi.readthedocs.io/en/latest/whatsnew.html +Project-URL: Downloads, https://github.com/python-cffi/cffi/releases +Project-URL: Contact, https://groups.google.com/forum/#!forum/python-cffi +Project-URL: Source Code, https://github.com/python-cffi/cffi +Project-URL: Issue Tracker, https://github.com/python-cffi/cffi/issues +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta +Classifier: Programming Language :: Python :: Implementation :: CPython +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS +Requires-Dist: pycparser; implementation_name != "PyPy" +Dynamic: license-file + +[![GitHub Actions Status](https://github.com/python-cffi/cffi/actions/workflows/ci.yaml/badge.svg?branch=main)](https://github.com/python-cffi/cffi/actions/workflows/ci.yaml?query=branch%3Amain++) +[![PyPI version](https://img.shields.io/pypi/v/cffi.svg)](https://pypi.org/project/cffi) +[![Read the Docs](https://img.shields.io/badge/docs-latest-blue.svg)][Documentation] + + +CFFI +==== + +Foreign Function Interface for Python calling C code. + +Please see the [Documentation] or uncompiled in the `doc/` subdirectory. + +Download +-------- + +[Download page](https://github.com/python-cffi/cffi/releases) + +Source Code +----------- + +Source code is publicly available on +[GitHub](https://github.com/python-cffi/cffi). + +Contact +------- + +[Mailing list](https://groups.google.com/forum/#!forum/python-cffi) + +Testing/development tips +------------------------ + +After `git clone` or `wget && tar`, we will get a directory called `cffi` or `cffi-x.x.x`. we call it `repo-directory`. To run tests under CPython, run the following in the `repo-directory`: + + pip install pytest + pip install -e . # editable install of CFFI for local development + pytest src/c/ testing/ + +[Documentation]: http://cffi.readthedocs.org/ diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..6e64198a6254cbbbfd08485baacf4ffc4d0ccdb0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/RECORD @@ -0,0 +1,51 @@ +_cffi_backend.cpython-313-x86_64-linux-gnu.so,sha256=WQ1OsCJH42d4wdjMp6SAQoYMIWrgJa2l2y0pjHJ5Md0,224152 +cffi-2.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +cffi-2.0.0.dist-info/METADATA,sha256=uYzn40F68Im8EtXHNBLZs7FoPM-OxzyYbDWsjJvhujk,2559 +cffi-2.0.0.dist-info/RECORD,, +cffi-2.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +cffi-2.0.0.dist-info/WHEEL,sha256=edS7gZHRaM8x-3M3xoAkSxyeLfZjWAhIur1iLsXkBLo,104 +cffi-2.0.0.dist-info/direct_url.json,sha256=BMp_QCyWkyX2f-NQQsZAT92_pc-ZoA1eYBpQ-BwTw5I,94 +cffi-2.0.0.dist-info/entry_points.txt,sha256=y6jTxnyeuLnL-XJcDv8uML3n6wyYiGRg8MTp_QGJ9Ho,75 +cffi-2.0.0.dist-info/licenses/AUTHORS,sha256=KmemC7-zN1nWfWRf8TG45ta8TK_CMtdR_Kw-2k0xTMg,208 +cffi-2.0.0.dist-info/licenses/LICENSE,sha256=W6JN3FcGf5JJrdZEw6_EGl1tw34jQz73Wdld83Cwr2M,1123 +cffi-2.0.0.dist-info/top_level.txt,sha256=rE7WR3rZfNKxWI9-jn6hsHCAl7MDkB-FmuQbxWjFehQ,19 +cffi/__init__.py,sha256=-ksBQ7MfDzVvbBlV_ftYBWAmEqfA86ljIzMxzaZeAlI,511 +cffi/__pycache__/__init__.cpython-313.pyc,, +cffi/__pycache__/_imp_emulation.cpython-313.pyc,, +cffi/__pycache__/_shimmed_dist_utils.cpython-313.pyc,, +cffi/__pycache__/api.cpython-313.pyc,, +cffi/__pycache__/backend_ctypes.cpython-313.pyc,, +cffi/__pycache__/cffi_opcode.cpython-313.pyc,, +cffi/__pycache__/commontypes.cpython-313.pyc,, +cffi/__pycache__/cparser.cpython-313.pyc,, +cffi/__pycache__/error.cpython-313.pyc,, +cffi/__pycache__/ffiplatform.cpython-313.pyc,, +cffi/__pycache__/lock.cpython-313.pyc,, +cffi/__pycache__/model.cpython-313.pyc,, +cffi/__pycache__/pkgconfig.cpython-313.pyc,, +cffi/__pycache__/recompiler.cpython-313.pyc,, +cffi/__pycache__/setuptools_ext.cpython-313.pyc,, +cffi/__pycache__/vengine_cpy.cpython-313.pyc,, +cffi/__pycache__/vengine_gen.cpython-313.pyc,, +cffi/__pycache__/verifier.cpython-313.pyc,, +cffi/_cffi_errors.h,sha256=zQXt7uR_m8gUW-fI2hJg0KoSkJFwXv8RGUkEDZ177dQ,3908 +cffi/_cffi_include.h,sha256=Exhmgm9qzHWzWivjfTe0D7Xp4rPUkVxdNuwGhMTMzbw,15055 +cffi/_embedding.h,sha256=Ai33FHblE7XSpHOCp8kPcWwN5_9BV14OvN0JVa6ITpw,18786 +cffi/_imp_emulation.py,sha256=RxREG8zAbI2RPGBww90u_5fi8sWdahpdipOoPzkp7C0,2960 +cffi/_shimmed_dist_utils.py,sha256=Bjj2wm8yZbvFvWEx5AEfmqaqZyZFhYfoyLLQHkXZuao,2230 +cffi/api.py,sha256=alBv6hZQkjpmZplBphdaRn2lPO9-CORs_M7ixabvZWI,42169 +cffi/backend_ctypes.py,sha256=h5ZIzLc6BFVXnGyc9xPqZWUS7qGy7yFSDqXe68Sa8z4,42454 +cffi/cffi_opcode.py,sha256=JDV5l0R0_OadBX_uE7xPPTYtMdmpp8I9UYd6av7aiDU,5731 +cffi/commontypes.py,sha256=7N6zPtCFlvxXMWhHV08psUjdYIK2XgsN3yo5dgua_v4,2805 +cffi/cparser.py,sha256=QUTfmlL-aO-MYR8bFGlvAUHc36OQr7XYLe0WLkGFjRo,44790 +cffi/error.py,sha256=v6xTiS4U0kvDcy4h_BDRo5v39ZQuj-IMRYLv5ETddZs,877 +cffi/ffiplatform.py,sha256=avxFjdikYGJoEtmJO7ewVmwG_VEVl6EZ_WaNhZYCqv4,3584 +cffi/lock.py,sha256=l9TTdwMIMpi6jDkJGnQgE9cvTIR7CAntIJr8EGHt3pY,747 +cffi/model.py,sha256=W30UFQZE73jL5Mx5N81YT77us2W2iJjTm0XYfnwz1cg,21797 +cffi/parse_c_type.h,sha256=OdwQfwM9ktq6vlCB43exFQmxDBtj2MBNdK8LYl15tjw,5976 +cffi/pkgconfig.py,sha256=LP1w7vmWvmKwyqLaU1Z243FOWGNQMrgMUZrvgFuOlco,4374 +cffi/recompiler.py,sha256=78J6lMEEOygXNmjN9-fOFFO3j7eW-iFxSrxfvQb54bY,65509 +cffi/setuptools_ext.py,sha256=0rCwBJ1W7FHWtiMKfNXsSST88V8UXrui5oeXFlDNLG8,9411 +cffi/vengine_cpy.py,sha256=oyQKD23kpE0aChUKA8Jg0e723foPiYzLYEdb-J0MiNs,43881 +cffi/vengine_gen.py,sha256=DUlEIrDiVin1Pnhn1sfoamnS5NLqfJcOdhRoeSNeJRg,26939 +cffi/verifier.py,sha256=oX8jpaohg2Qm3aHcznidAdvrVm5N4sQYG0a3Eo5mIl4,11182 diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..69b458e365fc9b069c1677d11d9130ee3a8f7392 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp313-cp313-linux_x86_64 + diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..2227248fc305edce484b98e8fc753bf95b775a53 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176183214835616/conda-bld/cffi_1761832774688/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..4b0274f2333a8cfadbe2d13922c47d0138e48141 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[distutils.setup_keywords] +cffi_modules = cffi.setuptools_ext:cffi_modules diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/licenses/AUTHORS b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..370a25d317c9063a3b87d59d0168570f4ee27cf2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/licenses/AUTHORS @@ -0,0 +1,8 @@ +This package has been mostly done by Armin Rigo with help from +Maciej Fijałkowski. The idea is heavily based (although not directly +copied) from LuaJIT ffi by Mike Pall. + + +Other contributors: + + Google Inc. diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0a1dbfb017c2e0afcaac48ba6750d32539335e41 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,23 @@ + +Except when otherwise stated (look for LICENSE files in directories or +information at the beginning of each file) all software and +documentation is licensed as follows: + + MIT No Attribution + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the + Software is furnished to do so. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + diff --git a/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/top_level.txt b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f64577957eb0d893196994ae517759f3fa8e48dd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi-2.0.0.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_cffi_backend +cffi diff --git a/miniconda3/lib/python3.13/site-packages/cffi/__init__.py b/miniconda3/lib/python3.13/site-packages/cffi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c99ec3d481788c39ea12dc57e4b61547176c8e88 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/__init__.py @@ -0,0 +1,14 @@ +__all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError', + 'FFIError'] + +from .api import FFI +from .error import CDefError, FFIError, VerificationError, VerificationMissing +from .error import PkgConfigError + +__version__ = "2.0.0" +__version_info__ = (2, 0, 0) + +# The verifier module file names are based on the CRC32 of a string that +# contains the following version number. It may be older than __version__ +# if nothing is clearly incompatible. +__version_verifier_modules__ = "0.8.6" diff --git a/miniconda3/lib/python3.13/site-packages/cffi/_cffi_errors.h b/miniconda3/lib/python3.13/site-packages/cffi/_cffi_errors.h new file mode 100644 index 0000000000000000000000000000000000000000..158e0590346a9a8b2ab047ac1bd23bcb3af21398 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/_cffi_errors.h @@ -0,0 +1,149 @@ +#ifndef CFFI_MESSAGEBOX +# ifdef _MSC_VER +# define CFFI_MESSAGEBOX 1 +# else +# define CFFI_MESSAGEBOX 0 +# endif +#endif + + +#if CFFI_MESSAGEBOX +/* Windows only: logic to take the Python-CFFI embedding logic + initialization errors and display them in a background thread + with MessageBox. The idea is that if the whole program closes + as a result of this problem, then likely it is already a console + program and you can read the stderr output in the console too. + If it is not a console program, then it will likely show its own + dialog to complain, or generally not abruptly close, and for this + case the background thread should stay alive. +*/ +static void *volatile _cffi_bootstrap_text; + +static PyObject *_cffi_start_error_capture(void) +{ + PyObject *result = NULL; + PyObject *x, *m, *bi; + + if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text, + (void *)1, NULL) != NULL) + return (PyObject *)1; + + m = PyImport_AddModule("_cffi_error_capture"); + if (m == NULL) + goto error; + + result = PyModule_GetDict(m); + if (result == NULL) + goto error; + +#if PY_MAJOR_VERSION >= 3 + bi = PyImport_ImportModule("builtins"); +#else + bi = PyImport_ImportModule("__builtin__"); +#endif + if (bi == NULL) + goto error; + PyDict_SetItemString(result, "__builtins__", bi); + Py_DECREF(bi); + + x = PyRun_String( + "import sys\n" + "class FileLike:\n" + " def write(self, x):\n" + " try:\n" + " of.write(x)\n" + " except: pass\n" + " self.buf += x\n" + " def flush(self):\n" + " pass\n" + "fl = FileLike()\n" + "fl.buf = ''\n" + "of = sys.stderr\n" + "sys.stderr = fl\n" + "def done():\n" + " sys.stderr = of\n" + " return fl.buf\n", /* make sure the returned value stays alive */ + Py_file_input, + result, result); + Py_XDECREF(x); + + error: + if (PyErr_Occurred()) + { + PyErr_WriteUnraisable(Py_None); + PyErr_Clear(); + } + return result; +} + +#pragma comment(lib, "user32.lib") + +static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored) +{ + Sleep(666); /* may be interrupted if the whole process is closing */ +#if PY_MAJOR_VERSION >= 3 + MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text, + L"Python-CFFI error", + MB_OK | MB_ICONERROR); +#else + MessageBoxA(NULL, (char *)_cffi_bootstrap_text, + "Python-CFFI error", + MB_OK | MB_ICONERROR); +#endif + _cffi_bootstrap_text = NULL; + return 0; +} + +static void _cffi_stop_error_capture(PyObject *ecap) +{ + PyObject *s; + void *text; + + if (ecap == (PyObject *)1) + return; + + if (ecap == NULL) + goto error; + + s = PyRun_String("done()", Py_eval_input, ecap, ecap); + if (s == NULL) + goto error; + + /* Show a dialog box, but in a background thread, and + never show multiple dialog boxes at once. */ +#if PY_MAJOR_VERSION >= 3 + text = PyUnicode_AsWideCharString(s, NULL); +#else + text = PyString_AsString(s); +#endif + + _cffi_bootstrap_text = text; + + if (text != NULL) + { + HANDLE h; + h = CreateThread(NULL, 0, _cffi_bootstrap_dialog, + NULL, 0, NULL); + if (h != NULL) + CloseHandle(h); + } + /* decref the string, but it should stay alive as 'fl.buf' + in the small module above. It will really be freed only if + we later get another similar error. So it's a leak of at + most one copy of the small module. That's fine for this + situation which is usually a "fatal error" anyway. */ + Py_DECREF(s); + PyErr_Clear(); + return; + + error: + _cffi_bootstrap_text = NULL; + PyErr_Clear(); +} + +#else + +static PyObject *_cffi_start_error_capture(void) { return NULL; } +static void _cffi_stop_error_capture(PyObject *ecap) { } + +#endif diff --git a/miniconda3/lib/python3.13/site-packages/cffi/_cffi_include.h b/miniconda3/lib/python3.13/site-packages/cffi/_cffi_include.h new file mode 100644 index 0000000000000000000000000000000000000000..908a1d7343f1869bc8818ca8e786f2c94a4732d2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/_cffi_include.h @@ -0,0 +1,389 @@ +#define _CFFI_ + +/* We try to define Py_LIMITED_API before including Python.h. + + Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and + Py_REF_DEBUG are not defined. This is a best-effort approximation: + we can learn about Py_DEBUG from pyconfig.h, but it is unclear if + the same works for the other two macros. Py_DEBUG implies them, + but not the other way around. + + The implementation is messy (issue #350): on Windows, with _MSC_VER, + we have to define Py_LIMITED_API even before including pyconfig.h. + In that case, we guess what pyconfig.h will do to the macros above, + and check our guess after the #include. + + Note that on Windows, with CPython 3.x, you need >= 3.5 and virtualenv + version >= 16.0.0. With older versions of either, you don't get a + copy of PYTHON3.DLL in the virtualenv. We can't check the version of + CPython *before* we even include pyconfig.h. ffi.set_source() puts + a ``#define _CFFI_NO_LIMITED_API'' at the start of this file if it is + running on Windows < 3.5, as an attempt at fixing it, but that's + arguably wrong because it may not be the target version of Python. + Still better than nothing I guess. As another workaround, you can + remove the definition of Py_LIMITED_API here. + + See also 'py_limited_api' in cffi/setuptools_ext.py. +*/ +#if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API) +# ifdef _MSC_VER +# if !defined(_DEBUG) && !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) +# define Py_LIMITED_API +# endif +# include + /* sanity-check: Py_LIMITED_API will cause crashes if any of these + are also defined. Normally, the Python file PC/pyconfig.h does not + cause any of these to be defined, with the exception that _DEBUG + causes Py_DEBUG. Double-check that. */ +# ifdef Py_LIMITED_API +# if defined(Py_DEBUG) +# error "pyconfig.h unexpectedly defines Py_DEBUG, but Py_LIMITED_API is set" +# endif +# if defined(Py_TRACE_REFS) +# error "pyconfig.h unexpectedly defines Py_TRACE_REFS, but Py_LIMITED_API is set" +# endif +# if defined(Py_REF_DEBUG) +# error "pyconfig.h unexpectedly defines Py_REF_DEBUG, but Py_LIMITED_API is set" +# endif +# endif +# else +# include +# if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) && !defined(_CFFI_NO_LIMITED_API) +# define Py_LIMITED_API +# endif +# endif +#endif + +#include +#ifdef __cplusplus +extern "C" { +#endif +#include +#include "parse_c_type.h" + +/* this block of #ifs should be kept exactly identical between + c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py + and cffi/_cffi_include.h */ +#if defined(_MSC_VER) +# include /* for alloca() */ +# if _MSC_VER < 1600 /* MSVC < 2010 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; + typedef __int8 int_least8_t; + typedef __int16 int_least16_t; + typedef __int32 int_least32_t; + typedef __int64 int_least64_t; + typedef unsigned __int8 uint_least8_t; + typedef unsigned __int16 uint_least16_t; + typedef unsigned __int32 uint_least32_t; + typedef unsigned __int64 uint_least64_t; + typedef __int8 int_fast8_t; + typedef __int16 int_fast16_t; + typedef __int32 int_fast32_t; + typedef __int64 int_fast64_t; + typedef unsigned __int8 uint_fast8_t; + typedef unsigned __int16 uint_fast16_t; + typedef unsigned __int32 uint_fast32_t; + typedef unsigned __int64 uint_fast64_t; + typedef __int64 intmax_t; + typedef unsigned __int64 uintmax_t; +# else +# include +# endif +# if _MSC_VER < 1800 /* MSVC < 2013 */ +# ifndef __cplusplus + typedef unsigned char _Bool; +# endif +# endif +# define _cffi_float_complex_t _Fcomplex /* include for it */ +# define _cffi_double_complex_t _Dcomplex /* include for it */ +#else +# include +# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) +# include +# endif +# define _cffi_float_complex_t float _Complex +# define _cffi_double_complex_t double _Complex +#endif + +#ifdef __GNUC__ +# define _CFFI_UNUSED_FN __attribute__((unused)) +#else +# define _CFFI_UNUSED_FN /* nothing */ +#endif + +#ifdef __cplusplus +# ifndef _Bool + typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */ +# endif +#endif + +/********** CPython-specific section **********/ +#ifndef PYPY_VERSION + + +#if PY_MAJOR_VERSION >= 3 +# define PyInt_FromLong PyLong_FromLong +#endif + +#define _cffi_from_c_double PyFloat_FromDouble +#define _cffi_from_c_float PyFloat_FromDouble +#define _cffi_from_c_long PyInt_FromLong +#define _cffi_from_c_ulong PyLong_FromUnsignedLong +#define _cffi_from_c_longlong PyLong_FromLongLong +#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong +#define _cffi_from_c__Bool PyBool_FromLong + +#define _cffi_to_c_double PyFloat_AsDouble +#define _cffi_to_c_float PyFloat_AsDouble + +#define _cffi_from_c_int(x, type) \ + (((type)-1) > 0 ? /* unsigned */ \ + (sizeof(type) < sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + sizeof(type) == sizeof(long) ? \ + PyLong_FromUnsignedLong((unsigned long)x) : \ + PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ + (sizeof(type) <= sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + PyLong_FromLongLong((long long)x))) + +#define _cffi_to_c_int(o, type) \ + ((type)( \ + sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ + : (type)_cffi_to_c_i8(o)) : \ + sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ + : (type)_cffi_to_c_i16(o)) : \ + sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ + : (type)_cffi_to_c_i32(o)) : \ + sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ + : (type)_cffi_to_c_i64(o)) : \ + (Py_FatalError("unsupported size for type " #type), (type)0))) + +#define _cffi_to_c_i8 \ + ((int(*)(PyObject *))_cffi_exports[1]) +#define _cffi_to_c_u8 \ + ((int(*)(PyObject *))_cffi_exports[2]) +#define _cffi_to_c_i16 \ + ((int(*)(PyObject *))_cffi_exports[3]) +#define _cffi_to_c_u16 \ + ((int(*)(PyObject *))_cffi_exports[4]) +#define _cffi_to_c_i32 \ + ((int(*)(PyObject *))_cffi_exports[5]) +#define _cffi_to_c_u32 \ + ((unsigned int(*)(PyObject *))_cffi_exports[6]) +#define _cffi_to_c_i64 \ + ((long long(*)(PyObject *))_cffi_exports[7]) +#define _cffi_to_c_u64 \ + ((unsigned long long(*)(PyObject *))_cffi_exports[8]) +#define _cffi_to_c_char \ + ((int(*)(PyObject *))_cffi_exports[9]) +#define _cffi_from_c_pointer \ + ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10]) +#define _cffi_to_c_pointer \ + ((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11]) +#define _cffi_get_struct_layout \ + not used any more +#define _cffi_restore_errno \ + ((void(*)(void))_cffi_exports[13]) +#define _cffi_save_errno \ + ((void(*)(void))_cffi_exports[14]) +#define _cffi_from_c_char \ + ((PyObject *(*)(char))_cffi_exports[15]) +#define _cffi_from_c_deref \ + ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16]) +#define _cffi_to_c \ + ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17]) +#define _cffi_from_c_struct \ + ((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18]) +#define _cffi_to_c_wchar_t \ + ((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19]) +#define _cffi_from_c_wchar_t \ + ((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20]) +#define _cffi_to_c_long_double \ + ((long double(*)(PyObject *))_cffi_exports[21]) +#define _cffi_to_c__Bool \ + ((_Bool(*)(PyObject *))_cffi_exports[22]) +#define _cffi_prepare_pointer_call_argument \ + ((Py_ssize_t(*)(struct _cffi_ctypedescr *, \ + PyObject *, char **))_cffi_exports[23]) +#define _cffi_convert_array_from_object \ + ((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24]) +#define _CFFI_CPIDX 25 +#define _cffi_call_python \ + ((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX]) +#define _cffi_to_c_wchar3216_t \ + ((int(*)(PyObject *))_cffi_exports[26]) +#define _cffi_from_c_wchar3216_t \ + ((PyObject *(*)(int))_cffi_exports[27]) +#define _CFFI_NUM_EXPORTS 28 + +struct _cffi_ctypedescr; + +static void *_cffi_exports[_CFFI_NUM_EXPORTS]; + +#define _cffi_type(index) ( \ + assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \ + (struct _cffi_ctypedescr *)_cffi_types[index]) + +static PyObject *_cffi_init(const char *module_name, Py_ssize_t version, + const struct _cffi_type_context_s *ctx) +{ + PyObject *module, *o_arg, *new_module; + void *raw[] = { + (void *)module_name, + (void *)version, + (void *)_cffi_exports, + (void *)ctx, + }; + + module = PyImport_ImportModule("_cffi_backend"); + if (module == NULL) + goto failure; + + o_arg = PyLong_FromVoidPtr((void *)raw); + if (o_arg == NULL) + goto failure; + + new_module = PyObject_CallMethod( + module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg); + + Py_DECREF(o_arg); + Py_DECREF(module); + return new_module; + + failure: + Py_XDECREF(module); + return NULL; +} + + +#ifdef HAVE_WCHAR_H +typedef wchar_t _cffi_wchar_t; +#else +typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */ +#endif + +_CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o) +{ + if (sizeof(_cffi_wchar_t) == 2) + return (uint16_t)_cffi_to_c_wchar_t(o); + else + return (uint16_t)_cffi_to_c_wchar3216_t(o); +} + +_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x) +{ + if (sizeof(_cffi_wchar_t) == 2) + return _cffi_from_c_wchar_t((_cffi_wchar_t)x); + else + return _cffi_from_c_wchar3216_t((int)x); +} + +_CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o) +{ + if (sizeof(_cffi_wchar_t) == 4) + return (int)_cffi_to_c_wchar_t(o); + else + return (int)_cffi_to_c_wchar3216_t(o); +} + +_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(unsigned int x) +{ + if (sizeof(_cffi_wchar_t) == 4) + return _cffi_from_c_wchar_t((_cffi_wchar_t)x); + else + return _cffi_from_c_wchar3216_t((int)x); +} + +union _cffi_union_alignment_u { + unsigned char m_char; + unsigned short m_short; + unsigned int m_int; + unsigned long m_long; + unsigned long long m_longlong; + float m_float; + double m_double; + long double m_longdouble; +}; + +struct _cffi_freeme_s { + struct _cffi_freeme_s *next; + union _cffi_union_alignment_u alignment; +}; + +_CFFI_UNUSED_FN static int +_cffi_convert_array_argument(struct _cffi_ctypedescr *ctptr, PyObject *arg, + char **output_data, Py_ssize_t datasize, + struct _cffi_freeme_s **freeme) +{ + char *p; + if (datasize < 0) + return -1; + + p = *output_data; + if (p == NULL) { + struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc( + offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize); + if (fp == NULL) + return -1; + fp->next = *freeme; + *freeme = fp; + p = *output_data = (char *)&fp->alignment; + } + memset((void *)p, 0, (size_t)datasize); + return _cffi_convert_array_from_object(p, ctptr, arg); +} + +_CFFI_UNUSED_FN static void +_cffi_free_array_arguments(struct _cffi_freeme_s *freeme) +{ + do { + void *p = (void *)freeme; + freeme = freeme->next; + PyObject_Free(p); + } while (freeme != NULL); +} + +/********** end CPython-specific section **********/ +#else +_CFFI_UNUSED_FN +static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *); +# define _cffi_call_python _cffi_call_python_org +#endif + + +#define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0])) + +#define _cffi_prim_int(size, sign) \ + ((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \ + (size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \ + (size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \ + (size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \ + _CFFI__UNKNOWN_PRIM) + +#define _cffi_prim_float(size) \ + ((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \ + (size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \ + (size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \ + _CFFI__UNKNOWN_FLOAT_PRIM) + +#define _cffi_check_int(got, got_nonpos, expected) \ + ((got_nonpos) == (expected <= 0) && \ + (got) == (unsigned long long)expected) + +#ifdef MS_WIN32 +# define _cffi_stdcall __stdcall +#else +# define _cffi_stdcall /* nothing */ +#endif + +#ifdef __cplusplus +} +#endif diff --git a/miniconda3/lib/python3.13/site-packages/cffi/_embedding.h b/miniconda3/lib/python3.13/site-packages/cffi/_embedding.h new file mode 100644 index 0000000000000000000000000000000000000000..64c04f67cacb5d9f2aeb295e0e48a07720d07076 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/_embedding.h @@ -0,0 +1,550 @@ + +/***** Support code for embedding *****/ + +#ifdef __cplusplus +extern "C" { +#endif + + +#if defined(_WIN32) +# define CFFI_DLLEXPORT __declspec(dllexport) +#elif defined(__GNUC__) +# define CFFI_DLLEXPORT __attribute__((visibility("default"))) +#else +# define CFFI_DLLEXPORT /* nothing */ +#endif + + +/* There are two global variables of type _cffi_call_python_fnptr: + + * _cffi_call_python, which we declare just below, is the one called + by ``extern "Python"`` implementations. + + * _cffi_call_python_org, which on CPython is actually part of the + _cffi_exports[] array, is the function pointer copied from + _cffi_backend. If _cffi_start_python() fails, then this is set + to NULL; otherwise, it should never be NULL. + + After initialization is complete, both are equal. However, the + first one remains equal to &_cffi_start_and_call_python until the + very end of initialization, when we are (or should be) sure that + concurrent threads also see a completely initialized world, and + only then is it changed. +*/ +#undef _cffi_call_python +typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *); +static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *); +static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python; + + +#ifndef _MSC_VER + /* --- Assuming a GCC not infinitely old --- */ +# define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n) +# define cffi_write_barrier() __sync_synchronize() +# if !defined(__amd64__) && !defined(__x86_64__) && \ + !defined(__i386__) && !defined(__i386) +# define cffi_read_barrier() __sync_synchronize() +# else +# define cffi_read_barrier() (void)0 +# endif +#else + /* --- Windows threads version --- */ +# include +# define cffi_compare_and_swap(l,o,n) \ + (InterlockedCompareExchangePointer(l,n,o) == (o)) +# define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0) +# define cffi_read_barrier() (void)0 +static volatile LONG _cffi_dummy; +#endif + +#ifdef WITH_THREAD +# ifndef _MSC_VER +# include + static pthread_mutex_t _cffi_embed_startup_lock; +# else + static CRITICAL_SECTION _cffi_embed_startup_lock; +# endif + static char _cffi_embed_startup_lock_ready = 0; +#endif + +static void _cffi_acquire_reentrant_mutex(void) +{ + static void *volatile lock = NULL; + + while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) { + /* should ideally do a spin loop instruction here, but + hard to do it portably and doesn't really matter I + think: pthread_mutex_init() should be very fast, and + this is only run at start-up anyway. */ + } + +#ifdef WITH_THREAD + if (!_cffi_embed_startup_lock_ready) { +# ifndef _MSC_VER + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&_cffi_embed_startup_lock, &attr); +# else + InitializeCriticalSection(&_cffi_embed_startup_lock); +# endif + _cffi_embed_startup_lock_ready = 1; + } +#endif + + while (!cffi_compare_and_swap(&lock, (void *)1, NULL)) + ; + +#ifndef _MSC_VER + pthread_mutex_lock(&_cffi_embed_startup_lock); +#else + EnterCriticalSection(&_cffi_embed_startup_lock); +#endif +} + +static void _cffi_release_reentrant_mutex(void) +{ +#ifndef _MSC_VER + pthread_mutex_unlock(&_cffi_embed_startup_lock); +#else + LeaveCriticalSection(&_cffi_embed_startup_lock); +#endif +} + + +/********** CPython-specific section **********/ +#ifndef PYPY_VERSION + +#include "_cffi_errors.h" + + +#define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX] + +PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */ + +static void _cffi_py_initialize(void) +{ + /* XXX use initsigs=0, which "skips initialization registration of + signal handlers, which might be useful when Python is + embedded" according to the Python docs. But review and think + if it should be a user-controllable setting. + + XXX we should also give a way to write errors to a buffer + instead of to stderr. + + XXX if importing 'site' fails, CPython (any version) calls + exit(). Should we try to work around this behavior here? + */ + Py_InitializeEx(0); +} + +static int _cffi_initialize_python(void) +{ + /* This initializes Python, imports _cffi_backend, and then the + present .dll/.so is set up as a CPython C extension module. + */ + int result; + PyGILState_STATE state; + PyObject *pycode=NULL, *global_dict=NULL, *x; + PyObject *builtins; + + state = PyGILState_Ensure(); + + /* Call the initxxx() function from the present module. It will + create and initialize us as a CPython extension module, instead + of letting the startup Python code do it---it might reimport + the same .dll/.so and get maybe confused on some platforms. + It might also have troubles locating the .dll/.so again for all + I know. + */ + (void)_CFFI_PYTHON_STARTUP_FUNC(); + if (PyErr_Occurred()) + goto error; + + /* Now run the Python code provided to ffi.embedding_init_code(). + */ + pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE, + "", + Py_file_input); + if (pycode == NULL) + goto error; + global_dict = PyDict_New(); + if (global_dict == NULL) + goto error; + builtins = PyEval_GetBuiltins(); + if (builtins == NULL) + goto error; + if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0) + goto error; + x = PyEval_EvalCode( +#if PY_MAJOR_VERSION < 3 + (PyCodeObject *) +#endif + pycode, global_dict, global_dict); + if (x == NULL) + goto error; + Py_DECREF(x); + + /* Done! Now if we've been called from + _cffi_start_and_call_python() in an ``extern "Python"``, we can + only hope that the Python code did correctly set up the + corresponding @ffi.def_extern() function. Otherwise, the + general logic of ``extern "Python"`` functions (inside the + _cffi_backend module) will find that the reference is still + missing and print an error. + */ + result = 0; + done: + Py_XDECREF(pycode); + Py_XDECREF(global_dict); + PyGILState_Release(state); + return result; + + error:; + { + /* Print as much information as potentially useful. + Debugging load-time failures with embedding is not fun + */ + PyObject *ecap; + PyObject *exception, *v, *tb, *f, *modules, *mod; + PyErr_Fetch(&exception, &v, &tb); + ecap = _cffi_start_error_capture(); + f = PySys_GetObject((char *)"stderr"); + if (f != NULL && f != Py_None) { + PyFile_WriteString( + "Failed to initialize the Python-CFFI embedding logic:\n\n", f); + } + + if (exception != NULL) { + PyErr_NormalizeException(&exception, &v, &tb); + PyErr_Display(exception, v, tb); + } + Py_XDECREF(exception); + Py_XDECREF(v); + Py_XDECREF(tb); + + if (f != NULL && f != Py_None) { + PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME + "\ncompiled with cffi version: 2.0.0" + "\n_cffi_backend module: ", f); + modules = PyImport_GetModuleDict(); + mod = PyDict_GetItemString(modules, "_cffi_backend"); + if (mod == NULL) { + PyFile_WriteString("not loaded", f); + } + else { + v = PyObject_GetAttrString(mod, "__file__"); + PyFile_WriteObject(v, f, 0); + Py_XDECREF(v); + } + PyFile_WriteString("\nsys.path: ", f); + PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0); + PyFile_WriteString("\n\n", f); + } + _cffi_stop_error_capture(ecap); + } + result = -1; + goto done; +} + +#if PY_VERSION_HEX < 0x03080000 +PyAPI_DATA(char *) _PyParser_TokenNames[]; /* from CPython */ +#endif + +static int _cffi_carefully_make_gil(void) +{ + /* This does the basic initialization of Python. It can be called + completely concurrently from unrelated threads. It assumes + that we don't hold the GIL before (if it exists), and we don't + hold it afterwards. + + (What it really does used to be completely different in Python 2 + and Python 3, with the Python 2 solution avoiding the spin-lock + around the Py_InitializeEx() call. However, after recent changes + to CPython 2.7 (issue #358) it no longer works. So we use the + Python 3 solution everywhere.) + + This initializes Python by calling Py_InitializeEx(). + Important: this must not be called concurrently at all. + So we use a global variable as a simple spin lock. This global + variable must be from 'libpythonX.Y.so', not from this + cffi-based extension module, because it must be shared from + different cffi-based extension modules. + + In Python < 3.8, we choose + _PyParser_TokenNames[0] as a completely arbitrary pointer value + that is never written to. The default is to point to the + string "ENDMARKER". We change it temporarily to point to the + next character in that string. (Yes, I know it's REALLY + obscure.) + + In Python >= 3.8, this string array is no longer writable, so + instead we pick PyCapsuleType.tp_version_tag. We can't change + Python < 3.8 because someone might use a mixture of cffi + embedded modules, some of which were compiled before this file + changed. + + In Python >= 3.12, this stopped working because that particular + tp_version_tag gets modified during interpreter startup. It's + arguably a bad idea before 3.12 too, but again we can't change + that because someone might use a mixture of cffi embedded + modules, and no-one reported a bug so far. In Python >= 3.12 + we go instead for PyCapsuleType.tp_as_buffer, which is supposed + to always be NULL. We write to it temporarily a pointer to + a struct full of NULLs, which is semantically the same. + */ + +#ifdef WITH_THREAD +# if PY_VERSION_HEX < 0x03080000 + char *volatile *lock = (char *volatile *)_PyParser_TokenNames; + char *old_value, *locked_value; + + while (1) { /* spin loop */ + old_value = *lock; + locked_value = old_value + 1; + if (old_value[0] == 'E') { + assert(old_value[1] == 'N'); + if (cffi_compare_and_swap(lock, old_value, locked_value)) + break; + } + else { + assert(old_value[0] == 'N'); + /* should ideally do a spin loop instruction here, but + hard to do it portably and doesn't really matter I + think: PyEval_InitThreads() should be very fast, and + this is only run at start-up anyway. */ + } + } +# else +# if PY_VERSION_HEX < 0x030C0000 + int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag; + int old_value, locked_value = -42; + assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG)); +# else + static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs; + empty_buffer_procs.mark = -42; + PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *) + &PyCapsule_Type.tp_as_buffer; + PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf; +# endif + + while (1) { /* spin loop */ + old_value = *lock; + if (old_value == 0) { + if (cffi_compare_and_swap(lock, old_value, locked_value)) + break; + } + else { +# if PY_VERSION_HEX < 0x030C0000 + assert(old_value == locked_value); +# else + /* The pointer should point to a possibly different + empty_buffer_procs from another C extension module */ + assert(((struct ebp_s *)old_value)->mark == -42); +# endif + /* should ideally do a spin loop instruction here, but + hard to do it portably and doesn't really matter I + think: PyEval_InitThreads() should be very fast, and + this is only run at start-up anyway. */ + } + } +# endif +#endif + + /* call Py_InitializeEx() */ + if (!Py_IsInitialized()) { + _cffi_py_initialize(); +#if PY_VERSION_HEX < 0x03070000 + PyEval_InitThreads(); +#endif + PyEval_SaveThread(); /* release the GIL */ + /* the returned tstate must be the one that has been stored into the + autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */ + } + else { +#if PY_VERSION_HEX < 0x03070000 + /* PyEval_InitThreads() is always a no-op from CPython 3.7 */ + PyGILState_STATE state = PyGILState_Ensure(); + PyEval_InitThreads(); + PyGILState_Release(state); +#endif + } + +#ifdef WITH_THREAD + /* release the lock */ + while (!cffi_compare_and_swap(lock, locked_value, old_value)) + ; +#endif + + return 0; +} + +/********** end CPython-specific section **********/ + + +#else + + +/********** PyPy-specific section **********/ + +PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */ + +static struct _cffi_pypy_init_s { + const char *name; + void *func; /* function pointer */ + const char *code; +} _cffi_pypy_init = { + _CFFI_MODULE_NAME, + _CFFI_PYTHON_STARTUP_FUNC, + _CFFI_PYTHON_STARTUP_CODE, +}; + +extern int pypy_carefully_make_gil(const char *); +extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *); + +static int _cffi_carefully_make_gil(void) +{ + return pypy_carefully_make_gil(_CFFI_MODULE_NAME); +} + +static int _cffi_initialize_python(void) +{ + return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init); +} + +/********** end PyPy-specific section **********/ + + +#endif + + +#ifdef __GNUC__ +__attribute__((noinline)) +#endif +static _cffi_call_python_fnptr _cffi_start_python(void) +{ + /* Delicate logic to initialize Python. This function can be + called multiple times concurrently, e.g. when the process calls + its first ``extern "Python"`` functions in multiple threads at + once. It can also be called recursively, in which case we must + ignore it. We also have to consider what occurs if several + different cffi-based extensions reach this code in parallel + threads---it is a different copy of the code, then, and we + can't have any shared global variable unless it comes from + 'libpythonX.Y.so'. + + Idea: + + * _cffi_carefully_make_gil(): "carefully" call + PyEval_InitThreads() (possibly with Py_InitializeEx() first). + + * then we use a (local) custom lock to make sure that a call to this + cffi-based extension will wait if another call to the *same* + extension is running the initialization in another thread. + It is reentrant, so that a recursive call will not block, but + only one from a different thread. + + * then we grab the GIL and (Python 2) we call Py_InitializeEx(). + At this point, concurrent calls to Py_InitializeEx() are not + possible: we have the GIL. + + * do the rest of the specific initialization, which may + temporarily release the GIL but not the custom lock. + Only release the custom lock when we are done. + */ + static char called = 0; + + if (_cffi_carefully_make_gil() != 0) + return NULL; + + _cffi_acquire_reentrant_mutex(); + + /* Here the GIL exists, but we don't have it. We're only protected + from concurrency by the reentrant mutex. */ + + /* This file only initializes the embedded module once, the first + time this is called, even if there are subinterpreters. */ + if (!called) { + called = 1; /* invoke _cffi_initialize_python() only once, + but don't set '_cffi_call_python' right now, + otherwise concurrent threads won't call + this function at all (we need them to wait) */ + if (_cffi_initialize_python() == 0) { + /* now initialization is finished. Switch to the fast-path. */ + + /* We would like nobody to see the new value of + '_cffi_call_python' without also seeing the rest of the + data initialized. However, this is not possible. But + the new value of '_cffi_call_python' is the function + 'cffi_call_python()' from _cffi_backend. So: */ + cffi_write_barrier(); + /* ^^^ we put a write barrier here, and a corresponding + read barrier at the start of cffi_call_python(). This + ensures that after that read barrier, we see everything + done here before the write barrier. + */ + + assert(_cffi_call_python_org != NULL); + _cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org; + } + else { + /* initialization failed. Reset this to NULL, even if it was + already set to some other value. Future calls to + _cffi_start_python() are still forced to occur, and will + always return NULL from now on. */ + _cffi_call_python_org = NULL; + } + } + + _cffi_release_reentrant_mutex(); + + return (_cffi_call_python_fnptr)_cffi_call_python_org; +} + +static +void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args) +{ + _cffi_call_python_fnptr fnptr; + int current_err = errno; +#ifdef _MSC_VER + int current_lasterr = GetLastError(); +#endif + fnptr = _cffi_start_python(); + if (fnptr == NULL) { + fprintf(stderr, "function %s() called, but initialization code " + "failed. Returning 0.\n", externpy->name); + memset(args, 0, externpy->size_of_result); + } +#ifdef _MSC_VER + SetLastError(current_lasterr); +#endif + errno = current_err; + + if (fnptr != NULL) + fnptr(externpy, args); +} + + +/* The cffi_start_python() function makes sure Python is initialized + and our cffi module is set up. It can be called manually from the + user C code. The same effect is obtained automatically from any + dll-exported ``extern "Python"`` function. This function returns + -1 if initialization failed, 0 if all is OK. */ +_CFFI_UNUSED_FN +static int cffi_start_python(void) +{ + if (_cffi_call_python == &_cffi_start_and_call_python) { + if (_cffi_start_python() == NULL) + return -1; + } + cffi_read_barrier(); + return 0; +} + +#undef cffi_compare_and_swap +#undef cffi_write_barrier +#undef cffi_read_barrier + +#ifdef __cplusplus +} +#endif diff --git a/miniconda3/lib/python3.13/site-packages/cffi/_imp_emulation.py b/miniconda3/lib/python3.13/site-packages/cffi/_imp_emulation.py new file mode 100644 index 0000000000000000000000000000000000000000..136abdddf9d1276095e6f6724298ac19811c136a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/_imp_emulation.py @@ -0,0 +1,83 @@ + +try: + # this works on Python < 3.12 + from imp import * + +except ImportError: + # this is a limited emulation for Python >= 3.12. + # Note that this is used only for tests or for the old ffi.verify(). + # This is copied from the source code of Python 3.11. + + from _imp import (acquire_lock, release_lock, + is_builtin, is_frozen) + + from importlib._bootstrap import _load + + from importlib import machinery + import os + import sys + import tokenize + + SEARCH_ERROR = 0 + PY_SOURCE = 1 + PY_COMPILED = 2 + C_EXTENSION = 3 + PY_RESOURCE = 4 + PKG_DIRECTORY = 5 + C_BUILTIN = 6 + PY_FROZEN = 7 + PY_CODERESOURCE = 8 + IMP_HOOK = 9 + + def get_suffixes(): + extensions = [(s, 'rb', C_EXTENSION) + for s in machinery.EXTENSION_SUFFIXES] + source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] + bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] + return extensions + source + bytecode + + def find_module(name, path=None): + if not isinstance(name, str): + raise TypeError("'name' must be a str, not {}".format(type(name))) + elif not isinstance(path, (type(None), list)): + # Backwards-compatibility + raise RuntimeError("'path' must be None or a list, " + "not {}".format(type(path))) + + if path is None: + if is_builtin(name): + return None, None, ('', '', C_BUILTIN) + elif is_frozen(name): + return None, None, ('', '', PY_FROZEN) + else: + path = sys.path + + for entry in path: + package_directory = os.path.join(entry, name) + for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: + package_file_name = '__init__' + suffix + file_path = os.path.join(package_directory, package_file_name) + if os.path.isfile(file_path): + return None, package_directory, ('', '', PKG_DIRECTORY) + for suffix, mode, type_ in get_suffixes(): + file_name = name + suffix + file_path = os.path.join(entry, file_name) + if os.path.isfile(file_path): + break + else: + continue + break # Break out of outer loop when breaking out of inner loop. + else: + raise ImportError(name, name=name) + + encoding = None + if 'b' not in mode: + with open(file_path, 'rb') as file: + encoding = tokenize.detect_encoding(file.readline)[0] + file = open(file_path, mode, encoding=encoding) + return file, file_path, (suffix, mode, type_) + + def load_dynamic(name, path, file=None): + loader = machinery.ExtensionFileLoader(name, path) + spec = machinery.ModuleSpec(name=name, loader=loader, origin=path) + return _load(spec) diff --git a/miniconda3/lib/python3.13/site-packages/cffi/_shimmed_dist_utils.py b/miniconda3/lib/python3.13/site-packages/cffi/_shimmed_dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d23128189fc121bff3f86b19330b0ac5ce0a45 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/_shimmed_dist_utils.py @@ -0,0 +1,45 @@ +""" +Temporary shim module to indirect the bits of distutils we need from setuptools/distutils while providing useful +error messages beyond `No module named 'distutils' on Python >= 3.12, or when setuptools' vendored distutils is broken. + +This is a compromise to avoid a hard-dep on setuptools for Python >= 3.12, since many users don't need runtime compilation support from CFFI. +""" +import sys + +try: + # import setuptools first; this is the most robust way to ensure its embedded distutils is available + # (the .pth shim should usually work, but this is even more robust) + import setuptools +except Exception as ex: + if sys.version_info >= (3, 12): + # Python 3.12 has no built-in distutils to fall back on, so any import problem is fatal + raise Exception("This CFFI feature requires setuptools on Python >= 3.12. The setuptools module is missing or non-functional.") from ex + + # silently ignore on older Pythons (support fallback to stdlib distutils where available) +else: + del setuptools + +try: + # bring in just the bits of distutils we need, whether they really came from setuptools or stdlib-embedded distutils + from distutils import log, sysconfig + from distutils.ccompiler import CCompiler + from distutils.command.build_ext import build_ext + from distutils.core import Distribution, Extension + from distutils.dir_util import mkpath + from distutils.errors import DistutilsSetupError, CompileError, LinkError + from distutils.log import set_threshold, set_verbosity + + if sys.platform == 'win32': + try: + # FUTURE: msvc9compiler module was removed in setuptools 74; consider removing, as it's only used by an ancient patch in `recompiler` + from distutils.msvc9compiler import MSVCCompiler + except ImportError: + MSVCCompiler = None +except Exception as ex: + if sys.version_info >= (3, 12): + raise Exception("This CFFI feature requires setuptools on Python >= 3.12. Please install the setuptools package.") from ex + + # anything older, just let the underlying distutils import error fly + raise Exception("This CFFI feature requires distutils. Please install the distutils or setuptools package.") from ex + +del sys diff --git a/miniconda3/lib/python3.13/site-packages/cffi/api.py b/miniconda3/lib/python3.13/site-packages/cffi/api.py new file mode 100644 index 0000000000000000000000000000000000000000..5a474f3da9288e51df2ab93f7c40372955986265 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/api.py @@ -0,0 +1,967 @@ +import sys, types +from .lock import allocate_lock +from .error import CDefError +from . import model + +try: + callable +except NameError: + # Python 3.1 + from collections import Callable + callable = lambda x: isinstance(x, Callable) + +try: + basestring +except NameError: + # Python 3.x + basestring = str + +_unspecified = object() + + + +class FFI(object): + r''' + The main top-level class that you instantiate once, or once per module. + + Example usage: + + ffi = FFI() + ffi.cdef(""" + int printf(const char *, ...); + """) + + C = ffi.dlopen(None) # standard library + -or- + C = ffi.verify() # use a C compiler: verify the decl above is right + + C.printf("hello, %s!\n", ffi.new("char[]", "world")) + ''' + + def __init__(self, backend=None): + """Create an FFI instance. The 'backend' argument is used to + select a non-default backend, mostly for tests. + """ + if backend is None: + # You need PyPy (>= 2.0 beta), or a CPython (>= 2.6) with + # _cffi_backend.so compiled. + import _cffi_backend as backend + from . import __version__ + if backend.__version__ != __version__: + # bad version! Try to be as explicit as possible. + if hasattr(backend, '__file__'): + # CPython + raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. When we import the top-level '_cffi_backend' extension module, we get version %s, located in %r. The two versions should be equal; check your installation." % ( + __version__, __file__, + backend.__version__, backend.__file__)) + else: + # PyPy + raise Exception("Version mismatch: this is the 'cffi' package version %s, located in %r. This interpreter comes with a built-in '_cffi_backend' module, which is version %s. The two versions should be equal; check your installation." % ( + __version__, __file__, backend.__version__)) + # (If you insist you can also try to pass the option + # 'backend=backend_ctypes.CTypesBackend()', but don't + # rely on it! It's probably not going to work well.) + + from . import cparser + self._backend = backend + self._lock = allocate_lock() + self._parser = cparser.Parser() + self._cached_btypes = {} + self._parsed_types = types.ModuleType('parsed_types').__dict__ + self._new_types = types.ModuleType('new_types').__dict__ + self._function_caches = [] + self._libraries = [] + self._cdefsources = [] + self._included_ffis = [] + self._windows_unicode = None + self._init_once_cache = {} + self._cdef_version = None + self._embedding = None + self._typecache = model.get_typecache(backend) + if hasattr(backend, 'set_ffi'): + backend.set_ffi(self) + for name in list(backend.__dict__): + if name.startswith('RTLD_'): + setattr(self, name, getattr(backend, name)) + # + with self._lock: + self.BVoidP = self._get_cached_btype(model.voidp_type) + self.BCharA = self._get_cached_btype(model.char_array_type) + if isinstance(backend, types.ModuleType): + # _cffi_backend: attach these constants to the class + if not hasattr(FFI, 'NULL'): + FFI.NULL = self.cast(self.BVoidP, 0) + FFI.CData, FFI.CType = backend._get_types() + else: + # ctypes backend: attach these constants to the instance + self.NULL = self.cast(self.BVoidP, 0) + self.CData, self.CType = backend._get_types() + self.buffer = backend.buffer + + def cdef(self, csource, override=False, packed=False, pack=None): + """Parse the given C source. This registers all declared functions, + types, and global variables. The functions and global variables can + then be accessed via either 'ffi.dlopen()' or 'ffi.verify()'. + The types can be used in 'ffi.new()' and other functions. + If 'packed' is specified as True, all structs declared inside this + cdef are packed, i.e. laid out without any field alignment at all. + Alternatively, 'pack' can be a small integer, and requests for + alignment greater than that are ignored (pack=1 is equivalent to + packed=True). + """ + self._cdef(csource, override=override, packed=packed, pack=pack) + + def embedding_api(self, csource, packed=False, pack=None): + self._cdef(csource, packed=packed, pack=pack, dllexport=True) + if self._embedding is None: + self._embedding = '' + + def _cdef(self, csource, override=False, **options): + if not isinstance(csource, str): # unicode, on Python 2 + if not isinstance(csource, basestring): + raise TypeError("cdef() argument must be a string") + csource = csource.encode('ascii') + with self._lock: + self._cdef_version = object() + self._parser.parse(csource, override=override, **options) + self._cdefsources.append(csource) + if override: + for cache in self._function_caches: + cache.clear() + finishlist = self._parser._recomplete + if finishlist: + self._parser._recomplete = [] + for tp in finishlist: + tp.finish_backend_type(self, finishlist) + + def dlopen(self, name, flags=0): + """Load and return a dynamic library identified by 'name'. + The standard C library can be loaded by passing None. + Note that functions and types declared by 'ffi.cdef()' are not + linked to a particular library, just like C headers; in the + library we only look for the actual (untyped) symbols. + """ + if not (isinstance(name, basestring) or + name is None or + isinstance(name, self.CData)): + raise TypeError("dlopen(name): name must be a file name, None, " + "or an already-opened 'void *' handle") + with self._lock: + lib, function_cache = _make_ffi_library(self, name, flags) + self._function_caches.append(function_cache) + self._libraries.append(lib) + return lib + + def dlclose(self, lib): + """Close a library obtained with ffi.dlopen(). After this call, + access to functions or variables from the library will fail + (possibly with a segmentation fault). + """ + type(lib).__cffi_close__(lib) + + def _typeof_locked(self, cdecl): + # call me with the lock! + key = cdecl + if key in self._parsed_types: + return self._parsed_types[key] + # + if not isinstance(cdecl, str): # unicode, on Python 2 + cdecl = cdecl.encode('ascii') + # + type = self._parser.parse_type(cdecl) + really_a_function_type = type.is_raw_function + if really_a_function_type: + type = type.as_function_pointer() + btype = self._get_cached_btype(type) + result = btype, really_a_function_type + self._parsed_types[key] = result + return result + + def _typeof(self, cdecl, consider_function_as_funcptr=False): + # string -> ctype object + try: + result = self._parsed_types[cdecl] + except KeyError: + with self._lock: + result = self._typeof_locked(cdecl) + # + btype, really_a_function_type = result + if really_a_function_type and not consider_function_as_funcptr: + raise CDefError("the type %r is a function type, not a " + "pointer-to-function type" % (cdecl,)) + return btype + + def typeof(self, cdecl): + """Parse the C type given as a string and return the + corresponding object. + It can also be used on 'cdata' instance to get its C type. + """ + if isinstance(cdecl, basestring): + return self._typeof(cdecl) + if isinstance(cdecl, self.CData): + return self._backend.typeof(cdecl) + if isinstance(cdecl, types.BuiltinFunctionType): + res = _builtin_function_type(cdecl) + if res is not None: + return res + if (isinstance(cdecl, types.FunctionType) + and hasattr(cdecl, '_cffi_base_type')): + with self._lock: + return self._get_cached_btype(cdecl._cffi_base_type) + raise TypeError(type(cdecl)) + + def sizeof(self, cdecl): + """Return the size in bytes of the argument. It can be a + string naming a C type, or a 'cdata' instance. + """ + if isinstance(cdecl, basestring): + BType = self._typeof(cdecl) + return self._backend.sizeof(BType) + else: + return self._backend.sizeof(cdecl) + + def alignof(self, cdecl): + """Return the natural alignment size in bytes of the C type + given as a string. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.alignof(cdecl) + + def offsetof(self, cdecl, *fields_or_indexes): + """Return the offset of the named field inside the given + structure or array, which must be given as a C type name. + You can give several field names in case of nested structures. + You can also give numeric values which correspond to array + items, in case of an array type. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._typeoffsetof(cdecl, *fields_or_indexes)[1] + + def new(self, cdecl, init=None): + """Allocate an instance according to the specified C type and + return a pointer to it. The specified C type must be either a + pointer or an array: ``new('X *')`` allocates an X and returns + a pointer to it, whereas ``new('X[n]')`` allocates an array of + n X'es and returns an array referencing it (which works + mostly like a pointer, like in C). You can also use + ``new('X[]', n)`` to allocate an array of a non-constant + length n. + + The memory is initialized following the rules of declaring a + global variable in C: by default it is zero-initialized, but + an explicit initializer can be given which can be used to + fill all or part of the memory. + + When the returned object goes out of scope, the memory + is freed. In other words the returned object has + ownership of the value of type 'cdecl' that it points to. This + means that the raw data can be used as long as this object is + kept alive, but must not be used for a longer time. Be careful + about that when copying the pointer to the memory somewhere + else, e.g. into another structure. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.newp(cdecl, init) + + def new_allocator(self, alloc=None, free=None, + should_clear_after_alloc=True): + """Return a new allocator, i.e. a function that behaves like ffi.new() + but uses the provided low-level 'alloc' and 'free' functions. + + 'alloc' is called with the size as argument. If it returns NULL, a + MemoryError is raised. 'free' is called with the result of 'alloc' + as argument. Both can be either Python function or directly C + functions. If 'free' is None, then no free function is called. + If both 'alloc' and 'free' are None, the default is used. + + If 'should_clear_after_alloc' is set to False, then the memory + returned by 'alloc' is assumed to be already cleared (or you are + fine with garbage); otherwise CFFI will clear it. + """ + compiled_ffi = self._backend.FFI() + allocator = compiled_ffi.new_allocator(alloc, free, + should_clear_after_alloc) + def allocate(cdecl, init=None): + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return allocator(cdecl, init) + return allocate + + def cast(self, cdecl, source): + """Similar to a C cast: returns an instance of the named C + type initialized with the given 'source'. The source is + casted between integers or pointers of any type. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.cast(cdecl, source) + + def string(self, cdata, maxlen=-1): + """Return a Python string (or unicode string) from the 'cdata'. + If 'cdata' is a pointer or array of characters or bytes, returns + the null-terminated string. The returned string extends until + the first null character, or at most 'maxlen' characters. If + 'cdata' is an array then 'maxlen' defaults to its length. + + If 'cdata' is a pointer or array of wchar_t, returns a unicode + string following the same rules. + + If 'cdata' is a single character or byte or a wchar_t, returns + it as a string or unicode string. + + If 'cdata' is an enum, returns the value of the enumerator as a + string, or 'NUMBER' if the value is out of range. + """ + return self._backend.string(cdata, maxlen) + + def unpack(self, cdata, length): + """Unpack an array of C data of the given length, + returning a Python string/unicode/list. + + If 'cdata' is a pointer to 'char', returns a byte string. + It does not stop at the first null. This is equivalent to: + ffi.buffer(cdata, length)[:] + + If 'cdata' is a pointer to 'wchar_t', returns a unicode string. + 'length' is measured in wchar_t's; it is not the size in bytes. + + If 'cdata' is a pointer to anything else, returns a list of + 'length' items. This is a faster equivalent to: + [cdata[i] for i in range(length)] + """ + return self._backend.unpack(cdata, length) + + #def buffer(self, cdata, size=-1): + # """Return a read-write buffer object that references the raw C data + # pointed to by the given 'cdata'. The 'cdata' must be a pointer or + # an array. Can be passed to functions expecting a buffer, or directly + # manipulated with: + # + # buf[:] get a copy of it in a regular string, or + # buf[idx] as a single character + # buf[:] = ... + # buf[idx] = ... change the content + # """ + # note that 'buffer' is a type, set on this instance by __init__ + + def from_buffer(self, cdecl, python_buffer=_unspecified, + require_writable=False): + """Return a cdata of the given type pointing to the data of the + given Python object, which must support the buffer interface. + Note that this is not meant to be used on the built-in types + str or unicode (you can build 'char[]' arrays explicitly) + but only on objects containing large quantities of raw data + in some other format, like 'array.array' or numpy arrays. + + The first argument is optional and default to 'char[]'. + """ + if python_buffer is _unspecified: + cdecl, python_buffer = self.BCharA, cdecl + elif isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + return self._backend.from_buffer(cdecl, python_buffer, + require_writable) + + def memmove(self, dest, src, n): + """ffi.memmove(dest, src, n) copies n bytes of memory from src to dest. + + Like the C function memmove(), the memory areas may overlap; + apart from that it behaves like the C function memcpy(). + + 'src' can be any cdata ptr or array, or any Python buffer object. + 'dest' can be any cdata ptr or array, or a writable Python buffer + object. The size to copy, 'n', is always measured in bytes. + + Unlike other methods, this one supports all Python buffer including + byte strings and bytearrays---but it still does not support + non-contiguous buffers. + """ + return self._backend.memmove(dest, src, n) + + def callback(self, cdecl, python_callable=None, error=None, onerror=None): + """Return a callback object or a decorator making such a + callback object. 'cdecl' must name a C function pointer type. + The callback invokes the specified 'python_callable' (which may + be provided either directly or via a decorator). Important: the + callback object must be manually kept alive for as long as the + callback may be invoked from the C level. + """ + def callback_decorator_wrap(python_callable): + if not callable(python_callable): + raise TypeError("the 'python_callable' argument " + "is not callable") + return self._backend.callback(cdecl, python_callable, + error, onerror) + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl, consider_function_as_funcptr=True) + if python_callable is None: + return callback_decorator_wrap # decorator mode + else: + return callback_decorator_wrap(python_callable) # direct mode + + def getctype(self, cdecl, replace_with=''): + """Return a string giving the C type 'cdecl', which may be itself + a string or a object. If 'replace_with' is given, it gives + extra text to append (or insert for more complicated C types), like + a variable name, or '*' to get actually the C type 'pointer-to-cdecl'. + """ + if isinstance(cdecl, basestring): + cdecl = self._typeof(cdecl) + replace_with = replace_with.strip() + if (replace_with.startswith('*') + and '&[' in self._backend.getcname(cdecl, '&')): + replace_with = '(%s)' % replace_with + elif replace_with and not replace_with[0] in '[(': + replace_with = ' ' + replace_with + return self._backend.getcname(cdecl, replace_with) + + def gc(self, cdata, destructor, size=0): + """Return a new cdata object that points to the same + data. Later, when this new cdata object is garbage-collected, + 'destructor(old_cdata_object)' will be called. + + The optional 'size' gives an estimate of the size, used to + trigger the garbage collection more eagerly. So far only used + on PyPy. It tells the GC that the returned object keeps alive + roughly 'size' bytes of external memory. + """ + return self._backend.gcp(cdata, destructor, size) + + def _get_cached_btype(self, type): + assert self._lock.acquire(False) is False + # call me with the lock! + try: + BType = self._cached_btypes[type] + except KeyError: + finishlist = [] + BType = type.get_cached_btype(self, finishlist) + for type in finishlist: + type.finish_backend_type(self, finishlist) + return BType + + def verify(self, source='', tmpdir=None, **kwargs): + """Verify that the current ffi signatures compile on this + machine, and return a dynamic library object. The dynamic + library can be used to call functions and access global + variables declared in this 'ffi'. The library is compiled + by the C compiler: it gives you C-level API compatibility + (including calling macros). This is unlike 'ffi.dlopen()', + which requires binary compatibility in the signatures. + """ + from .verifier import Verifier, _caller_dir_pycache + # + # If set_unicode(True) was called, insert the UNICODE and + # _UNICODE macro declarations + if self._windows_unicode: + self._apply_windows_unicode(kwargs) + # + # Set the tmpdir here, and not in Verifier.__init__: it picks + # up the caller's directory, which we want to be the caller of + # ffi.verify(), as opposed to the caller of Veritier(). + tmpdir = tmpdir or _caller_dir_pycache() + # + # Make a Verifier() and use it to load the library. + self.verifier = Verifier(self, source, tmpdir, **kwargs) + lib = self.verifier.load_library() + # + # Save the loaded library for keep-alive purposes, even + # if the caller doesn't keep it alive itself (it should). + self._libraries.append(lib) + return lib + + def _get_errno(self): + return self._backend.get_errno() + def _set_errno(self, errno): + self._backend.set_errno(errno) + errno = property(_get_errno, _set_errno, None, + "the value of 'errno' from/to the C calls") + + def getwinerror(self, code=-1): + return self._backend.getwinerror(code) + + def _pointer_to(self, ctype): + with self._lock: + return model.pointer_cache(self, ctype) + + def addressof(self, cdata, *fields_or_indexes): + """Return the address of a . + If 'fields_or_indexes' are given, returns the address of that + field or array item in the structure or array, recursively in + case of nested structures. + """ + try: + ctype = self._backend.typeof(cdata) + except TypeError: + if '__addressof__' in type(cdata).__dict__: + return type(cdata).__addressof__(cdata, *fields_or_indexes) + raise + if fields_or_indexes: + ctype, offset = self._typeoffsetof(ctype, *fields_or_indexes) + else: + if ctype.kind == "pointer": + raise TypeError("addressof(pointer)") + offset = 0 + ctypeptr = self._pointer_to(ctype) + return self._backend.rawaddressof(ctypeptr, cdata, offset) + + def _typeoffsetof(self, ctype, field_or_index, *fields_or_indexes): + ctype, offset = self._backend.typeoffsetof(ctype, field_or_index) + for field1 in fields_or_indexes: + ctype, offset1 = self._backend.typeoffsetof(ctype, field1, 1) + offset += offset1 + return ctype, offset + + def include(self, ffi_to_include): + """Includes the typedefs, structs, unions and enums defined + in another FFI instance. Usage is similar to a #include in C, + where a part of the program might include types defined in + another part for its own usage. Note that the include() + method has no effect on functions, constants and global + variables, which must anyway be accessed directly from the + lib object returned by the original FFI instance. + """ + if not isinstance(ffi_to_include, FFI): + raise TypeError("ffi.include() expects an argument that is also of" + " type cffi.FFI, not %r" % ( + type(ffi_to_include).__name__,)) + if ffi_to_include is self: + raise ValueError("self.include(self)") + with ffi_to_include._lock: + with self._lock: + self._parser.include(ffi_to_include._parser) + self._cdefsources.append('[') + self._cdefsources.extend(ffi_to_include._cdefsources) + self._cdefsources.append(']') + self._included_ffis.append(ffi_to_include) + + def new_handle(self, x): + return self._backend.newp_handle(self.BVoidP, x) + + def from_handle(self, x): + return self._backend.from_handle(x) + + def release(self, x): + self._backend.release(x) + + def set_unicode(self, enabled_flag): + """Windows: if 'enabled_flag' is True, enable the UNICODE and + _UNICODE defines in C, and declare the types like TCHAR and LPTCSTR + to be (pointers to) wchar_t. If 'enabled_flag' is False, + declare these types to be (pointers to) plain 8-bit characters. + This is mostly for backward compatibility; you usually want True. + """ + if self._windows_unicode is not None: + raise ValueError("set_unicode() can only be called once") + enabled_flag = bool(enabled_flag) + if enabled_flag: + self.cdef("typedef wchar_t TBYTE;" + "typedef wchar_t TCHAR;" + "typedef const wchar_t *LPCTSTR;" + "typedef const wchar_t *PCTSTR;" + "typedef wchar_t *LPTSTR;" + "typedef wchar_t *PTSTR;" + "typedef TBYTE *PTBYTE;" + "typedef TCHAR *PTCHAR;") + else: + self.cdef("typedef char TBYTE;" + "typedef char TCHAR;" + "typedef const char *LPCTSTR;" + "typedef const char *PCTSTR;" + "typedef char *LPTSTR;" + "typedef char *PTSTR;" + "typedef TBYTE *PTBYTE;" + "typedef TCHAR *PTCHAR;") + self._windows_unicode = enabled_flag + + def _apply_windows_unicode(self, kwds): + defmacros = kwds.get('define_macros', ()) + if not isinstance(defmacros, (list, tuple)): + raise TypeError("'define_macros' must be a list or tuple") + defmacros = list(defmacros) + [('UNICODE', '1'), + ('_UNICODE', '1')] + kwds['define_macros'] = defmacros + + def _apply_embedding_fix(self, kwds): + # must include an argument like "-lpython2.7" for the compiler + def ensure(key, value): + lst = kwds.setdefault(key, []) + if value not in lst: + lst.append(value) + # + if '__pypy__' in sys.builtin_module_names: + import os + if sys.platform == "win32": + # we need 'libpypy-c.lib'. Current distributions of + # pypy (>= 4.1) contain it as 'libs/python27.lib'. + pythonlib = "python{0[0]}{0[1]}".format(sys.version_info) + if hasattr(sys, 'prefix'): + ensure('library_dirs', os.path.join(sys.prefix, 'libs')) + else: + # we need 'libpypy-c.{so,dylib}', which should be by + # default located in 'sys.prefix/bin' for installed + # systems. + if sys.version_info < (3,): + pythonlib = "pypy-c" + else: + pythonlib = "pypy3-c" + if hasattr(sys, 'prefix'): + ensure('library_dirs', os.path.join(sys.prefix, 'bin')) + # On uninstalled pypy's, the libpypy-c is typically found in + # .../pypy/goal/. + if hasattr(sys, 'prefix'): + ensure('library_dirs', os.path.join(sys.prefix, 'pypy', 'goal')) + else: + if sys.platform == "win32": + template = "python%d%d" + if hasattr(sys, 'gettotalrefcount'): + template += '_d' + else: + try: + import sysconfig + except ImportError: # 2.6 + from cffi._shimmed_dist_utils import sysconfig + template = "python%d.%d" + if sysconfig.get_config_var('DEBUG_EXT'): + template += sysconfig.get_config_var('DEBUG_EXT') + pythonlib = (template % + (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff)) + if hasattr(sys, 'abiflags'): + pythonlib += sys.abiflags + ensure('libraries', pythonlib) + if sys.platform == "win32": + ensure('extra_link_args', '/MANIFEST') + + def set_source(self, module_name, source, source_extension='.c', **kwds): + import os + if hasattr(self, '_assigned_source'): + raise ValueError("set_source() cannot be called several times " + "per ffi object") + if not isinstance(module_name, basestring): + raise TypeError("'module_name' must be a string") + if os.sep in module_name or (os.altsep and os.altsep in module_name): + raise ValueError("'module_name' must not contain '/': use a dotted " + "name to make a 'package.module' location") + self._assigned_source = (str(module_name), source, + source_extension, kwds) + + def set_source_pkgconfig(self, module_name, pkgconfig_libs, source, + source_extension='.c', **kwds): + from . import pkgconfig + if not isinstance(pkgconfig_libs, list): + raise TypeError("the pkgconfig_libs argument must be a list " + "of package names") + kwds2 = pkgconfig.flags_from_pkgconfig(pkgconfig_libs) + pkgconfig.merge_flags(kwds, kwds2) + self.set_source(module_name, source, source_extension, **kwds) + + def distutils_extension(self, tmpdir='build', verbose=True): + from cffi._shimmed_dist_utils import mkpath + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + if hasattr(self, 'verifier'): # fallback, 'tmpdir' ignored + return self.verifier.get_extension() + raise ValueError("set_source() must be called before" + " distutils_extension()") + module_name, source, source_extension, kwds = self._assigned_source + if source is None: + raise TypeError("distutils_extension() is only for C extension " + "modules, not for dlopen()-style pure Python " + "modules") + mkpath(tmpdir) + ext, updated = recompile(self, module_name, + source, tmpdir=tmpdir, extradir=tmpdir, + source_extension=source_extension, + call_c_compiler=False, **kwds) + if verbose: + if updated: + sys.stderr.write("regenerated: %r\n" % (ext.sources[0],)) + else: + sys.stderr.write("not modified: %r\n" % (ext.sources[0],)) + return ext + + def emit_c_code(self, filename): + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + raise ValueError("set_source() must be called before emit_c_code()") + module_name, source, source_extension, kwds = self._assigned_source + if source is None: + raise TypeError("emit_c_code() is only for C extension modules, " + "not for dlopen()-style pure Python modules") + recompile(self, module_name, source, + c_file=filename, call_c_compiler=False, + uses_ffiplatform=False, **kwds) + + def emit_python_code(self, filename): + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + raise ValueError("set_source() must be called before emit_c_code()") + module_name, source, source_extension, kwds = self._assigned_source + if source is not None: + raise TypeError("emit_python_code() is only for dlopen()-style " + "pure Python modules, not for C extension modules") + recompile(self, module_name, source, + c_file=filename, call_c_compiler=False, + uses_ffiplatform=False, **kwds) + + def compile(self, tmpdir='.', verbose=0, target=None, debug=None): + """The 'target' argument gives the final file name of the + compiled DLL. Use '*' to force distutils' choice, suitable for + regular CPython C API modules. Use a file name ending in '.*' + to ask for the system's default extension for dynamic libraries + (.so/.dll/.dylib). + + The default is '*' when building a non-embedded C API extension, + and (module_name + '.*') when building an embedded library. + """ + from .recompiler import recompile + # + if not hasattr(self, '_assigned_source'): + raise ValueError("set_source() must be called before compile()") + module_name, source, source_extension, kwds = self._assigned_source + return recompile(self, module_name, source, tmpdir=tmpdir, + target=target, source_extension=source_extension, + compiler_verbose=verbose, debug=debug, **kwds) + + def init_once(self, func, tag): + # Read _init_once_cache[tag], which is either (False, lock) if + # we're calling the function now in some thread, or (True, result). + # Don't call setdefault() in most cases, to avoid allocating and + # immediately freeing a lock; but still use setdefaut() to avoid + # races. + try: + x = self._init_once_cache[tag] + except KeyError: + x = self._init_once_cache.setdefault(tag, (False, allocate_lock())) + # Common case: we got (True, result), so we return the result. + if x[0]: + return x[1] + # Else, it's a lock. Acquire it to serialize the following tests. + with x[1]: + # Read again from _init_once_cache the current status. + x = self._init_once_cache[tag] + if x[0]: + return x[1] + # Call the function and store the result back. + result = func() + self._init_once_cache[tag] = (True, result) + return result + + def embedding_init_code(self, pysource): + if self._embedding: + raise ValueError("embedding_init_code() can only be called once") + # fix 'pysource' before it gets dumped into the C file: + # - remove empty lines at the beginning, so it starts at "line 1" + # - dedent, if all non-empty lines are indented + # - check for SyntaxErrors + import re + match = re.match(r'\s*\n', pysource) + if match: + pysource = pysource[match.end():] + lines = pysource.splitlines() or [''] + prefix = re.match(r'\s*', lines[0]).group() + for i in range(1, len(lines)): + line = lines[i] + if line.rstrip(): + while not line.startswith(prefix): + prefix = prefix[:-1] + i = len(prefix) + lines = [line[i:]+'\n' for line in lines] + pysource = ''.join(lines) + # + compile(pysource, "cffi_init", "exec") + # + self._embedding = pysource + + def def_extern(self, *args, **kwds): + raise ValueError("ffi.def_extern() is only available on API-mode FFI " + "objects") + + def list_types(self): + """Returns the user type names known to this FFI instance. + This returns a tuple containing three lists of names: + (typedef_names, names_of_structs, names_of_unions) + """ + typedefs = [] + structs = [] + unions = [] + for key in self._parser._declarations: + if key.startswith('typedef '): + typedefs.append(key[8:]) + elif key.startswith('struct '): + structs.append(key[7:]) + elif key.startswith('union '): + unions.append(key[6:]) + typedefs.sort() + structs.sort() + unions.sort() + return (typedefs, structs, unions) + + +def _load_backend_lib(backend, name, flags): + import os + if not isinstance(name, basestring): + if sys.platform != "win32" or name is not None: + return backend.load_library(name, flags) + name = "c" # Windows: load_library(None) fails, but this works + # on Python 2 (backward compatibility hack only) + first_error = None + if '.' in name or '/' in name or os.sep in name: + try: + return backend.load_library(name, flags) + except OSError as e: + first_error = e + import ctypes.util + path = ctypes.util.find_library(name) + if path is None: + if name == "c" and sys.platform == "win32" and sys.version_info >= (3,): + raise OSError("dlopen(None) cannot work on Windows for Python 3 " + "(see http://bugs.python.org/issue23606)") + msg = ("ctypes.util.find_library() did not manage " + "to locate a library called %r" % (name,)) + if first_error is not None: + msg = "%s. Additionally, %s" % (first_error, msg) + raise OSError(msg) + return backend.load_library(path, flags) + +def _make_ffi_library(ffi, libname, flags): + backend = ffi._backend + backendlib = _load_backend_lib(backend, libname, flags) + # + def accessor_function(name): + key = 'function ' + name + tp, _ = ffi._parser._declarations[key] + BType = ffi._get_cached_btype(tp) + value = backendlib.load_function(BType, name) + library.__dict__[name] = value + # + def accessor_variable(name): + key = 'variable ' + name + tp, _ = ffi._parser._declarations[key] + BType = ffi._get_cached_btype(tp) + read_variable = backendlib.read_variable + write_variable = backendlib.write_variable + setattr(FFILibrary, name, property( + lambda self: read_variable(BType, name), + lambda self, value: write_variable(BType, name, value))) + # + def addressof_var(name): + try: + return addr_variables[name] + except KeyError: + with ffi._lock: + if name not in addr_variables: + key = 'variable ' + name + tp, _ = ffi._parser._declarations[key] + BType = ffi._get_cached_btype(tp) + if BType.kind != 'array': + BType = model.pointer_cache(ffi, BType) + p = backendlib.load_function(BType, name) + addr_variables[name] = p + return addr_variables[name] + # + def accessor_constant(name): + raise NotImplementedError("non-integer constant '%s' cannot be " + "accessed from a dlopen() library" % (name,)) + # + def accessor_int_constant(name): + library.__dict__[name] = ffi._parser._int_constants[name] + # + accessors = {} + accessors_version = [False] + addr_variables = {} + # + def update_accessors(): + if accessors_version[0] is ffi._cdef_version: + return + # + for key, (tp, _) in ffi._parser._declarations.items(): + if not isinstance(tp, model.EnumType): + tag, name = key.split(' ', 1) + if tag == 'function': + accessors[name] = accessor_function + elif tag == 'variable': + accessors[name] = accessor_variable + elif tag == 'constant': + accessors[name] = accessor_constant + else: + for i, enumname in enumerate(tp.enumerators): + def accessor_enum(name, tp=tp, i=i): + tp.check_not_partial() + library.__dict__[name] = tp.enumvalues[i] + accessors[enumname] = accessor_enum + for name in ffi._parser._int_constants: + accessors.setdefault(name, accessor_int_constant) + accessors_version[0] = ffi._cdef_version + # + def make_accessor(name): + with ffi._lock: + if name in library.__dict__ or name in FFILibrary.__dict__: + return # added by another thread while waiting for the lock + if name not in accessors: + update_accessors() + if name not in accessors: + raise AttributeError(name) + accessors[name](name) + # + class FFILibrary(object): + def __getattr__(self, name): + make_accessor(name) + return getattr(self, name) + def __setattr__(self, name, value): + try: + property = getattr(self.__class__, name) + except AttributeError: + make_accessor(name) + setattr(self, name, value) + else: + property.__set__(self, value) + def __dir__(self): + with ffi._lock: + update_accessors() + return accessors.keys() + def __addressof__(self, name): + if name in library.__dict__: + return library.__dict__[name] + if name in FFILibrary.__dict__: + return addressof_var(name) + make_accessor(name) + if name in library.__dict__: + return library.__dict__[name] + if name in FFILibrary.__dict__: + return addressof_var(name) + raise AttributeError("cffi library has no function or " + "global variable named '%s'" % (name,)) + def __cffi_close__(self): + backendlib.close_lib() + self.__dict__.clear() + # + if isinstance(libname, basestring): + try: + if not isinstance(libname, str): # unicode, on Python 2 + libname = libname.encode('utf-8') + FFILibrary.__name__ = 'FFILibrary_%s' % libname + except UnicodeError: + pass + library = FFILibrary() + return library, library.__dict__ + +def _builtin_function_type(func): + # a hack to make at least ffi.typeof(builtin_function) work, + # if the builtin function was obtained by 'vengine_cpy'. + import sys + try: + module = sys.modules[func.__module__] + ffi = module._cffi_original_ffi + types_of_builtin_funcs = module._cffi_types_of_builtin_funcs + tp = types_of_builtin_funcs[func] + except (KeyError, AttributeError, TypeError): + return None + else: + with ffi._lock: + return ffi._get_cached_btype(tp) diff --git a/miniconda3/lib/python3.13/site-packages/cffi/backend_ctypes.py b/miniconda3/lib/python3.13/site-packages/cffi/backend_ctypes.py new file mode 100644 index 0000000000000000000000000000000000000000..e7956a79cfb1c3d28a2ad22a40b261ae7dbbbb5f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/backend_ctypes.py @@ -0,0 +1,1121 @@ +import ctypes, ctypes.util, operator, sys +from . import model + +if sys.version_info < (3,): + bytechr = chr +else: + unicode = str + long = int + xrange = range + bytechr = lambda num: bytes([num]) + +class CTypesType(type): + pass + +class CTypesData(object): + __metaclass__ = CTypesType + __slots__ = ['__weakref__'] + __name__ = '' + + def __init__(self, *args): + raise TypeError("cannot instantiate %r" % (self.__class__,)) + + @classmethod + def _newp(cls, init): + raise TypeError("expected a pointer or array ctype, got '%s'" + % (cls._get_c_name(),)) + + @staticmethod + def _to_ctypes(value): + raise TypeError + + @classmethod + def _arg_to_ctypes(cls, *value): + try: + ctype = cls._ctype + except AttributeError: + raise TypeError("cannot create an instance of %r" % (cls,)) + if value: + res = cls._to_ctypes(*value) + if not isinstance(res, ctype): + res = cls._ctype(res) + else: + res = cls._ctype() + return res + + @classmethod + def _create_ctype_obj(cls, init): + if init is None: + return cls._arg_to_ctypes() + else: + return cls._arg_to_ctypes(init) + + @staticmethod + def _from_ctypes(ctypes_value): + raise TypeError + + @classmethod + def _get_c_name(cls, replace_with=''): + return cls._reftypename.replace(' &', replace_with) + + @classmethod + def _fix_class(cls): + cls.__name__ = 'CData<%s>' % (cls._get_c_name(),) + cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),) + cls.__module__ = 'ffi' + + def _get_own_repr(self): + raise NotImplementedError + + def _addr_repr(self, address): + if address == 0: + return 'NULL' + else: + if address < 0: + address += 1 << (8*ctypes.sizeof(ctypes.c_void_p)) + return '0x%x' % address + + def __repr__(self, c_name=None): + own = self._get_own_repr() + return '' % (c_name or self._get_c_name(), own) + + def _convert_to_address(self, BClass): + if BClass is None: + raise TypeError("cannot convert %r to an address" % ( + self._get_c_name(),)) + else: + raise TypeError("cannot convert %r to %r" % ( + self._get_c_name(), BClass._get_c_name())) + + @classmethod + def _get_size(cls): + return ctypes.sizeof(cls._ctype) + + def _get_size_of_instance(self): + return ctypes.sizeof(self._ctype) + + @classmethod + def _cast_from(cls, source): + raise TypeError("cannot cast to %r" % (cls._get_c_name(),)) + + def _cast_to_integer(self): + return self._convert_to_address(None) + + @classmethod + def _alignment(cls): + return ctypes.alignment(cls._ctype) + + def __iter__(self): + raise TypeError("cdata %r does not support iteration" % ( + self._get_c_name()),) + + def _make_cmp(name): + cmpfunc = getattr(operator, name) + def cmp(self, other): + v_is_ptr = not isinstance(self, CTypesGenericPrimitive) + w_is_ptr = (isinstance(other, CTypesData) and + not isinstance(other, CTypesGenericPrimitive)) + if v_is_ptr and w_is_ptr: + return cmpfunc(self._convert_to_address(None), + other._convert_to_address(None)) + elif v_is_ptr or w_is_ptr: + return NotImplemented + else: + if isinstance(self, CTypesGenericPrimitive): + self = self._value + if isinstance(other, CTypesGenericPrimitive): + other = other._value + return cmpfunc(self, other) + cmp.func_name = name + return cmp + + __eq__ = _make_cmp('__eq__') + __ne__ = _make_cmp('__ne__') + __lt__ = _make_cmp('__lt__') + __le__ = _make_cmp('__le__') + __gt__ = _make_cmp('__gt__') + __ge__ = _make_cmp('__ge__') + + def __hash__(self): + return hash(self._convert_to_address(None)) + + def _to_string(self, maxlen): + raise TypeError("string(): %r" % (self,)) + + +class CTypesGenericPrimitive(CTypesData): + __slots__ = [] + + def __hash__(self): + return hash(self._value) + + def _get_own_repr(self): + return repr(self._from_ctypes(self._value)) + + +class CTypesGenericArray(CTypesData): + __slots__ = [] + + @classmethod + def _newp(cls, init): + return cls(init) + + def __iter__(self): + for i in xrange(len(self)): + yield self[i] + + def _get_own_repr(self): + return self._addr_repr(ctypes.addressof(self._blob)) + + +class CTypesGenericPtr(CTypesData): + __slots__ = ['_address', '_as_ctype_ptr'] + _automatic_casts = False + kind = "pointer" + + @classmethod + def _newp(cls, init): + return cls(init) + + @classmethod + def _cast_from(cls, source): + if source is None: + address = 0 + elif isinstance(source, CTypesData): + address = source._cast_to_integer() + elif isinstance(source, (int, long)): + address = source + else: + raise TypeError("bad type for cast to %r: %r" % + (cls, type(source).__name__)) + return cls._new_pointer_at(address) + + @classmethod + def _new_pointer_at(cls, address): + self = cls.__new__(cls) + self._address = address + self._as_ctype_ptr = ctypes.cast(address, cls._ctype) + return self + + def _get_own_repr(self): + try: + return self._addr_repr(self._address) + except AttributeError: + return '???' + + def _cast_to_integer(self): + return self._address + + def __nonzero__(self): + return bool(self._address) + __bool__ = __nonzero__ + + @classmethod + def _to_ctypes(cls, value): + if not isinstance(value, CTypesData): + raise TypeError("unexpected %s object" % type(value).__name__) + address = value._convert_to_address(cls) + return ctypes.cast(address, cls._ctype) + + @classmethod + def _from_ctypes(cls, ctypes_ptr): + address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0 + return cls._new_pointer_at(address) + + @classmethod + def _initialize(cls, ctypes_ptr, value): + if value: + ctypes_ptr.contents = cls._to_ctypes(value).contents + + def _convert_to_address(self, BClass): + if (BClass in (self.__class__, None) or BClass._automatic_casts + or self._automatic_casts): + return self._address + else: + return CTypesData._convert_to_address(self, BClass) + + +class CTypesBaseStructOrUnion(CTypesData): + __slots__ = ['_blob'] + + @classmethod + def _create_ctype_obj(cls, init): + # may be overridden + raise TypeError("cannot instantiate opaque type %s" % (cls,)) + + def _get_own_repr(self): + return self._addr_repr(ctypes.addressof(self._blob)) + + @classmethod + def _offsetof(cls, fieldname): + return getattr(cls._ctype, fieldname).offset + + def _convert_to_address(self, BClass): + if getattr(BClass, '_BItem', None) is self.__class__: + return ctypes.addressof(self._blob) + else: + return CTypesData._convert_to_address(self, BClass) + + @classmethod + def _from_ctypes(cls, ctypes_struct_or_union): + self = cls.__new__(cls) + self._blob = ctypes_struct_or_union + return self + + @classmethod + def _to_ctypes(cls, value): + return value._blob + + def __repr__(self, c_name=None): + return CTypesData.__repr__(self, c_name or self._get_c_name(' &')) + + +class CTypesBackend(object): + + PRIMITIVE_TYPES = { + 'char': ctypes.c_char, + 'short': ctypes.c_short, + 'int': ctypes.c_int, + 'long': ctypes.c_long, + 'long long': ctypes.c_longlong, + 'signed char': ctypes.c_byte, + 'unsigned char': ctypes.c_ubyte, + 'unsigned short': ctypes.c_ushort, + 'unsigned int': ctypes.c_uint, + 'unsigned long': ctypes.c_ulong, + 'unsigned long long': ctypes.c_ulonglong, + 'float': ctypes.c_float, + 'double': ctypes.c_double, + '_Bool': ctypes.c_bool, + } + + for _name in ['unsigned long long', 'unsigned long', + 'unsigned int', 'unsigned short', 'unsigned char']: + _size = ctypes.sizeof(PRIMITIVE_TYPES[_name]) + PRIMITIVE_TYPES['uint%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_void_p): + PRIMITIVE_TYPES['uintptr_t'] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_size_t): + PRIMITIVE_TYPES['size_t'] = PRIMITIVE_TYPES[_name] + + for _name in ['long long', 'long', 'int', 'short', 'signed char']: + _size = ctypes.sizeof(PRIMITIVE_TYPES[_name]) + PRIMITIVE_TYPES['int%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_void_p): + PRIMITIVE_TYPES['intptr_t'] = PRIMITIVE_TYPES[_name] + PRIMITIVE_TYPES['ptrdiff_t'] = PRIMITIVE_TYPES[_name] + if _size == ctypes.sizeof(ctypes.c_size_t): + PRIMITIVE_TYPES['ssize_t'] = PRIMITIVE_TYPES[_name] + + + def __init__(self): + self.RTLD_LAZY = 0 # not supported anyway by ctypes + self.RTLD_NOW = 0 + self.RTLD_GLOBAL = ctypes.RTLD_GLOBAL + self.RTLD_LOCAL = ctypes.RTLD_LOCAL + + def set_ffi(self, ffi): + self.ffi = ffi + + def _get_types(self): + return CTypesData, CTypesType + + def load_library(self, path, flags=0): + cdll = ctypes.CDLL(path, flags) + return CTypesLibrary(self, cdll) + + def new_void_type(self): + class CTypesVoid(CTypesData): + __slots__ = [] + _reftypename = 'void &' + @staticmethod + def _from_ctypes(novalue): + return None + @staticmethod + def _to_ctypes(novalue): + if novalue is not None: + raise TypeError("None expected, got %s object" % + (type(novalue).__name__,)) + return None + CTypesVoid._fix_class() + return CTypesVoid + + def new_primitive_type(self, name): + if name == 'wchar_t': + raise NotImplementedError(name) + ctype = self.PRIMITIVE_TYPES[name] + if name == 'char': + kind = 'char' + elif name in ('float', 'double'): + kind = 'float' + else: + if name in ('signed char', 'unsigned char'): + kind = 'byte' + elif name == '_Bool': + kind = 'bool' + else: + kind = 'int' + is_signed = (ctype(-1).value == -1) + # + def _cast_source_to_int(source): + if isinstance(source, (int, long, float)): + source = int(source) + elif isinstance(source, CTypesData): + source = source._cast_to_integer() + elif isinstance(source, bytes): + source = ord(source) + elif source is None: + source = 0 + else: + raise TypeError("bad type for cast to %r: %r" % + (CTypesPrimitive, type(source).__name__)) + return source + # + kind1 = kind + class CTypesPrimitive(CTypesGenericPrimitive): + __slots__ = ['_value'] + _ctype = ctype + _reftypename = '%s &' % name + kind = kind1 + + def __init__(self, value): + self._value = value + + @staticmethod + def _create_ctype_obj(init): + if init is None: + return ctype() + return ctype(CTypesPrimitive._to_ctypes(init)) + + if kind == 'int' or kind == 'byte': + @classmethod + def _cast_from(cls, source): + source = _cast_source_to_int(source) + source = ctype(source).value # cast within range + return cls(source) + def __int__(self): + return self._value + + if kind == 'bool': + @classmethod + def _cast_from(cls, source): + if not isinstance(source, (int, long, float)): + source = _cast_source_to_int(source) + return cls(bool(source)) + def __int__(self): + return int(self._value) + + if kind == 'char': + @classmethod + def _cast_from(cls, source): + source = _cast_source_to_int(source) + source = bytechr(source & 0xFF) + return cls(source) + def __int__(self): + return ord(self._value) + + if kind == 'float': + @classmethod + def _cast_from(cls, source): + if isinstance(source, float): + pass + elif isinstance(source, CTypesGenericPrimitive): + if hasattr(source, '__float__'): + source = float(source) + else: + source = int(source) + else: + source = _cast_source_to_int(source) + source = ctype(source).value # fix precision + return cls(source) + def __int__(self): + return int(self._value) + def __float__(self): + return self._value + + _cast_to_integer = __int__ + + if kind == 'int' or kind == 'byte' or kind == 'bool': + @staticmethod + def _to_ctypes(x): + if not isinstance(x, (int, long)): + if isinstance(x, CTypesData): + x = int(x) + else: + raise TypeError("integer expected, got %s" % + type(x).__name__) + if ctype(x).value != x: + if not is_signed and x < 0: + raise OverflowError("%s: negative integer" % name) + else: + raise OverflowError("%s: integer out of bounds" + % name) + return x + + if kind == 'char': + @staticmethod + def _to_ctypes(x): + if isinstance(x, bytes) and len(x) == 1: + return x + if isinstance(x, CTypesPrimitive): # > + return x._value + raise TypeError("character expected, got %s" % + type(x).__name__) + def __nonzero__(self): + return ord(self._value) != 0 + else: + def __nonzero__(self): + return self._value != 0 + __bool__ = __nonzero__ + + if kind == 'float': + @staticmethod + def _to_ctypes(x): + if not isinstance(x, (int, long, float, CTypesData)): + raise TypeError("float expected, got %s" % + type(x).__name__) + return ctype(x).value + + @staticmethod + def _from_ctypes(value): + return getattr(value, 'value', value) + + @staticmethod + def _initialize(blob, init): + blob.value = CTypesPrimitive._to_ctypes(init) + + if kind == 'char': + def _to_string(self, maxlen): + return self._value + if kind == 'byte': + def _to_string(self, maxlen): + return chr(self._value & 0xff) + # + CTypesPrimitive._fix_class() + return CTypesPrimitive + + def new_pointer_type(self, BItem): + getbtype = self.ffi._get_cached_btype + if BItem is getbtype(model.PrimitiveType('char')): + kind = 'charp' + elif BItem in (getbtype(model.PrimitiveType('signed char')), + getbtype(model.PrimitiveType('unsigned char'))): + kind = 'bytep' + elif BItem is getbtype(model.void_type): + kind = 'voidp' + else: + kind = 'generic' + # + class CTypesPtr(CTypesGenericPtr): + __slots__ = ['_own'] + if kind == 'charp': + __slots__ += ['__as_strbuf'] + _BItem = BItem + if hasattr(BItem, '_ctype'): + _ctype = ctypes.POINTER(BItem._ctype) + _bitem_size = ctypes.sizeof(BItem._ctype) + else: + _ctype = ctypes.c_void_p + if issubclass(BItem, CTypesGenericArray): + _reftypename = BItem._get_c_name('(* &)') + else: + _reftypename = BItem._get_c_name(' * &') + + def __init__(self, init): + ctypeobj = BItem._create_ctype_obj(init) + if kind == 'charp': + self.__as_strbuf = ctypes.create_string_buffer( + ctypeobj.value + b'\x00') + self._as_ctype_ptr = ctypes.cast( + self.__as_strbuf, self._ctype) + else: + self._as_ctype_ptr = ctypes.pointer(ctypeobj) + self._address = ctypes.cast(self._as_ctype_ptr, + ctypes.c_void_p).value + self._own = True + + def __add__(self, other): + if isinstance(other, (int, long)): + return self._new_pointer_at(self._address + + other * self._bitem_size) + else: + return NotImplemented + + def __sub__(self, other): + if isinstance(other, (int, long)): + return self._new_pointer_at(self._address - + other * self._bitem_size) + elif type(self) is type(other): + return (self._address - other._address) // self._bitem_size + else: + return NotImplemented + + def __getitem__(self, index): + if getattr(self, '_own', False) and index != 0: + raise IndexError + return BItem._from_ctypes(self._as_ctype_ptr[index]) + + def __setitem__(self, index, value): + self._as_ctype_ptr[index] = BItem._to_ctypes(value) + + if kind == 'charp' or kind == 'voidp': + @classmethod + def _arg_to_ctypes(cls, *value): + if value and isinstance(value[0], bytes): + return ctypes.c_char_p(value[0]) + else: + return super(CTypesPtr, cls)._arg_to_ctypes(*value) + + if kind == 'charp' or kind == 'bytep': + def _to_string(self, maxlen): + if maxlen < 0: + maxlen = sys.maxsize + p = ctypes.cast(self._as_ctype_ptr, + ctypes.POINTER(ctypes.c_char)) + n = 0 + while n < maxlen and p[n] != b'\x00': + n += 1 + return b''.join([p[i] for i in range(n)]) + + def _get_own_repr(self): + if getattr(self, '_own', False): + return 'owning %d bytes' % ( + ctypes.sizeof(self._as_ctype_ptr.contents),) + return super(CTypesPtr, self)._get_own_repr() + # + if (BItem is self.ffi._get_cached_btype(model.void_type) or + BItem is self.ffi._get_cached_btype(model.PrimitiveType('char'))): + CTypesPtr._automatic_casts = True + # + CTypesPtr._fix_class() + return CTypesPtr + + def new_array_type(self, CTypesPtr, length): + if length is None: + brackets = ' &[]' + else: + brackets = ' &[%d]' % length + BItem = CTypesPtr._BItem + getbtype = self.ffi._get_cached_btype + if BItem is getbtype(model.PrimitiveType('char')): + kind = 'char' + elif BItem in (getbtype(model.PrimitiveType('signed char')), + getbtype(model.PrimitiveType('unsigned char'))): + kind = 'byte' + else: + kind = 'generic' + # + class CTypesArray(CTypesGenericArray): + __slots__ = ['_blob', '_own'] + if length is not None: + _ctype = BItem._ctype * length + else: + __slots__.append('_ctype') + _reftypename = BItem._get_c_name(brackets) + _declared_length = length + _CTPtr = CTypesPtr + + def __init__(self, init): + if length is None: + if isinstance(init, (int, long)): + len1 = init + init = None + elif kind == 'char' and isinstance(init, bytes): + len1 = len(init) + 1 # extra null + else: + init = tuple(init) + len1 = len(init) + self._ctype = BItem._ctype * len1 + self._blob = self._ctype() + self._own = True + if init is not None: + self._initialize(self._blob, init) + + @staticmethod + def _initialize(blob, init): + if isinstance(init, bytes): + init = [init[i:i+1] for i in range(len(init))] + else: + if isinstance(init, CTypesGenericArray): + if (len(init) != len(blob) or + not isinstance(init, CTypesArray)): + raise TypeError("length/type mismatch: %s" % (init,)) + init = tuple(init) + if len(init) > len(blob): + raise IndexError("too many initializers") + addr = ctypes.cast(blob, ctypes.c_void_p).value + PTR = ctypes.POINTER(BItem._ctype) + itemsize = ctypes.sizeof(BItem._ctype) + for i, value in enumerate(init): + p = ctypes.cast(addr + i * itemsize, PTR) + BItem._initialize(p.contents, value) + + def __len__(self): + return len(self._blob) + + def __getitem__(self, index): + if not (0 <= index < len(self._blob)): + raise IndexError + return BItem._from_ctypes(self._blob[index]) + + def __setitem__(self, index, value): + if not (0 <= index < len(self._blob)): + raise IndexError + self._blob[index] = BItem._to_ctypes(value) + + if kind == 'char' or kind == 'byte': + def _to_string(self, maxlen): + if maxlen < 0: + maxlen = len(self._blob) + p = ctypes.cast(self._blob, + ctypes.POINTER(ctypes.c_char)) + n = 0 + while n < maxlen and p[n] != b'\x00': + n += 1 + return b''.join([p[i] for i in range(n)]) + + def _get_own_repr(self): + if getattr(self, '_own', False): + return 'owning %d bytes' % (ctypes.sizeof(self._blob),) + return super(CTypesArray, self)._get_own_repr() + + def _convert_to_address(self, BClass): + if BClass in (CTypesPtr, None) or BClass._automatic_casts: + return ctypes.addressof(self._blob) + else: + return CTypesData._convert_to_address(self, BClass) + + @staticmethod + def _from_ctypes(ctypes_array): + self = CTypesArray.__new__(CTypesArray) + self._blob = ctypes_array + return self + + @staticmethod + def _arg_to_ctypes(value): + return CTypesPtr._arg_to_ctypes(value) + + def __add__(self, other): + if isinstance(other, (int, long)): + return CTypesPtr._new_pointer_at( + ctypes.addressof(self._blob) + + other * ctypes.sizeof(BItem._ctype)) + else: + return NotImplemented + + @classmethod + def _cast_from(cls, source): + raise NotImplementedError("casting to %r" % ( + cls._get_c_name(),)) + # + CTypesArray._fix_class() + return CTypesArray + + def _new_struct_or_union(self, kind, name, base_ctypes_class): + # + class struct_or_union(base_ctypes_class): + pass + struct_or_union.__name__ = '%s_%s' % (kind, name) + kind1 = kind + # + class CTypesStructOrUnion(CTypesBaseStructOrUnion): + __slots__ = ['_blob'] + _ctype = struct_or_union + _reftypename = '%s &' % (name,) + _kind = kind = kind1 + # + CTypesStructOrUnion._fix_class() + return CTypesStructOrUnion + + def new_struct_type(self, name): + return self._new_struct_or_union('struct', name, ctypes.Structure) + + def new_union_type(self, name): + return self._new_struct_or_union('union', name, ctypes.Union) + + def complete_struct_or_union(self, CTypesStructOrUnion, fields, tp, + totalsize=-1, totalalignment=-1, sflags=0, + pack=0): + if totalsize >= 0 or totalalignment >= 0: + raise NotImplementedError("the ctypes backend of CFFI does not support " + "structures completed by verify(); please " + "compile and install the _cffi_backend module.") + struct_or_union = CTypesStructOrUnion._ctype + fnames = [fname for (fname, BField, bitsize) in fields] + btypes = [BField for (fname, BField, bitsize) in fields] + bitfields = [bitsize for (fname, BField, bitsize) in fields] + # + bfield_types = {} + cfields = [] + for (fname, BField, bitsize) in fields: + if bitsize < 0: + cfields.append((fname, BField._ctype)) + bfield_types[fname] = BField + else: + cfields.append((fname, BField._ctype, bitsize)) + bfield_types[fname] = Ellipsis + if sflags & 8: + struct_or_union._pack_ = 1 + elif pack: + struct_or_union._pack_ = pack + struct_or_union._fields_ = cfields + CTypesStructOrUnion._bfield_types = bfield_types + # + @staticmethod + def _create_ctype_obj(init): + result = struct_or_union() + if init is not None: + initialize(result, init) + return result + CTypesStructOrUnion._create_ctype_obj = _create_ctype_obj + # + def initialize(blob, init): + if is_union: + if len(init) > 1: + raise ValueError("union initializer: %d items given, but " + "only one supported (use a dict if needed)" + % (len(init),)) + if not isinstance(init, dict): + if isinstance(init, (bytes, unicode)): + raise TypeError("union initializer: got a str") + init = tuple(init) + if len(init) > len(fnames): + raise ValueError("too many values for %s initializer" % + CTypesStructOrUnion._get_c_name()) + init = dict(zip(fnames, init)) + addr = ctypes.addressof(blob) + for fname, value in init.items(): + BField, bitsize = name2fieldtype[fname] + assert bitsize < 0, \ + "not implemented: initializer with bit fields" + offset = CTypesStructOrUnion._offsetof(fname) + PTR = ctypes.POINTER(BField._ctype) + p = ctypes.cast(addr + offset, PTR) + BField._initialize(p.contents, value) + is_union = CTypesStructOrUnion._kind == 'union' + name2fieldtype = dict(zip(fnames, zip(btypes, bitfields))) + # + for fname, BField, bitsize in fields: + if fname == '': + raise NotImplementedError("nested anonymous structs/unions") + if hasattr(CTypesStructOrUnion, fname): + raise ValueError("the field name %r conflicts in " + "the ctypes backend" % fname) + if bitsize < 0: + def getter(self, fname=fname, BField=BField, + offset=CTypesStructOrUnion._offsetof(fname), + PTR=ctypes.POINTER(BField._ctype)): + addr = ctypes.addressof(self._blob) + p = ctypes.cast(addr + offset, PTR) + return BField._from_ctypes(p.contents) + def setter(self, value, fname=fname, BField=BField): + setattr(self._blob, fname, BField._to_ctypes(value)) + # + if issubclass(BField, CTypesGenericArray): + setter = None + if BField._declared_length == 0: + def getter(self, fname=fname, BFieldPtr=BField._CTPtr, + offset=CTypesStructOrUnion._offsetof(fname), + PTR=ctypes.POINTER(BField._ctype)): + addr = ctypes.addressof(self._blob) + p = ctypes.cast(addr + offset, PTR) + return BFieldPtr._from_ctypes(p) + # + else: + def getter(self, fname=fname, BField=BField): + return BField._from_ctypes(getattr(self._blob, fname)) + def setter(self, value, fname=fname, BField=BField): + # xxx obscure workaround + value = BField._to_ctypes(value) + oldvalue = getattr(self._blob, fname) + setattr(self._blob, fname, value) + if value != getattr(self._blob, fname): + setattr(self._blob, fname, oldvalue) + raise OverflowError("value too large for bitfield") + setattr(CTypesStructOrUnion, fname, property(getter, setter)) + # + CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp)) + for fname in fnames: + if hasattr(CTypesPtr, fname): + raise ValueError("the field name %r conflicts in " + "the ctypes backend" % fname) + def getter(self, fname=fname): + return getattr(self[0], fname) + def setter(self, value, fname=fname): + setattr(self[0], fname, value) + setattr(CTypesPtr, fname, property(getter, setter)) + + def new_function_type(self, BArgs, BResult, has_varargs): + nameargs = [BArg._get_c_name() for BArg in BArgs] + if has_varargs: + nameargs.append('...') + nameargs = ', '.join(nameargs) + # + class CTypesFunctionPtr(CTypesGenericPtr): + __slots__ = ['_own_callback', '_name'] + _ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None), + *[BArg._ctype for BArg in BArgs], + use_errno=True) + _reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,)) + + def __init__(self, init, error=None): + # create a callback to the Python callable init() + import traceback + assert not has_varargs, "varargs not supported for callbacks" + if getattr(BResult, '_ctype', None) is not None: + error = BResult._from_ctypes( + BResult._create_ctype_obj(error)) + else: + error = None + def callback(*args): + args2 = [] + for arg, BArg in zip(args, BArgs): + args2.append(BArg._from_ctypes(arg)) + try: + res2 = init(*args2) + res2 = BResult._to_ctypes(res2) + except: + traceback.print_exc() + res2 = error + if issubclass(BResult, CTypesGenericPtr): + if res2: + res2 = ctypes.cast(res2, ctypes.c_void_p).value + # .value: http://bugs.python.org/issue1574593 + else: + res2 = None + #print repr(res2) + return res2 + if issubclass(BResult, CTypesGenericPtr): + # The only pointers callbacks can return are void*s: + # http://bugs.python.org/issue5710 + callback_ctype = ctypes.CFUNCTYPE( + ctypes.c_void_p, + *[BArg._ctype for BArg in BArgs], + use_errno=True) + else: + callback_ctype = CTypesFunctionPtr._ctype + self._as_ctype_ptr = callback_ctype(callback) + self._address = ctypes.cast(self._as_ctype_ptr, + ctypes.c_void_p).value + self._own_callback = init + + @staticmethod + def _initialize(ctypes_ptr, value): + if value: + raise NotImplementedError("ctypes backend: not supported: " + "initializers for function pointers") + + def __repr__(self): + c_name = getattr(self, '_name', None) + if c_name: + i = self._reftypename.index('(* &)') + if self._reftypename[i-1] not in ' )*': + c_name = ' ' + c_name + c_name = self._reftypename.replace('(* &)', c_name) + return CTypesData.__repr__(self, c_name) + + def _get_own_repr(self): + if getattr(self, '_own_callback', None) is not None: + return 'calling %r' % (self._own_callback,) + return super(CTypesFunctionPtr, self)._get_own_repr() + + def __call__(self, *args): + if has_varargs: + assert len(args) >= len(BArgs) + extraargs = args[len(BArgs):] + args = args[:len(BArgs)] + else: + assert len(args) == len(BArgs) + ctypes_args = [] + for arg, BArg in zip(args, BArgs): + ctypes_args.append(BArg._arg_to_ctypes(arg)) + if has_varargs: + for i, arg in enumerate(extraargs): + if arg is None: + ctypes_args.append(ctypes.c_void_p(0)) # NULL + continue + if not isinstance(arg, CTypesData): + raise TypeError( + "argument %d passed in the variadic part " + "needs to be a cdata object (got %s)" % + (1 + len(BArgs) + i, type(arg).__name__)) + ctypes_args.append(arg._arg_to_ctypes(arg)) + result = self._as_ctype_ptr(*ctypes_args) + return BResult._from_ctypes(result) + # + CTypesFunctionPtr._fix_class() + return CTypesFunctionPtr + + def new_enum_type(self, name, enumerators, enumvalues, CTypesInt): + assert isinstance(name, str) + reverse_mapping = dict(zip(reversed(enumvalues), + reversed(enumerators))) + # + class CTypesEnum(CTypesInt): + __slots__ = [] + _reftypename = '%s &' % name + + def _get_own_repr(self): + value = self._value + try: + return '%d: %s' % (value, reverse_mapping[value]) + except KeyError: + return str(value) + + def _to_string(self, maxlen): + value = self._value + try: + return reverse_mapping[value] + except KeyError: + return str(value) + # + CTypesEnum._fix_class() + return CTypesEnum + + def get_errno(self): + return ctypes.get_errno() + + def set_errno(self, value): + ctypes.set_errno(value) + + def string(self, b, maxlen=-1): + return b._to_string(maxlen) + + def buffer(self, bptr, size=-1): + raise NotImplementedError("buffer() with ctypes backend") + + def sizeof(self, cdata_or_BType): + if isinstance(cdata_or_BType, CTypesData): + return cdata_or_BType._get_size_of_instance() + else: + assert issubclass(cdata_or_BType, CTypesData) + return cdata_or_BType._get_size() + + def alignof(self, BType): + assert issubclass(BType, CTypesData) + return BType._alignment() + + def newp(self, BType, source): + if not issubclass(BType, CTypesData): + raise TypeError + return BType._newp(source) + + def cast(self, BType, source): + return BType._cast_from(source) + + def callback(self, BType, source, error, onerror): + assert onerror is None # XXX not implemented + return BType(source, error) + + _weakref_cache_ref = None + + def gcp(self, cdata, destructor, size=0): + if self._weakref_cache_ref is None: + import weakref + class MyRef(weakref.ref): + def __eq__(self, other): + myref = self() + return self is other or ( + myref is not None and myref is other()) + def __ne__(self, other): + return not (self == other) + def __hash__(self): + try: + return self._hash + except AttributeError: + self._hash = hash(self()) + return self._hash + self._weakref_cache_ref = {}, MyRef + weak_cache, MyRef = self._weakref_cache_ref + + if destructor is None: + try: + del weak_cache[MyRef(cdata)] + except KeyError: + raise TypeError("Can remove destructor only on a object " + "previously returned by ffi.gc()") + return None + + def remove(k): + cdata, destructor = weak_cache.pop(k, (None, None)) + if destructor is not None: + destructor(cdata) + + new_cdata = self.cast(self.typeof(cdata), cdata) + assert new_cdata is not cdata + weak_cache[MyRef(new_cdata, remove)] = (cdata, destructor) + return new_cdata + + typeof = type + + def getcname(self, BType, replace_with): + return BType._get_c_name(replace_with) + + def typeoffsetof(self, BType, fieldname, num=0): + if isinstance(fieldname, str): + if num == 0 and issubclass(BType, CTypesGenericPtr): + BType = BType._BItem + if not issubclass(BType, CTypesBaseStructOrUnion): + raise TypeError("expected a struct or union ctype") + BField = BType._bfield_types[fieldname] + if BField is Ellipsis: + raise TypeError("not supported for bitfields") + return (BField, BType._offsetof(fieldname)) + elif isinstance(fieldname, (int, long)): + if issubclass(BType, CTypesGenericArray): + BType = BType._CTPtr + if not issubclass(BType, CTypesGenericPtr): + raise TypeError("expected an array or ptr ctype") + BItem = BType._BItem + offset = BItem._get_size() * fieldname + if offset > sys.maxsize: + raise OverflowError + return (BItem, offset) + else: + raise TypeError(type(fieldname)) + + def rawaddressof(self, BTypePtr, cdata, offset=None): + if isinstance(cdata, CTypesBaseStructOrUnion): + ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata)) + elif isinstance(cdata, CTypesGenericPtr): + if offset is None or not issubclass(type(cdata)._BItem, + CTypesBaseStructOrUnion): + raise TypeError("unexpected cdata type") + ptr = type(cdata)._to_ctypes(cdata) + elif isinstance(cdata, CTypesGenericArray): + ptr = type(cdata)._to_ctypes(cdata) + else: + raise TypeError("expected a ") + if offset: + ptr = ctypes.cast( + ctypes.c_void_p( + ctypes.cast(ptr, ctypes.c_void_p).value + offset), + type(ptr)) + return BTypePtr._from_ctypes(ptr) + + +class CTypesLibrary(object): + + def __init__(self, backend, cdll): + self.backend = backend + self.cdll = cdll + + def load_function(self, BType, name): + c_func = getattr(self.cdll, name) + funcobj = BType._from_ctypes(c_func) + funcobj._name = name + return funcobj + + def read_variable(self, BType, name): + try: + ctypes_obj = BType._ctype.in_dll(self.cdll, name) + except AttributeError as e: + raise NotImplementedError(e) + return BType._from_ctypes(ctypes_obj) + + def write_variable(self, BType, name, value): + new_ctypes_obj = BType._to_ctypes(value) + ctypes_obj = BType._ctype.in_dll(self.cdll, name) + ctypes.memmove(ctypes.addressof(ctypes_obj), + ctypes.addressof(new_ctypes_obj), + ctypes.sizeof(BType._ctype)) diff --git a/miniconda3/lib/python3.13/site-packages/cffi/cffi_opcode.py b/miniconda3/lib/python3.13/site-packages/cffi/cffi_opcode.py new file mode 100644 index 0000000000000000000000000000000000000000..6421df62134ce43a10d72b3b404102681574abf3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/cffi_opcode.py @@ -0,0 +1,187 @@ +from .error import VerificationError + +class CffiOp(object): + def __init__(self, op, arg): + self.op = op + self.arg = arg + + def as_c_expr(self): + if self.op is None: + assert isinstance(self.arg, str) + return '(_cffi_opcode_t)(%s)' % (self.arg,) + classname = CLASS_NAME[self.op] + return '_CFFI_OP(_CFFI_OP_%s, %s)' % (classname, self.arg) + + def as_python_bytes(self): + if self.op is None and self.arg.isdigit(): + value = int(self.arg) # non-negative: '-' not in self.arg + if value >= 2**31: + raise OverflowError("cannot emit %r: limited to 2**31-1" + % (self.arg,)) + return format_four_bytes(value) + if isinstance(self.arg, str): + raise VerificationError("cannot emit to Python: %r" % (self.arg,)) + return format_four_bytes((self.arg << 8) | self.op) + + def __str__(self): + classname = CLASS_NAME.get(self.op, self.op) + return '(%s %s)' % (classname, self.arg) + +def format_four_bytes(num): + return '\\x%02X\\x%02X\\x%02X\\x%02X' % ( + (num >> 24) & 0xFF, + (num >> 16) & 0xFF, + (num >> 8) & 0xFF, + (num ) & 0xFF) + +OP_PRIMITIVE = 1 +OP_POINTER = 3 +OP_ARRAY = 5 +OP_OPEN_ARRAY = 7 +OP_STRUCT_UNION = 9 +OP_ENUM = 11 +OP_FUNCTION = 13 +OP_FUNCTION_END = 15 +OP_NOOP = 17 +OP_BITFIELD = 19 +OP_TYPENAME = 21 +OP_CPYTHON_BLTN_V = 23 # varargs +OP_CPYTHON_BLTN_N = 25 # noargs +OP_CPYTHON_BLTN_O = 27 # O (i.e. a single arg) +OP_CONSTANT = 29 +OP_CONSTANT_INT = 31 +OP_GLOBAL_VAR = 33 +OP_DLOPEN_FUNC = 35 +OP_DLOPEN_CONST = 37 +OP_GLOBAL_VAR_F = 39 +OP_EXTERN_PYTHON = 41 + +PRIM_VOID = 0 +PRIM_BOOL = 1 +PRIM_CHAR = 2 +PRIM_SCHAR = 3 +PRIM_UCHAR = 4 +PRIM_SHORT = 5 +PRIM_USHORT = 6 +PRIM_INT = 7 +PRIM_UINT = 8 +PRIM_LONG = 9 +PRIM_ULONG = 10 +PRIM_LONGLONG = 11 +PRIM_ULONGLONG = 12 +PRIM_FLOAT = 13 +PRIM_DOUBLE = 14 +PRIM_LONGDOUBLE = 15 + +PRIM_WCHAR = 16 +PRIM_INT8 = 17 +PRIM_UINT8 = 18 +PRIM_INT16 = 19 +PRIM_UINT16 = 20 +PRIM_INT32 = 21 +PRIM_UINT32 = 22 +PRIM_INT64 = 23 +PRIM_UINT64 = 24 +PRIM_INTPTR = 25 +PRIM_UINTPTR = 26 +PRIM_PTRDIFF = 27 +PRIM_SIZE = 28 +PRIM_SSIZE = 29 +PRIM_INT_LEAST8 = 30 +PRIM_UINT_LEAST8 = 31 +PRIM_INT_LEAST16 = 32 +PRIM_UINT_LEAST16 = 33 +PRIM_INT_LEAST32 = 34 +PRIM_UINT_LEAST32 = 35 +PRIM_INT_LEAST64 = 36 +PRIM_UINT_LEAST64 = 37 +PRIM_INT_FAST8 = 38 +PRIM_UINT_FAST8 = 39 +PRIM_INT_FAST16 = 40 +PRIM_UINT_FAST16 = 41 +PRIM_INT_FAST32 = 42 +PRIM_UINT_FAST32 = 43 +PRIM_INT_FAST64 = 44 +PRIM_UINT_FAST64 = 45 +PRIM_INTMAX = 46 +PRIM_UINTMAX = 47 +PRIM_FLOATCOMPLEX = 48 +PRIM_DOUBLECOMPLEX = 49 +PRIM_CHAR16 = 50 +PRIM_CHAR32 = 51 + +_NUM_PRIM = 52 +_UNKNOWN_PRIM = -1 +_UNKNOWN_FLOAT_PRIM = -2 +_UNKNOWN_LONG_DOUBLE = -3 + +_IO_FILE_STRUCT = -1 + +PRIMITIVE_TO_INDEX = { + 'char': PRIM_CHAR, + 'short': PRIM_SHORT, + 'int': PRIM_INT, + 'long': PRIM_LONG, + 'long long': PRIM_LONGLONG, + 'signed char': PRIM_SCHAR, + 'unsigned char': PRIM_UCHAR, + 'unsigned short': PRIM_USHORT, + 'unsigned int': PRIM_UINT, + 'unsigned long': PRIM_ULONG, + 'unsigned long long': PRIM_ULONGLONG, + 'float': PRIM_FLOAT, + 'double': PRIM_DOUBLE, + 'long double': PRIM_LONGDOUBLE, + '_cffi_float_complex_t': PRIM_FLOATCOMPLEX, + '_cffi_double_complex_t': PRIM_DOUBLECOMPLEX, + '_Bool': PRIM_BOOL, + 'wchar_t': PRIM_WCHAR, + 'char16_t': PRIM_CHAR16, + 'char32_t': PRIM_CHAR32, + 'int8_t': PRIM_INT8, + 'uint8_t': PRIM_UINT8, + 'int16_t': PRIM_INT16, + 'uint16_t': PRIM_UINT16, + 'int32_t': PRIM_INT32, + 'uint32_t': PRIM_UINT32, + 'int64_t': PRIM_INT64, + 'uint64_t': PRIM_UINT64, + 'intptr_t': PRIM_INTPTR, + 'uintptr_t': PRIM_UINTPTR, + 'ptrdiff_t': PRIM_PTRDIFF, + 'size_t': PRIM_SIZE, + 'ssize_t': PRIM_SSIZE, + 'int_least8_t': PRIM_INT_LEAST8, + 'uint_least8_t': PRIM_UINT_LEAST8, + 'int_least16_t': PRIM_INT_LEAST16, + 'uint_least16_t': PRIM_UINT_LEAST16, + 'int_least32_t': PRIM_INT_LEAST32, + 'uint_least32_t': PRIM_UINT_LEAST32, + 'int_least64_t': PRIM_INT_LEAST64, + 'uint_least64_t': PRIM_UINT_LEAST64, + 'int_fast8_t': PRIM_INT_FAST8, + 'uint_fast8_t': PRIM_UINT_FAST8, + 'int_fast16_t': PRIM_INT_FAST16, + 'uint_fast16_t': PRIM_UINT_FAST16, + 'int_fast32_t': PRIM_INT_FAST32, + 'uint_fast32_t': PRIM_UINT_FAST32, + 'int_fast64_t': PRIM_INT_FAST64, + 'uint_fast64_t': PRIM_UINT_FAST64, + 'intmax_t': PRIM_INTMAX, + 'uintmax_t': PRIM_UINTMAX, + } + +F_UNION = 0x01 +F_CHECK_FIELDS = 0x02 +F_PACKED = 0x04 +F_EXTERNAL = 0x08 +F_OPAQUE = 0x10 + +G_FLAGS = dict([('_CFFI_' + _key, globals()[_key]) + for _key in ['F_UNION', 'F_CHECK_FIELDS', 'F_PACKED', + 'F_EXTERNAL', 'F_OPAQUE']]) + +CLASS_NAME = {} +for _name, _value in list(globals().items()): + if _name.startswith('OP_') and isinstance(_value, int): + CLASS_NAME[_value] = _name[3:] diff --git a/miniconda3/lib/python3.13/site-packages/cffi/commontypes.py b/miniconda3/lib/python3.13/site-packages/cffi/commontypes.py new file mode 100644 index 0000000000000000000000000000000000000000..d4dae3517009fc3f7ccaf01d97d10df098700d06 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/commontypes.py @@ -0,0 +1,82 @@ +import sys +from . import model +from .error import FFIError + + +COMMON_TYPES = {} + +try: + # fetch "bool" and all simple Windows types + from _cffi_backend import _get_common_types + _get_common_types(COMMON_TYPES) +except ImportError: + pass + +COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE') +COMMON_TYPES['bool'] = '_Bool' # in case we got ImportError above +COMMON_TYPES['float _Complex'] = '_cffi_float_complex_t' +COMMON_TYPES['double _Complex'] = '_cffi_double_complex_t' + +for _type in model.PrimitiveType.ALL_PRIMITIVE_TYPES: + if _type.endswith('_t'): + COMMON_TYPES[_type] = _type +del _type + +_CACHE = {} + +def resolve_common_type(parser, commontype): + try: + return _CACHE[commontype] + except KeyError: + cdecl = COMMON_TYPES.get(commontype, commontype) + if not isinstance(cdecl, str): + result, quals = cdecl, 0 # cdecl is already a BaseType + elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES: + result, quals = model.PrimitiveType(cdecl), 0 + elif cdecl == 'set-unicode-needed': + raise FFIError("The Windows type %r is only available after " + "you call ffi.set_unicode()" % (commontype,)) + else: + if commontype == cdecl: + raise FFIError( + "Unsupported type: %r. Please look at " + "http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations " + "and file an issue if you think this type should really " + "be supported." % (commontype,)) + result, quals = parser.parse_type_and_quals(cdecl) # recursive + + assert isinstance(result, model.BaseTypeByIdentity) + _CACHE[commontype] = result, quals + return result, quals + + +# ____________________________________________________________ +# extra types for Windows (most of them are in commontypes.c) + + +def win_common_types(): + return { + "UNICODE_STRING": model.StructType( + "_UNICODE_STRING", + ["Length", + "MaximumLength", + "Buffer"], + [model.PrimitiveType("unsigned short"), + model.PrimitiveType("unsigned short"), + model.PointerType(model.PrimitiveType("wchar_t"))], + [-1, -1, -1]), + "PUNICODE_STRING": "UNICODE_STRING *", + "PCUNICODE_STRING": "const UNICODE_STRING *", + + "TBYTE": "set-unicode-needed", + "TCHAR": "set-unicode-needed", + "LPCTSTR": "set-unicode-needed", + "PCTSTR": "set-unicode-needed", + "LPTSTR": "set-unicode-needed", + "PTSTR": "set-unicode-needed", + "PTBYTE": "set-unicode-needed", + "PTCHAR": "set-unicode-needed", + } + +if sys.platform == 'win32': + COMMON_TYPES.update(win_common_types()) diff --git a/miniconda3/lib/python3.13/site-packages/cffi/cparser.py b/miniconda3/lib/python3.13/site-packages/cffi/cparser.py new file mode 100644 index 0000000000000000000000000000000000000000..dd590d8743d1828eb6139401b2269d173f487b6c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/cparser.py @@ -0,0 +1,1015 @@ +from . import model +from .commontypes import COMMON_TYPES, resolve_common_type +from .error import FFIError, CDefError +try: + from . import _pycparser as pycparser +except ImportError: + import pycparser +import weakref, re, sys + +try: + if sys.version_info < (3,): + import thread as _thread + else: + import _thread + lock = _thread.allocate_lock() +except ImportError: + lock = None + +def _workaround_for_static_import_finders(): + # Issue #392: packaging tools like cx_Freeze can not find these + # because pycparser uses exec dynamic import. This is an obscure + # workaround. This function is never called. + import pycparser.yacctab + import pycparser.lextab + +CDEF_SOURCE_STRING = "" +_r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$", + re.DOTALL | re.MULTILINE) +_r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)" + r"\b((?:[^\n\\]|\\.)*?)$", + re.DOTALL | re.MULTILINE) +_r_line_directive = re.compile(r"^[ \t]*#[ \t]*(?:line|\d+)\b.*$", re.MULTILINE) +_r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}") +_r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$") +_r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]") +_r_words = re.compile(r"\w+|\S") +_parser_cache = None +_r_int_literal = re.compile(r"-?0?x?[0-9a-f]+[lu]*$", re.IGNORECASE) +_r_stdcall1 = re.compile(r"\b(__stdcall|WINAPI)\b") +_r_stdcall2 = re.compile(r"[(]\s*(__stdcall|WINAPI)\b") +_r_cdecl = re.compile(r"\b__cdecl\b") +_r_extern_python = re.compile(r'\bextern\s*"' + r'(Python|Python\s*\+\s*C|C\s*\+\s*Python)"\s*.') +_r_star_const_space = re.compile( # matches "* const " + r"[*]\s*((const|volatile|restrict)\b\s*)+") +_r_int_dotdotdot = re.compile(r"(\b(int|long|short|signed|unsigned|char)\s*)+" + r"\.\.\.") +_r_float_dotdotdot = re.compile(r"\b(double|float)\s*\.\.\.") + +def _get_parser(): + global _parser_cache + if _parser_cache is None: + _parser_cache = pycparser.CParser() + return _parser_cache + +def _workaround_for_old_pycparser(csource): + # Workaround for a pycparser issue (fixed between pycparser 2.10 and + # 2.14): "char*const***" gives us a wrong syntax tree, the same as + # for "char***(*const)". This means we can't tell the difference + # afterwards. But "char(*const(***))" gives us the right syntax + # tree. The issue only occurs if there are several stars in + # sequence with no parenthesis in between, just possibly qualifiers. + # Attempt to fix it by adding some parentheses in the source: each + # time we see "* const" or "* const *", we add an opening + # parenthesis before each star---the hard part is figuring out where + # to close them. + parts = [] + while True: + match = _r_star_const_space.search(csource) + if not match: + break + #print repr(''.join(parts)+csource), '=>', + parts.append(csource[:match.start()]) + parts.append('('); closing = ')' + parts.append(match.group()) # e.g. "* const " + endpos = match.end() + if csource.startswith('*', endpos): + parts.append('('); closing += ')' + level = 0 + i = endpos + while i < len(csource): + c = csource[i] + if c == '(': + level += 1 + elif c == ')': + if level == 0: + break + level -= 1 + elif c in ',;=': + if level == 0: + break + i += 1 + csource = csource[endpos:i] + closing + csource[i:] + #print repr(''.join(parts)+csource) + parts.append(csource) + return ''.join(parts) + +def _preprocess_extern_python(csource): + # input: `extern "Python" int foo(int);` or + # `extern "Python" { int foo(int); }` + # output: + # void __cffi_extern_python_start; + # int foo(int); + # void __cffi_extern_python_stop; + # + # input: `extern "Python+C" int foo(int);` + # output: + # void __cffi_extern_python_plus_c_start; + # int foo(int); + # void __cffi_extern_python_stop; + parts = [] + while True: + match = _r_extern_python.search(csource) + if not match: + break + endpos = match.end() - 1 + #print + #print ''.join(parts)+csource + #print '=>' + parts.append(csource[:match.start()]) + if 'C' in match.group(1): + parts.append('void __cffi_extern_python_plus_c_start; ') + else: + parts.append('void __cffi_extern_python_start; ') + if csource[endpos] == '{': + # grouping variant + closing = csource.find('}', endpos) + if closing < 0: + raise CDefError("'extern \"Python\" {': no '}' found") + if csource.find('{', endpos + 1, closing) >= 0: + raise NotImplementedError("cannot use { } inside a block " + "'extern \"Python\" { ... }'") + parts.append(csource[endpos+1:closing]) + csource = csource[closing+1:] + else: + # non-grouping variant + semicolon = csource.find(';', endpos) + if semicolon < 0: + raise CDefError("'extern \"Python\": no ';' found") + parts.append(csource[endpos:semicolon+1]) + csource = csource[semicolon+1:] + parts.append(' void __cffi_extern_python_stop;') + #print ''.join(parts)+csource + #print + parts.append(csource) + return ''.join(parts) + +def _warn_for_string_literal(csource): + if '"' not in csource: + return + for line in csource.splitlines(): + if '"' in line and not line.lstrip().startswith('#'): + import warnings + warnings.warn("String literal found in cdef() or type source. " + "String literals are ignored here, but you should " + "remove them anyway because some character sequences " + "confuse pre-parsing.") + break + +def _warn_for_non_extern_non_static_global_variable(decl): + if not decl.storage: + import warnings + warnings.warn("Global variable '%s' in cdef(): for consistency " + "with C it should have a storage class specifier " + "(usually 'extern')" % (decl.name,)) + +def _remove_line_directives(csource): + # _r_line_directive matches whole lines, without the final \n, if they + # start with '#line' with some spacing allowed, or '#NUMBER'. This + # function stores them away and replaces them with exactly the string + # '#line@N', where N is the index in the list 'line_directives'. + line_directives = [] + def replace(m): + i = len(line_directives) + line_directives.append(m.group()) + return '#line@%d' % i + csource = _r_line_directive.sub(replace, csource) + return csource, line_directives + +def _put_back_line_directives(csource, line_directives): + def replace(m): + s = m.group() + if not s.startswith('#line@'): + raise AssertionError("unexpected #line directive " + "(should have been processed and removed") + return line_directives[int(s[6:])] + return _r_line_directive.sub(replace, csource) + +def _preprocess(csource): + # First, remove the lines of the form '#line N "filename"' because + # the "filename" part could confuse the rest + csource, line_directives = _remove_line_directives(csource) + # Remove comments. NOTE: this only work because the cdef() section + # should not contain any string literals (except in line directives)! + def replace_keeping_newlines(m): + return ' ' + m.group().count('\n') * '\n' + csource = _r_comment.sub(replace_keeping_newlines, csource) + # Remove the "#define FOO x" lines + macros = {} + for match in _r_define.finditer(csource): + macroname, macrovalue = match.groups() + macrovalue = macrovalue.replace('\\\n', '').strip() + macros[macroname] = macrovalue + csource = _r_define.sub('', csource) + # + if pycparser.__version__ < '2.14': + csource = _workaround_for_old_pycparser(csource) + # + # BIG HACK: replace WINAPI or __stdcall with "volatile const". + # It doesn't make sense for the return type of a function to be + # "volatile volatile const", so we abuse it to detect __stdcall... + # Hack number 2 is that "int(volatile *fptr)();" is not valid C + # syntax, so we place the "volatile" before the opening parenthesis. + csource = _r_stdcall2.sub(' volatile volatile const(', csource) + csource = _r_stdcall1.sub(' volatile volatile const ', csource) + csource = _r_cdecl.sub(' ', csource) + # + # Replace `extern "Python"` with start/end markers + csource = _preprocess_extern_python(csource) + # + # Now there should not be any string literal left; warn if we get one + _warn_for_string_literal(csource) + # + # Replace "[...]" with "[__dotdotdotarray__]" + csource = _r_partial_array.sub('[__dotdotdotarray__]', csource) + # + # Replace "...}" with "__dotdotdotNUM__}". This construction should + # occur only at the end of enums; at the end of structs we have "...;}" + # and at the end of vararg functions "...);". Also replace "=...[,}]" + # with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when + # giving an unknown value. + matches = list(_r_partial_enum.finditer(csource)) + for number, match in enumerate(reversed(matches)): + p = match.start() + if csource[p] == '=': + p2 = csource.find('...', p, match.end()) + assert p2 > p + csource = '%s,__dotdotdot%d__ %s' % (csource[:p], number, + csource[p2+3:]) + else: + assert csource[p:p+3] == '...' + csource = '%s __dotdotdot%d__ %s' % (csource[:p], number, + csource[p+3:]) + # Replace "int ..." or "unsigned long int..." with "__dotdotdotint__" + csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource) + # Replace "float ..." or "double..." with "__dotdotdotfloat__" + csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource) + # Replace all remaining "..." with the same name, "__dotdotdot__", + # which is declared with a typedef for the purpose of C parsing. + csource = csource.replace('...', ' __dotdotdot__ ') + # Finally, put back the line directives + csource = _put_back_line_directives(csource, line_directives) + return csource, macros + +def _common_type_names(csource): + # Look in the source for what looks like usages of types from the + # list of common types. A "usage" is approximated here as the + # appearance of the word, minus a "definition" of the type, which + # is the last word in a "typedef" statement. Approximative only + # but should be fine for all the common types. + look_for_words = set(COMMON_TYPES) + look_for_words.add(';') + look_for_words.add(',') + look_for_words.add('(') + look_for_words.add(')') + look_for_words.add('typedef') + words_used = set() + is_typedef = False + paren = 0 + previous_word = '' + for word in _r_words.findall(csource): + if word in look_for_words: + if word == ';': + if is_typedef: + words_used.discard(previous_word) + look_for_words.discard(previous_word) + is_typedef = False + elif word == 'typedef': + is_typedef = True + paren = 0 + elif word == '(': + paren += 1 + elif word == ')': + paren -= 1 + elif word == ',': + if is_typedef and paren == 0: + words_used.discard(previous_word) + look_for_words.discard(previous_word) + else: # word in COMMON_TYPES + words_used.add(word) + previous_word = word + return words_used + + +class Parser(object): + + def __init__(self): + self._declarations = {} + self._included_declarations = set() + self._anonymous_counter = 0 + self._structnode2type = weakref.WeakKeyDictionary() + self._options = {} + self._int_constants = {} + self._recomplete = [] + self._uses_new_feature = None + + def _parse(self, csource): + csource, macros = _preprocess(csource) + # XXX: for more efficiency we would need to poke into the + # internals of CParser... the following registers the + # typedefs, because their presence or absence influences the + # parsing itself (but what they are typedef'ed to plays no role) + ctn = _common_type_names(csource) + typenames = [] + for name in sorted(self._declarations): + if name.startswith('typedef '): + name = name[8:] + typenames.append(name) + ctn.discard(name) + typenames += sorted(ctn) + # + csourcelines = [] + csourcelines.append('# 1 ""') + for typename in typenames: + csourcelines.append('typedef int %s;' % typename) + csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,' + ' __dotdotdot__;') + # this forces pycparser to consider the following in the file + # called from line 1 + csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,)) + csourcelines.append(csource) + csourcelines.append('') # see test_missing_newline_bug + fullcsource = '\n'.join(csourcelines) + if lock is not None: + lock.acquire() # pycparser is not thread-safe... + try: + ast = _get_parser().parse(fullcsource) + except pycparser.c_parser.ParseError as e: + self.convert_pycparser_error(e, csource) + finally: + if lock is not None: + lock.release() + # csource will be used to find buggy source text + return ast, macros, csource + + def _convert_pycparser_error(self, e, csource): + # xxx look for ":NUM:" at the start of str(e) + # and interpret that as a line number. This will not work if + # the user gives explicit ``# NUM "FILE"`` directives. + line = None + msg = str(e) + match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg) + if match: + linenum = int(match.group(1), 10) + csourcelines = csource.splitlines() + if 1 <= linenum <= len(csourcelines): + line = csourcelines[linenum-1] + return line + + def convert_pycparser_error(self, e, csource): + line = self._convert_pycparser_error(e, csource) + + msg = str(e) + if line: + msg = 'cannot parse "%s"\n%s' % (line.strip(), msg) + else: + msg = 'parse error\n%s' % (msg,) + raise CDefError(msg) + + def parse(self, csource, override=False, packed=False, pack=None, + dllexport=False): + if packed: + if packed != True: + raise ValueError("'packed' should be False or True; use " + "'pack' to give another value") + if pack: + raise ValueError("cannot give both 'pack' and 'packed'") + pack = 1 + elif pack: + if pack & (pack - 1): + raise ValueError("'pack' must be a power of two, not %r" % + (pack,)) + else: + pack = 0 + prev_options = self._options + try: + self._options = {'override': override, + 'packed': pack, + 'dllexport': dllexport} + self._internal_parse(csource) + finally: + self._options = prev_options + + def _internal_parse(self, csource): + ast, macros, csource = self._parse(csource) + # add the macros + self._process_macros(macros) + # find the first "__dotdotdot__" and use that as a separator + # between the repeated typedefs and the real csource + iterator = iter(ast.ext) + for decl in iterator: + if decl.name == '__dotdotdot__': + break + else: + assert 0 + current_decl = None + # + try: + self._inside_extern_python = '__cffi_extern_python_stop' + for decl in iterator: + current_decl = decl + if isinstance(decl, pycparser.c_ast.Decl): + self._parse_decl(decl) + elif isinstance(decl, pycparser.c_ast.Typedef): + if not decl.name: + raise CDefError("typedef does not declare any name", + decl) + quals = 0 + if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType) and + decl.type.type.names[-1].startswith('__dotdotdot')): + realtype = self._get_unknown_type(decl) + elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and + isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and + isinstance(decl.type.type.type, + pycparser.c_ast.IdentifierType) and + decl.type.type.type.names[-1].startswith('__dotdotdot')): + realtype = self._get_unknown_ptr_type(decl) + else: + realtype, quals = self._get_type_and_quals( + decl.type, name=decl.name, partial_length_ok=True, + typedef_example="*(%s *)0" % (decl.name,)) + self._declare('typedef ' + decl.name, realtype, quals=quals) + elif decl.__class__.__name__ == 'Pragma': + # skip pragma, only in pycparser 2.15 + import warnings + warnings.warn( + "#pragma in cdef() are entirely ignored. " + "They should be removed for now, otherwise your " + "code might behave differently in a future version " + "of CFFI if #pragma support gets added. Note that " + "'#pragma pack' needs to be replaced with the " + "'packed' keyword argument to cdef().") + else: + raise CDefError("unexpected <%s>: this construct is valid " + "C but not valid in cdef()" % + decl.__class__.__name__, decl) + except CDefError as e: + if len(e.args) == 1: + e.args = e.args + (current_decl,) + raise + except FFIError as e: + msg = self._convert_pycparser_error(e, csource) + if msg: + e.args = (e.args[0] + "\n *** Err: %s" % msg,) + raise + + def _add_constants(self, key, val): + if key in self._int_constants: + if self._int_constants[key] == val: + return # ignore identical double declarations + raise FFIError( + "multiple declarations of constant: %s" % (key,)) + self._int_constants[key] = val + + def _add_integer_constant(self, name, int_str): + int_str = int_str.lower().rstrip("ul") + neg = int_str.startswith('-') + if neg: + int_str = int_str[1:] + # "010" is not valid oct in py3 + if (int_str.startswith("0") and int_str != '0' + and not int_str.startswith("0x")): + int_str = "0o" + int_str[1:] + pyvalue = int(int_str, 0) + if neg: + pyvalue = -pyvalue + self._add_constants(name, pyvalue) + self._declare('macro ' + name, pyvalue) + + def _process_macros(self, macros): + for key, value in macros.items(): + value = value.strip() + if _r_int_literal.match(value): + self._add_integer_constant(key, value) + elif value == '...': + self._declare('macro ' + key, value) + else: + raise CDefError( + 'only supports one of the following syntax:\n' + ' #define %s ... (literally dot-dot-dot)\n' + ' #define %s NUMBER (with NUMBER an integer' + ' constant, decimal/hex/octal)\n' + 'got:\n' + ' #define %s %s' + % (key, key, key, value)) + + def _declare_function(self, tp, quals, decl): + tp = self._get_type_pointer(tp, quals) + if self._options.get('dllexport'): + tag = 'dllexport_python ' + elif self._inside_extern_python == '__cffi_extern_python_start': + tag = 'extern_python ' + elif self._inside_extern_python == '__cffi_extern_python_plus_c_start': + tag = 'extern_python_plus_c ' + else: + tag = 'function ' + self._declare(tag + decl.name, tp) + + def _parse_decl(self, decl): + node = decl.type + if isinstance(node, pycparser.c_ast.FuncDecl): + tp, quals = self._get_type_and_quals(node, name=decl.name) + assert isinstance(tp, model.RawFunctionType) + self._declare_function(tp, quals, decl) + else: + if isinstance(node, pycparser.c_ast.Struct): + self._get_struct_union_enum_type('struct', node) + elif isinstance(node, pycparser.c_ast.Union): + self._get_struct_union_enum_type('union', node) + elif isinstance(node, pycparser.c_ast.Enum): + self._get_struct_union_enum_type('enum', node) + elif not decl.name: + raise CDefError("construct does not declare any variable", + decl) + # + if decl.name: + tp, quals = self._get_type_and_quals(node, + partial_length_ok=True) + if tp.is_raw_function: + self._declare_function(tp, quals, decl) + elif (tp.is_integer_type() and + hasattr(decl, 'init') and + hasattr(decl.init, 'value') and + _r_int_literal.match(decl.init.value)): + self._add_integer_constant(decl.name, decl.init.value) + elif (tp.is_integer_type() and + isinstance(decl.init, pycparser.c_ast.UnaryOp) and + decl.init.op == '-' and + hasattr(decl.init.expr, 'value') and + _r_int_literal.match(decl.init.expr.value)): + self._add_integer_constant(decl.name, + '-' + decl.init.expr.value) + elif (tp is model.void_type and + decl.name.startswith('__cffi_extern_python_')): + # hack: `extern "Python"` in the C source is replaced + # with "void __cffi_extern_python_start;" and + # "void __cffi_extern_python_stop;" + self._inside_extern_python = decl.name + else: + if self._inside_extern_python !='__cffi_extern_python_stop': + raise CDefError( + "cannot declare constants or " + "variables with 'extern \"Python\"'") + if (quals & model.Q_CONST) and not tp.is_array_type: + self._declare('constant ' + decl.name, tp, quals=quals) + else: + _warn_for_non_extern_non_static_global_variable(decl) + self._declare('variable ' + decl.name, tp, quals=quals) + + def parse_type(self, cdecl): + return self.parse_type_and_quals(cdecl)[0] + + def parse_type_and_quals(self, cdecl): + ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2] + assert not macros + exprnode = ast.ext[-1].type.args.params[0] + if isinstance(exprnode, pycparser.c_ast.ID): + raise CDefError("unknown identifier '%s'" % (exprnode.name,)) + return self._get_type_and_quals(exprnode.type) + + def _declare(self, name, obj, included=False, quals=0): + if name in self._declarations: + prevobj, prevquals = self._declarations[name] + if prevobj is obj and prevquals == quals: + return + if not self._options.get('override'): + raise FFIError( + "multiple declarations of %s (for interactive usage, " + "try cdef(xx, override=True))" % (name,)) + assert '__dotdotdot__' not in name.split() + self._declarations[name] = (obj, quals) + if included: + self._included_declarations.add(obj) + + def _extract_quals(self, type): + quals = 0 + if isinstance(type, (pycparser.c_ast.TypeDecl, + pycparser.c_ast.PtrDecl)): + if 'const' in type.quals: + quals |= model.Q_CONST + if 'volatile' in type.quals: + quals |= model.Q_VOLATILE + if 'restrict' in type.quals: + quals |= model.Q_RESTRICT + return quals + + def _get_type_pointer(self, type, quals, declname=None): + if isinstance(type, model.RawFunctionType): + return type.as_function_pointer() + if (isinstance(type, model.StructOrUnionOrEnum) and + type.name.startswith('$') and type.name[1:].isdigit() and + type.forcename is None and declname is not None): + return model.NamedPointerType(type, declname, quals) + return model.PointerType(type, quals) + + def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False, + typedef_example=None): + # first, dereference typedefs, if we have it already parsed, we're good + if (isinstance(typenode, pycparser.c_ast.TypeDecl) and + isinstance(typenode.type, pycparser.c_ast.IdentifierType) and + len(typenode.type.names) == 1 and + ('typedef ' + typenode.type.names[0]) in self._declarations): + tp, quals = self._declarations['typedef ' + typenode.type.names[0]] + quals |= self._extract_quals(typenode) + return tp, quals + # + if isinstance(typenode, pycparser.c_ast.ArrayDecl): + # array type + if typenode.dim is None: + length = None + else: + length = self._parse_constant( + typenode.dim, partial_length_ok=partial_length_ok) + # a hack: in 'typedef int foo_t[...][...];', don't use '...' as + # the length but use directly the C expression that would be + # generated by recompiler.py. This lets the typedef be used in + # many more places within recompiler.py + if typedef_example is not None: + if length == '...': + length = '_cffi_array_len(%s)' % (typedef_example,) + typedef_example = "*" + typedef_example + # + tp, quals = self._get_type_and_quals(typenode.type, + partial_length_ok=partial_length_ok, + typedef_example=typedef_example) + return model.ArrayType(tp, length), quals + # + if isinstance(typenode, pycparser.c_ast.PtrDecl): + # pointer type + itemtype, itemquals = self._get_type_and_quals(typenode.type) + tp = self._get_type_pointer(itemtype, itemquals, declname=name) + quals = self._extract_quals(typenode) + return tp, quals + # + if isinstance(typenode, pycparser.c_ast.TypeDecl): + quals = self._extract_quals(typenode) + type = typenode.type + if isinstance(type, pycparser.c_ast.IdentifierType): + # assume a primitive type. get it from .names, but reduce + # synonyms to a single chosen combination + names = list(type.names) + if names != ['signed', 'char']: # keep this unmodified + prefixes = {} + while names: + name = names[0] + if name in ('short', 'long', 'signed', 'unsigned'): + prefixes[name] = prefixes.get(name, 0) + 1 + del names[0] + else: + break + # ignore the 'signed' prefix below, and reorder the others + newnames = [] + for prefix in ('unsigned', 'short', 'long'): + for i in range(prefixes.get(prefix, 0)): + newnames.append(prefix) + if not names: + names = ['int'] # implicitly + if names == ['int']: # but kill it if 'short' or 'long' + if 'short' in prefixes or 'long' in prefixes: + names = [] + names = newnames + names + ident = ' '.join(names) + if ident == 'void': + return model.void_type, quals + if ident == '__dotdotdot__': + raise FFIError(':%d: bad usage of "..."' % + typenode.coord.line) + tp0, quals0 = resolve_common_type(self, ident) + return tp0, (quals | quals0) + # + if isinstance(type, pycparser.c_ast.Struct): + # 'struct foobar' + tp = self._get_struct_union_enum_type('struct', type, name) + return tp, quals + # + if isinstance(type, pycparser.c_ast.Union): + # 'union foobar' + tp = self._get_struct_union_enum_type('union', type, name) + return tp, quals + # + if isinstance(type, pycparser.c_ast.Enum): + # 'enum foobar' + tp = self._get_struct_union_enum_type('enum', type, name) + return tp, quals + # + if isinstance(typenode, pycparser.c_ast.FuncDecl): + # a function type + return self._parse_function_type(typenode, name), 0 + # + # nested anonymous structs or unions end up here + if isinstance(typenode, pycparser.c_ast.Struct): + return self._get_struct_union_enum_type('struct', typenode, name, + nested=True), 0 + if isinstance(typenode, pycparser.c_ast.Union): + return self._get_struct_union_enum_type('union', typenode, name, + nested=True), 0 + # + raise FFIError(":%d: bad or unsupported type declaration" % + typenode.coord.line) + + def _parse_function_type(self, typenode, funcname=None): + params = list(getattr(typenode.args, 'params', [])) + for i, arg in enumerate(params): + if not hasattr(arg, 'type'): + raise CDefError("%s arg %d: unknown type '%s'" + " (if you meant to use the old C syntax of giving" + " untyped arguments, it is not supported)" + % (funcname or 'in expression', i + 1, + getattr(arg, 'name', '?'))) + ellipsis = ( + len(params) > 0 and + isinstance(params[-1].type, pycparser.c_ast.TypeDecl) and + isinstance(params[-1].type.type, + pycparser.c_ast.IdentifierType) and + params[-1].type.type.names == ['__dotdotdot__']) + if ellipsis: + params.pop() + if not params: + raise CDefError( + "%s: a function with only '(...)' as argument" + " is not correct C" % (funcname or 'in expression')) + args = [self._as_func_arg(*self._get_type_and_quals(argdeclnode.type)) + for argdeclnode in params] + if not ellipsis and args == [model.void_type]: + args = [] + result, quals = self._get_type_and_quals(typenode.type) + # the 'quals' on the result type are ignored. HACK: we absure them + # to detect __stdcall functions: we textually replace "__stdcall" + # with "volatile volatile const" above. + abi = None + if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway + if typenode.type.quals[-3:] == ['volatile', 'volatile', 'const']: + abi = '__stdcall' + return model.RawFunctionType(tuple(args), result, ellipsis, abi) + + def _as_func_arg(self, type, quals): + if isinstance(type, model.ArrayType): + return model.PointerType(type.item, quals) + elif isinstance(type, model.RawFunctionType): + return type.as_function_pointer() + else: + return type + + def _get_struct_union_enum_type(self, kind, type, name=None, nested=False): + # First, a level of caching on the exact 'type' node of the AST. + # This is obscure, but needed because pycparser "unrolls" declarations + # such as "typedef struct { } foo_t, *foo_p" and we end up with + # an AST that is not a tree, but a DAG, with the "type" node of the + # two branches foo_t and foo_p of the trees being the same node. + # It's a bit silly but detecting "DAG-ness" in the AST tree seems + # to be the only way to distinguish this case from two independent + # structs. See test_struct_with_two_usages. + try: + return self._structnode2type[type] + except KeyError: + pass + # + # Note that this must handle parsing "struct foo" any number of + # times and always return the same StructType object. Additionally, + # one of these times (not necessarily the first), the fields of + # the struct can be specified with "struct foo { ...fields... }". + # If no name is given, then we have to create a new anonymous struct + # with no caching; in this case, the fields are either specified + # right now or never. + # + force_name = name + name = type.name + # + # get the type or create it if needed + if name is None: + # 'force_name' is used to guess a more readable name for + # anonymous structs, for the common case "typedef struct { } foo". + if force_name is not None: + explicit_name = '$%s' % force_name + else: + self._anonymous_counter += 1 + explicit_name = '$%d' % self._anonymous_counter + tp = None + else: + explicit_name = name + key = '%s %s' % (kind, name) + tp, _ = self._declarations.get(key, (None, None)) + # + if tp is None: + if kind == 'struct': + tp = model.StructType(explicit_name, None, None, None) + elif kind == 'union': + tp = model.UnionType(explicit_name, None, None, None) + elif kind == 'enum': + if explicit_name == '__dotdotdot__': + raise CDefError("Enums cannot be declared with ...") + tp = self._build_enum_type(explicit_name, type.values) + else: + raise AssertionError("kind = %r" % (kind,)) + if name is not None: + self._declare(key, tp) + else: + if kind == 'enum' and type.values is not None: + raise NotImplementedError( + "enum %s: the '{}' declaration should appear on the first " + "time the enum is mentioned, not later" % explicit_name) + if not tp.forcename: + tp.force_the_name(force_name) + if tp.forcename and '$' in tp.name: + self._declare('anonymous %s' % tp.forcename, tp) + # + self._structnode2type[type] = tp + # + # enums: done here + if kind == 'enum': + return tp + # + # is there a 'type.decls'? If yes, then this is the place in the + # C sources that declare the fields. If no, then just return the + # existing type, possibly still incomplete. + if type.decls is None: + return tp + # + if tp.fldnames is not None: + raise CDefError("duplicate declaration of struct %s" % name) + fldnames = [] + fldtypes = [] + fldbitsize = [] + fldquals = [] + for decl in type.decls: + if (isinstance(decl.type, pycparser.c_ast.IdentifierType) and + ''.join(decl.type.names) == '__dotdotdot__'): + # XXX pycparser is inconsistent: 'names' should be a list + # of strings, but is sometimes just one string. Use + # str.join() as a way to cope with both. + self._make_partial(tp, nested) + continue + if decl.bitsize is None: + bitsize = -1 + else: + bitsize = self._parse_constant(decl.bitsize) + self._partial_length = False + type, fqual = self._get_type_and_quals(decl.type, + partial_length_ok=True) + if self._partial_length: + self._make_partial(tp, nested) + if isinstance(type, model.StructType) and type.partial: + self._make_partial(tp, nested) + fldnames.append(decl.name or '') + fldtypes.append(type) + fldbitsize.append(bitsize) + fldquals.append(fqual) + tp.fldnames = tuple(fldnames) + tp.fldtypes = tuple(fldtypes) + tp.fldbitsize = tuple(fldbitsize) + tp.fldquals = tuple(fldquals) + if fldbitsize != [-1] * len(fldbitsize): + if isinstance(tp, model.StructType) and tp.partial: + raise NotImplementedError("%s: using both bitfields and '...;'" + % (tp,)) + tp.packed = self._options.get('packed') + if tp.completed: # must be re-completed: it is not opaque any more + tp.completed = 0 + self._recomplete.append(tp) + return tp + + def _make_partial(self, tp, nested): + if not isinstance(tp, model.StructOrUnion): + raise CDefError("%s cannot be partial" % (tp,)) + if not tp.has_c_name() and not nested: + raise NotImplementedError("%s is partial but has no C name" %(tp,)) + tp.partial = True + + def _parse_constant(self, exprnode, partial_length_ok=False): + # for now, limited to expressions that are an immediate number + # or positive/negative number + if isinstance(exprnode, pycparser.c_ast.Constant): + s = exprnode.value + if '0' <= s[0] <= '9': + s = s.rstrip('uUlL') + try: + if s.startswith('0'): + return int(s, 8) + else: + return int(s, 10) + except ValueError: + if len(s) > 1: + if s.lower()[0:2] == '0x': + return int(s, 16) + elif s.lower()[0:2] == '0b': + return int(s, 2) + raise CDefError("invalid constant %r" % (s,)) + elif s[0] == "'" and s[-1] == "'" and ( + len(s) == 3 or (len(s) == 4 and s[1] == "\\")): + return ord(s[-2]) + else: + raise CDefError("invalid constant %r" % (s,)) + # + if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and + exprnode.op == '+'): + return self._parse_constant(exprnode.expr) + # + if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and + exprnode.op == '-'): + return -self._parse_constant(exprnode.expr) + # load previously defined int constant + if (isinstance(exprnode, pycparser.c_ast.ID) and + exprnode.name in self._int_constants): + return self._int_constants[exprnode.name] + # + if (isinstance(exprnode, pycparser.c_ast.ID) and + exprnode.name == '__dotdotdotarray__'): + if partial_length_ok: + self._partial_length = True + return '...' + raise FFIError(":%d: unsupported '[...]' here, cannot derive " + "the actual array length in this context" + % exprnode.coord.line) + # + if isinstance(exprnode, pycparser.c_ast.BinaryOp): + left = self._parse_constant(exprnode.left) + right = self._parse_constant(exprnode.right) + if exprnode.op == '+': + return left + right + elif exprnode.op == '-': + return left - right + elif exprnode.op == '*': + return left * right + elif exprnode.op == '/': + return self._c_div(left, right) + elif exprnode.op == '%': + return left - self._c_div(left, right) * right + elif exprnode.op == '<<': + return left << right + elif exprnode.op == '>>': + return left >> right + elif exprnode.op == '&': + return left & right + elif exprnode.op == '|': + return left | right + elif exprnode.op == '^': + return left ^ right + # + raise FFIError(":%d: unsupported expression: expected a " + "simple numeric constant" % exprnode.coord.line) + + def _c_div(self, a, b): + result = a // b + if ((a < 0) ^ (b < 0)) and (a % b) != 0: + result += 1 + return result + + def _build_enum_type(self, explicit_name, decls): + if decls is not None: + partial = False + enumerators = [] + enumvalues = [] + nextenumvalue = 0 + for enum in decls.enumerators: + if _r_enum_dotdotdot.match(enum.name): + partial = True + continue + if enum.value is not None: + nextenumvalue = self._parse_constant(enum.value) + enumerators.append(enum.name) + enumvalues.append(nextenumvalue) + self._add_constants(enum.name, nextenumvalue) + nextenumvalue += 1 + enumerators = tuple(enumerators) + enumvalues = tuple(enumvalues) + tp = model.EnumType(explicit_name, enumerators, enumvalues) + tp.partial = partial + else: # opaque enum + tp = model.EnumType(explicit_name, (), ()) + return tp + + def include(self, other): + for name, (tp, quals) in other._declarations.items(): + if name.startswith('anonymous $enum_$'): + continue # fix for test_anonymous_enum_include + kind = name.split(' ', 1)[0] + if kind in ('struct', 'union', 'enum', 'anonymous', 'typedef'): + self._declare(name, tp, included=True, quals=quals) + for k, v in other._int_constants.items(): + self._add_constants(k, v) + + def _get_unknown_type(self, decl): + typenames = decl.type.type.names + if typenames == ['__dotdotdot__']: + return model.unknown_type(decl.name) + + if typenames == ['__dotdotdotint__']: + if self._uses_new_feature is None: + self._uses_new_feature = "'typedef int... %s'" % decl.name + return model.UnknownIntegerType(decl.name) + + if typenames == ['__dotdotdotfloat__']: + # note: not for 'long double' so far + if self._uses_new_feature is None: + self._uses_new_feature = "'typedef float... %s'" % decl.name + return model.UnknownFloatType(decl.name) + + raise FFIError(':%d: unsupported usage of "..." in typedef' + % decl.coord.line) + + def _get_unknown_ptr_type(self, decl): + if decl.type.type.type.names == ['__dotdotdot__']: + return model.unknown_ptr_type(decl.name) + raise FFIError(':%d: unsupported usage of "..." in typedef' + % decl.coord.line) diff --git a/miniconda3/lib/python3.13/site-packages/cffi/error.py b/miniconda3/lib/python3.13/site-packages/cffi/error.py new file mode 100644 index 0000000000000000000000000000000000000000..0a27247c32a381ab7cecedd0f985b781619c1ea5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/error.py @@ -0,0 +1,31 @@ + +class FFIError(Exception): + __module__ = 'cffi' + +class CDefError(Exception): + __module__ = 'cffi' + def __str__(self): + try: + current_decl = self.args[1] + filename = current_decl.coord.file + linenum = current_decl.coord.line + prefix = '%s:%d: ' % (filename, linenum) + except (AttributeError, TypeError, IndexError): + prefix = '' + return '%s%s' % (prefix, self.args[0]) + +class VerificationError(Exception): + """ An error raised when verification fails + """ + __module__ = 'cffi' + +class VerificationMissing(Exception): + """ An error raised when incomplete structures are passed into + cdef, but no verification has been done + """ + __module__ = 'cffi' + +class PkgConfigError(Exception): + """ An error raised for missing modules in pkg-config + """ + __module__ = 'cffi' diff --git a/miniconda3/lib/python3.13/site-packages/cffi/ffiplatform.py b/miniconda3/lib/python3.13/site-packages/cffi/ffiplatform.py new file mode 100644 index 0000000000000000000000000000000000000000..adca28f1a480bb04a11977d26457fe8886139043 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/ffiplatform.py @@ -0,0 +1,113 @@ +import sys, os +from .error import VerificationError + + +LIST_OF_FILE_NAMES = ['sources', 'include_dirs', 'library_dirs', + 'extra_objects', 'depends'] + +def get_extension(srcfilename, modname, sources=(), **kwds): + from cffi._shimmed_dist_utils import Extension + allsources = [srcfilename] + for src in sources: + allsources.append(os.path.normpath(src)) + return Extension(name=modname, sources=allsources, **kwds) + +def compile(tmpdir, ext, compiler_verbose=0, debug=None): + """Compile a C extension module using distutils.""" + + saved_environ = os.environ.copy() + try: + outputfilename = _build(tmpdir, ext, compiler_verbose, debug) + outputfilename = os.path.abspath(outputfilename) + finally: + # workaround for a distutils bugs where some env vars can + # become longer and longer every time it is used + for key, value in saved_environ.items(): + if os.environ.get(key) != value: + os.environ[key] = value + return outputfilename + +def _build(tmpdir, ext, compiler_verbose=0, debug=None): + # XXX compact but horrible :-( + from cffi._shimmed_dist_utils import Distribution, CompileError, LinkError, set_threshold, set_verbosity + + dist = Distribution({'ext_modules': [ext]}) + dist.parse_config_files() + options = dist.get_option_dict('build_ext') + if debug is None: + debug = sys.flags.debug + options['debug'] = ('ffiplatform', debug) + options['force'] = ('ffiplatform', True) + options['build_lib'] = ('ffiplatform', tmpdir) + options['build_temp'] = ('ffiplatform', tmpdir) + # + try: + old_level = set_threshold(0) or 0 + try: + set_verbosity(compiler_verbose) + dist.run_command('build_ext') + cmd_obj = dist.get_command_obj('build_ext') + [soname] = cmd_obj.get_outputs() + finally: + set_threshold(old_level) + except (CompileError, LinkError) as e: + raise VerificationError('%s: %s' % (e.__class__.__name__, e)) + # + return soname + +try: + from os.path import samefile +except ImportError: + def samefile(f1, f2): + return os.path.abspath(f1) == os.path.abspath(f2) + +def maybe_relative_path(path): + if not os.path.isabs(path): + return path # already relative + dir = path + names = [] + while True: + prevdir = dir + dir, name = os.path.split(prevdir) + if dir == prevdir or not dir: + return path # failed to make it relative + names.append(name) + try: + if samefile(dir, os.curdir): + names.reverse() + return os.path.join(*names) + except OSError: + pass + +# ____________________________________________________________ + +try: + int_or_long = (int, long) + import cStringIO +except NameError: + int_or_long = int # Python 3 + import io as cStringIO + +def _flatten(x, f): + if isinstance(x, str): + f.write('%ds%s' % (len(x), x)) + elif isinstance(x, dict): + keys = sorted(x.keys()) + f.write('%dd' % len(keys)) + for key in keys: + _flatten(key, f) + _flatten(x[key], f) + elif isinstance(x, (list, tuple)): + f.write('%dl' % len(x)) + for value in x: + _flatten(value, f) + elif isinstance(x, int_or_long): + f.write('%di' % (x,)) + else: + raise TypeError( + "the keywords to verify() contains unsupported object %r" % (x,)) + +def flatten(x): + f = cStringIO.StringIO() + _flatten(x, f) + return f.getvalue() diff --git a/miniconda3/lib/python3.13/site-packages/cffi/lock.py b/miniconda3/lib/python3.13/site-packages/cffi/lock.py new file mode 100644 index 0000000000000000000000000000000000000000..db91b7158c4ee9aa653462fe38e79ed1b553db87 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/lock.py @@ -0,0 +1,30 @@ +import sys + +if sys.version_info < (3,): + try: + from thread import allocate_lock + except ImportError: + from dummy_thread import allocate_lock +else: + try: + from _thread import allocate_lock + except ImportError: + from _dummy_thread import allocate_lock + + +##import sys +##l1 = allocate_lock + +##class allocate_lock(object): +## def __init__(self): +## self._real = l1() +## def __enter__(self): +## for i in range(4, 0, -1): +## print sys._getframe(i).f_code +## print +## return self._real.__enter__() +## def __exit__(self, *args): +## return self._real.__exit__(*args) +## def acquire(self, f): +## assert f is False +## return self._real.acquire(f) diff --git a/miniconda3/lib/python3.13/site-packages/cffi/model.py b/miniconda3/lib/python3.13/site-packages/cffi/model.py new file mode 100644 index 0000000000000000000000000000000000000000..e5f4cae3e84c73cd09980dabd2ec571d455fe0c1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/model.py @@ -0,0 +1,618 @@ +import types +import weakref + +from .lock import allocate_lock +from .error import CDefError, VerificationError, VerificationMissing + +# type qualifiers +Q_CONST = 0x01 +Q_RESTRICT = 0x02 +Q_VOLATILE = 0x04 + +def qualify(quals, replace_with): + if quals & Q_CONST: + replace_with = ' const ' + replace_with.lstrip() + if quals & Q_VOLATILE: + replace_with = ' volatile ' + replace_with.lstrip() + if quals & Q_RESTRICT: + # It seems that __restrict is supported by gcc and msvc. + # If you hit some different compiler, add a #define in + # _cffi_include.h for it (and in its copies, documented there) + replace_with = ' __restrict ' + replace_with.lstrip() + return replace_with + + +class BaseTypeByIdentity(object): + is_array_type = False + is_raw_function = False + + def get_c_name(self, replace_with='', context='a C file', quals=0): + result = self.c_name_with_marker + assert result.count('&') == 1 + # some logic duplication with ffi.getctype()... :-( + replace_with = replace_with.strip() + if replace_with: + if replace_with.startswith('*') and '&[' in result: + replace_with = '(%s)' % replace_with + elif not replace_with[0] in '[(': + replace_with = ' ' + replace_with + replace_with = qualify(quals, replace_with) + result = result.replace('&', replace_with) + if '$' in result: + raise VerificationError( + "cannot generate '%s' in %s: unknown type name" + % (self._get_c_name(), context)) + return result + + def _get_c_name(self): + return self.c_name_with_marker.replace('&', '') + + def has_c_name(self): + return '$' not in self._get_c_name() + + def is_integer_type(self): + return False + + def get_cached_btype(self, ffi, finishlist, can_delay=False): + try: + BType = ffi._cached_btypes[self] + except KeyError: + BType = self.build_backend_type(ffi, finishlist) + BType2 = ffi._cached_btypes.setdefault(self, BType) + assert BType2 is BType + return BType + + def __repr__(self): + return '<%s>' % (self._get_c_name(),) + + def _get_items(self): + return [(name, getattr(self, name)) for name in self._attrs_] + + +class BaseType(BaseTypeByIdentity): + + def __eq__(self, other): + return (self.__class__ == other.__class__ and + self._get_items() == other._get_items()) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((self.__class__, tuple(self._get_items()))) + + +class VoidType(BaseType): + _attrs_ = () + + def __init__(self): + self.c_name_with_marker = 'void&' + + def build_backend_type(self, ffi, finishlist): + return global_cache(self, ffi, 'new_void_type') + +void_type = VoidType() + + +class BasePrimitiveType(BaseType): + def is_complex_type(self): + return False + + +class PrimitiveType(BasePrimitiveType): + _attrs_ = ('name',) + + ALL_PRIMITIVE_TYPES = { + 'char': 'c', + 'short': 'i', + 'int': 'i', + 'long': 'i', + 'long long': 'i', + 'signed char': 'i', + 'unsigned char': 'i', + 'unsigned short': 'i', + 'unsigned int': 'i', + 'unsigned long': 'i', + 'unsigned long long': 'i', + 'float': 'f', + 'double': 'f', + 'long double': 'f', + '_cffi_float_complex_t': 'j', + '_cffi_double_complex_t': 'j', + '_Bool': 'i', + # the following types are not primitive in the C sense + 'wchar_t': 'c', + 'char16_t': 'c', + 'char32_t': 'c', + 'int8_t': 'i', + 'uint8_t': 'i', + 'int16_t': 'i', + 'uint16_t': 'i', + 'int32_t': 'i', + 'uint32_t': 'i', + 'int64_t': 'i', + 'uint64_t': 'i', + 'int_least8_t': 'i', + 'uint_least8_t': 'i', + 'int_least16_t': 'i', + 'uint_least16_t': 'i', + 'int_least32_t': 'i', + 'uint_least32_t': 'i', + 'int_least64_t': 'i', + 'uint_least64_t': 'i', + 'int_fast8_t': 'i', + 'uint_fast8_t': 'i', + 'int_fast16_t': 'i', + 'uint_fast16_t': 'i', + 'int_fast32_t': 'i', + 'uint_fast32_t': 'i', + 'int_fast64_t': 'i', + 'uint_fast64_t': 'i', + 'intptr_t': 'i', + 'uintptr_t': 'i', + 'intmax_t': 'i', + 'uintmax_t': 'i', + 'ptrdiff_t': 'i', + 'size_t': 'i', + 'ssize_t': 'i', + } + + def __init__(self, name): + assert name in self.ALL_PRIMITIVE_TYPES + self.name = name + self.c_name_with_marker = name + '&' + + def is_char_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'c' + def is_integer_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'i' + def is_float_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'f' + def is_complex_type(self): + return self.ALL_PRIMITIVE_TYPES[self.name] == 'j' + + def build_backend_type(self, ffi, finishlist): + return global_cache(self, ffi, 'new_primitive_type', self.name) + + +class UnknownIntegerType(BasePrimitiveType): + _attrs_ = ('name',) + + def __init__(self, name): + self.name = name + self.c_name_with_marker = name + '&' + + def is_integer_type(self): + return True + + def build_backend_type(self, ffi, finishlist): + raise NotImplementedError("integer type '%s' can only be used after " + "compilation" % self.name) + +class UnknownFloatType(BasePrimitiveType): + _attrs_ = ('name', ) + + def __init__(self, name): + self.name = name + self.c_name_with_marker = name + '&' + + def build_backend_type(self, ffi, finishlist): + raise NotImplementedError("float type '%s' can only be used after " + "compilation" % self.name) + + +class BaseFunctionType(BaseType): + _attrs_ = ('args', 'result', 'ellipsis', 'abi') + + def __init__(self, args, result, ellipsis, abi=None): + self.args = args + self.result = result + self.ellipsis = ellipsis + self.abi = abi + # + reprargs = [arg._get_c_name() for arg in self.args] + if self.ellipsis: + reprargs.append('...') + reprargs = reprargs or ['void'] + replace_with = self._base_pattern % (', '.join(reprargs),) + if abi is not None: + replace_with = replace_with[:1] + abi + ' ' + replace_with[1:] + self.c_name_with_marker = ( + self.result.c_name_with_marker.replace('&', replace_with)) + + +class RawFunctionType(BaseFunctionType): + # Corresponds to a C type like 'int(int)', which is the C type of + # a function, but not a pointer-to-function. The backend has no + # notion of such a type; it's used temporarily by parsing. + _base_pattern = '(&)(%s)' + is_raw_function = True + + def build_backend_type(self, ffi, finishlist): + raise CDefError("cannot render the type %r: it is a function " + "type, not a pointer-to-function type" % (self,)) + + def as_function_pointer(self): + return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi) + + +class FunctionPtrType(BaseFunctionType): + _base_pattern = '(*&)(%s)' + + def build_backend_type(self, ffi, finishlist): + result = self.result.get_cached_btype(ffi, finishlist) + args = [] + for tp in self.args: + args.append(tp.get_cached_btype(ffi, finishlist)) + abi_args = () + if self.abi == "__stdcall": + if not self.ellipsis: # __stdcall ignored for variadic funcs + try: + abi_args = (ffi._backend.FFI_STDCALL,) + except AttributeError: + pass + return global_cache(self, ffi, 'new_function_type', + tuple(args), result, self.ellipsis, *abi_args) + + def as_raw_function(self): + return RawFunctionType(self.args, self.result, self.ellipsis, self.abi) + + +class PointerType(BaseType): + _attrs_ = ('totype', 'quals') + + def __init__(self, totype, quals=0): + self.totype = totype + self.quals = quals + extra = " *&" + if totype.is_array_type: + extra = "(%s)" % (extra.lstrip(),) + extra = qualify(quals, extra) + self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra) + + def build_backend_type(self, ffi, finishlist): + BItem = self.totype.get_cached_btype(ffi, finishlist, can_delay=True) + return global_cache(self, ffi, 'new_pointer_type', BItem) + +voidp_type = PointerType(void_type) + +def ConstPointerType(totype): + return PointerType(totype, Q_CONST) + +const_voidp_type = ConstPointerType(void_type) + + +class NamedPointerType(PointerType): + _attrs_ = ('totype', 'name') + + def __init__(self, totype, name, quals=0): + PointerType.__init__(self, totype, quals) + self.name = name + self.c_name_with_marker = name + '&' + + +class ArrayType(BaseType): + _attrs_ = ('item', 'length') + is_array_type = True + + def __init__(self, item, length): + self.item = item + self.length = length + # + if length is None: + brackets = '&[]' + elif length == '...': + brackets = '&[/*...*/]' + else: + brackets = '&[%s]' % length + self.c_name_with_marker = ( + self.item.c_name_with_marker.replace('&', brackets)) + + def length_is_unknown(self): + return isinstance(self.length, str) + + def resolve_length(self, newlength): + return ArrayType(self.item, newlength) + + def build_backend_type(self, ffi, finishlist): + if self.length_is_unknown(): + raise CDefError("cannot render the type %r: unknown length" % + (self,)) + self.item.get_cached_btype(ffi, finishlist) # force the item BType + BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist) + return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length) + +char_array_type = ArrayType(PrimitiveType('char'), None) + + +class StructOrUnionOrEnum(BaseTypeByIdentity): + _attrs_ = ('name',) + forcename = None + + def build_c_name_with_marker(self): + name = self.forcename or '%s %s' % (self.kind, self.name) + self.c_name_with_marker = name + '&' + + def force_the_name(self, forcename): + self.forcename = forcename + self.build_c_name_with_marker() + + def get_official_name(self): + assert self.c_name_with_marker.endswith('&') + return self.c_name_with_marker[:-1] + + +class StructOrUnion(StructOrUnionOrEnum): + fixedlayout = None + completed = 0 + partial = False + packed = 0 + + def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None): + self.name = name + self.fldnames = fldnames + self.fldtypes = fldtypes + self.fldbitsize = fldbitsize + self.fldquals = fldquals + self.build_c_name_with_marker() + + def anonymous_struct_fields(self): + if self.fldtypes is not None: + for name, type in zip(self.fldnames, self.fldtypes): + if name == '' and isinstance(type, StructOrUnion): + yield type + + def enumfields(self, expand_anonymous_struct_union=True): + fldquals = self.fldquals + if fldquals is None: + fldquals = (0,) * len(self.fldnames) + for name, type, bitsize, quals in zip(self.fldnames, self.fldtypes, + self.fldbitsize, fldquals): + if (name == '' and isinstance(type, StructOrUnion) + and expand_anonymous_struct_union): + # nested anonymous struct/union + for result in type.enumfields(): + yield result + else: + yield (name, type, bitsize, quals) + + def force_flatten(self): + # force the struct or union to have a declaration that lists + # directly all fields returned by enumfields(), flattening + # nested anonymous structs/unions. + names = [] + types = [] + bitsizes = [] + fldquals = [] + for name, type, bitsize, quals in self.enumfields(): + names.append(name) + types.append(type) + bitsizes.append(bitsize) + fldquals.append(quals) + self.fldnames = tuple(names) + self.fldtypes = tuple(types) + self.fldbitsize = tuple(bitsizes) + self.fldquals = tuple(fldquals) + + def get_cached_btype(self, ffi, finishlist, can_delay=False): + BType = StructOrUnionOrEnum.get_cached_btype(self, ffi, finishlist, + can_delay) + if not can_delay: + self.finish_backend_type(ffi, finishlist) + return BType + + def finish_backend_type(self, ffi, finishlist): + if self.completed: + if self.completed != 2: + raise NotImplementedError("recursive structure declaration " + "for '%s'" % (self.name,)) + return + BType = ffi._cached_btypes[self] + # + self.completed = 1 + # + if self.fldtypes is None: + pass # not completing it: it's an opaque struct + # + elif self.fixedlayout is None: + fldtypes = [tp.get_cached_btype(ffi, finishlist) + for tp in self.fldtypes] + lst = list(zip(self.fldnames, fldtypes, self.fldbitsize)) + extra_flags = () + if self.packed: + if self.packed == 1: + extra_flags = (8,) # SF_PACKED + else: + extra_flags = (0, self.packed) + ffi._backend.complete_struct_or_union(BType, lst, self, + -1, -1, *extra_flags) + # + else: + fldtypes = [] + fieldofs, fieldsize, totalsize, totalalignment = self.fixedlayout + for i in range(len(self.fldnames)): + fsize = fieldsize[i] + ftype = self.fldtypes[i] + # + if isinstance(ftype, ArrayType) and ftype.length_is_unknown(): + # fix the length to match the total size + BItemType = ftype.item.get_cached_btype(ffi, finishlist) + nlen, nrest = divmod(fsize, ffi.sizeof(BItemType)) + if nrest != 0: + self._verification_error( + "field '%s.%s' has a bogus size?" % ( + self.name, self.fldnames[i] or '{}')) + ftype = ftype.resolve_length(nlen) + self.fldtypes = (self.fldtypes[:i] + (ftype,) + + self.fldtypes[i+1:]) + # + BFieldType = ftype.get_cached_btype(ffi, finishlist) + if isinstance(ftype, ArrayType) and ftype.length is None: + assert fsize == 0 + else: + bitemsize = ffi.sizeof(BFieldType) + if bitemsize != fsize: + self._verification_error( + "field '%s.%s' is declared as %d bytes, but is " + "really %d bytes" % (self.name, + self.fldnames[i] or '{}', + bitemsize, fsize)) + fldtypes.append(BFieldType) + # + lst = list(zip(self.fldnames, fldtypes, self.fldbitsize, fieldofs)) + ffi._backend.complete_struct_or_union(BType, lst, self, + totalsize, totalalignment) + self.completed = 2 + + def _verification_error(self, msg): + raise VerificationError(msg) + + def check_not_partial(self): + if self.partial and self.fixedlayout is None: + raise VerificationMissing(self._get_c_name()) + + def build_backend_type(self, ffi, finishlist): + self.check_not_partial() + finishlist.append(self) + # + return global_cache(self, ffi, 'new_%s_type' % self.kind, + self.get_official_name(), key=self) + + +class StructType(StructOrUnion): + kind = 'struct' + + +class UnionType(StructOrUnion): + kind = 'union' + + +class EnumType(StructOrUnionOrEnum): + kind = 'enum' + partial = False + partial_resolved = False + + def __init__(self, name, enumerators, enumvalues, baseinttype=None): + self.name = name + self.enumerators = enumerators + self.enumvalues = enumvalues + self.baseinttype = baseinttype + self.build_c_name_with_marker() + + def force_the_name(self, forcename): + StructOrUnionOrEnum.force_the_name(self, forcename) + if self.forcename is None: + name = self.get_official_name() + self.forcename = '$' + name.replace(' ', '_') + + def check_not_partial(self): + if self.partial and not self.partial_resolved: + raise VerificationMissing(self._get_c_name()) + + def build_backend_type(self, ffi, finishlist): + self.check_not_partial() + base_btype = self.build_baseinttype(ffi, finishlist) + return global_cache(self, ffi, 'new_enum_type', + self.get_official_name(), + self.enumerators, self.enumvalues, + base_btype, key=self) + + def build_baseinttype(self, ffi, finishlist): + if self.baseinttype is not None: + return self.baseinttype.get_cached_btype(ffi, finishlist) + # + if self.enumvalues: + smallest_value = min(self.enumvalues) + largest_value = max(self.enumvalues) + else: + import warnings + try: + # XXX! The goal is to ensure that the warnings.warn() + # will not suppress the warning. We want to get it + # several times if we reach this point several times. + __warningregistry__.clear() + except NameError: + pass + warnings.warn("%r has no values explicitly defined; " + "guessing that it is equivalent to 'unsigned int'" + % self._get_c_name()) + smallest_value = largest_value = 0 + if smallest_value < 0: # needs a signed type + sign = 1 + candidate1 = PrimitiveType("int") + candidate2 = PrimitiveType("long") + else: + sign = 0 + candidate1 = PrimitiveType("unsigned int") + candidate2 = PrimitiveType("unsigned long") + btype1 = candidate1.get_cached_btype(ffi, finishlist) + btype2 = candidate2.get_cached_btype(ffi, finishlist) + size1 = ffi.sizeof(btype1) + size2 = ffi.sizeof(btype2) + if (smallest_value >= ((-1) << (8*size1-1)) and + largest_value < (1 << (8*size1-sign))): + return btype1 + if (smallest_value >= ((-1) << (8*size2-1)) and + largest_value < (1 << (8*size2-sign))): + return btype2 + raise CDefError("%s values don't all fit into either 'long' " + "or 'unsigned long'" % self._get_c_name()) + +def unknown_type(name, structname=None): + if structname is None: + structname = '$%s' % name + tp = StructType(structname, None, None, None) + tp.force_the_name(name) + tp.origin = "unknown_type" + return tp + +def unknown_ptr_type(name, structname=None): + if structname is None: + structname = '$$%s' % name + tp = StructType(structname, None, None, None) + return NamedPointerType(tp, name) + + +global_lock = allocate_lock() +_typecache_cffi_backend = weakref.WeakValueDictionary() + +def get_typecache(backend): + # returns _typecache_cffi_backend if backend is the _cffi_backend + # module, or type(backend).__typecache if backend is an instance of + # CTypesBackend (or some FakeBackend class during tests) + if isinstance(backend, types.ModuleType): + return _typecache_cffi_backend + with global_lock: + if not hasattr(type(backend), '__typecache'): + type(backend).__typecache = weakref.WeakValueDictionary() + return type(backend).__typecache + +def global_cache(srctype, ffi, funcname, *args, **kwds): + key = kwds.pop('key', (funcname, args)) + assert not kwds + try: + return ffi._typecache[key] + except KeyError: + pass + try: + res = getattr(ffi._backend, funcname)(*args) + except NotImplementedError as e: + raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e)) + # note that setdefault() on WeakValueDictionary is not atomic + # and contains a rare bug (http://bugs.python.org/issue19542); + # we have to use a lock and do it ourselves + cache = ffi._typecache + with global_lock: + res1 = cache.get(key) + if res1 is None: + cache[key] = res + return res + else: + return res1 + +def pointer_cache(ffi, BType): + return global_cache('?', ffi, 'new_pointer_type', BType) + +def attach_exception_info(e, name): + if e.args and type(e.args[0]) is str: + e.args = ('%s: %s' % (name, e.args[0]),) + e.args[1:] diff --git a/miniconda3/lib/python3.13/site-packages/cffi/parse_c_type.h b/miniconda3/lib/python3.13/site-packages/cffi/parse_c_type.h new file mode 100644 index 0000000000000000000000000000000000000000..84e4ef85659eb63e6453d8af9f024f1866182342 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/parse_c_type.h @@ -0,0 +1,181 @@ + +/* This part is from file 'cffi/parse_c_type.h'. It is copied at the + beginning of C sources generated by CFFI's ffi.set_source(). */ + +typedef void *_cffi_opcode_t; + +#define _CFFI_OP(opcode, arg) (_cffi_opcode_t)(opcode | (((uintptr_t)(arg)) << 8)) +#define _CFFI_GETOP(cffi_opcode) ((unsigned char)(uintptr_t)cffi_opcode) +#define _CFFI_GETARG(cffi_opcode) (((intptr_t)cffi_opcode) >> 8) + +#define _CFFI_OP_PRIMITIVE 1 +#define _CFFI_OP_POINTER 3 +#define _CFFI_OP_ARRAY 5 +#define _CFFI_OP_OPEN_ARRAY 7 +#define _CFFI_OP_STRUCT_UNION 9 +#define _CFFI_OP_ENUM 11 +#define _CFFI_OP_FUNCTION 13 +#define _CFFI_OP_FUNCTION_END 15 +#define _CFFI_OP_NOOP 17 +#define _CFFI_OP_BITFIELD 19 +#define _CFFI_OP_TYPENAME 21 +#define _CFFI_OP_CPYTHON_BLTN_V 23 // varargs +#define _CFFI_OP_CPYTHON_BLTN_N 25 // noargs +#define _CFFI_OP_CPYTHON_BLTN_O 27 // O (i.e. a single arg) +#define _CFFI_OP_CONSTANT 29 +#define _CFFI_OP_CONSTANT_INT 31 +#define _CFFI_OP_GLOBAL_VAR 33 +#define _CFFI_OP_DLOPEN_FUNC 35 +#define _CFFI_OP_DLOPEN_CONST 37 +#define _CFFI_OP_GLOBAL_VAR_F 39 +#define _CFFI_OP_EXTERN_PYTHON 41 + +#define _CFFI_PRIM_VOID 0 +#define _CFFI_PRIM_BOOL 1 +#define _CFFI_PRIM_CHAR 2 +#define _CFFI_PRIM_SCHAR 3 +#define _CFFI_PRIM_UCHAR 4 +#define _CFFI_PRIM_SHORT 5 +#define _CFFI_PRIM_USHORT 6 +#define _CFFI_PRIM_INT 7 +#define _CFFI_PRIM_UINT 8 +#define _CFFI_PRIM_LONG 9 +#define _CFFI_PRIM_ULONG 10 +#define _CFFI_PRIM_LONGLONG 11 +#define _CFFI_PRIM_ULONGLONG 12 +#define _CFFI_PRIM_FLOAT 13 +#define _CFFI_PRIM_DOUBLE 14 +#define _CFFI_PRIM_LONGDOUBLE 15 + +#define _CFFI_PRIM_WCHAR 16 +#define _CFFI_PRIM_INT8 17 +#define _CFFI_PRIM_UINT8 18 +#define _CFFI_PRIM_INT16 19 +#define _CFFI_PRIM_UINT16 20 +#define _CFFI_PRIM_INT32 21 +#define _CFFI_PRIM_UINT32 22 +#define _CFFI_PRIM_INT64 23 +#define _CFFI_PRIM_UINT64 24 +#define _CFFI_PRIM_INTPTR 25 +#define _CFFI_PRIM_UINTPTR 26 +#define _CFFI_PRIM_PTRDIFF 27 +#define _CFFI_PRIM_SIZE 28 +#define _CFFI_PRIM_SSIZE 29 +#define _CFFI_PRIM_INT_LEAST8 30 +#define _CFFI_PRIM_UINT_LEAST8 31 +#define _CFFI_PRIM_INT_LEAST16 32 +#define _CFFI_PRIM_UINT_LEAST16 33 +#define _CFFI_PRIM_INT_LEAST32 34 +#define _CFFI_PRIM_UINT_LEAST32 35 +#define _CFFI_PRIM_INT_LEAST64 36 +#define _CFFI_PRIM_UINT_LEAST64 37 +#define _CFFI_PRIM_INT_FAST8 38 +#define _CFFI_PRIM_UINT_FAST8 39 +#define _CFFI_PRIM_INT_FAST16 40 +#define _CFFI_PRIM_UINT_FAST16 41 +#define _CFFI_PRIM_INT_FAST32 42 +#define _CFFI_PRIM_UINT_FAST32 43 +#define _CFFI_PRIM_INT_FAST64 44 +#define _CFFI_PRIM_UINT_FAST64 45 +#define _CFFI_PRIM_INTMAX 46 +#define _CFFI_PRIM_UINTMAX 47 +#define _CFFI_PRIM_FLOATCOMPLEX 48 +#define _CFFI_PRIM_DOUBLECOMPLEX 49 +#define _CFFI_PRIM_CHAR16 50 +#define _CFFI_PRIM_CHAR32 51 + +#define _CFFI__NUM_PRIM 52 +#define _CFFI__UNKNOWN_PRIM (-1) +#define _CFFI__UNKNOWN_FLOAT_PRIM (-2) +#define _CFFI__UNKNOWN_LONG_DOUBLE (-3) + +#define _CFFI__IO_FILE_STRUCT (-1) + + +struct _cffi_global_s { + const char *name; + void *address; + _cffi_opcode_t type_op; + void *size_or_direct_fn; // OP_GLOBAL_VAR: size, or 0 if unknown + // OP_CPYTHON_BLTN_*: addr of direct function +}; + +struct _cffi_getconst_s { + unsigned long long value; + const struct _cffi_type_context_s *ctx; + int gindex; +}; + +struct _cffi_struct_union_s { + const char *name; + int type_index; // -> _cffi_types, on a OP_STRUCT_UNION + int flags; // _CFFI_F_* flags below + size_t size; + int alignment; + int first_field_index; // -> _cffi_fields array + int num_fields; +}; +#define _CFFI_F_UNION 0x01 // is a union, not a struct +#define _CFFI_F_CHECK_FIELDS 0x02 // complain if fields are not in the + // "standard layout" or if some are missing +#define _CFFI_F_PACKED 0x04 // for CHECK_FIELDS, assume a packed struct +#define _CFFI_F_EXTERNAL 0x08 // in some other ffi.include() +#define _CFFI_F_OPAQUE 0x10 // opaque + +struct _cffi_field_s { + const char *name; + size_t field_offset; + size_t field_size; + _cffi_opcode_t field_type_op; +}; + +struct _cffi_enum_s { + const char *name; + int type_index; // -> _cffi_types, on a OP_ENUM + int type_prim; // _CFFI_PRIM_xxx + const char *enumerators; // comma-delimited string +}; + +struct _cffi_typename_s { + const char *name; + int type_index; /* if opaque, points to a possibly artificial + OP_STRUCT which is itself opaque */ +}; + +struct _cffi_type_context_s { + _cffi_opcode_t *types; + const struct _cffi_global_s *globals; + const struct _cffi_field_s *fields; + const struct _cffi_struct_union_s *struct_unions; + const struct _cffi_enum_s *enums; + const struct _cffi_typename_s *typenames; + int num_globals; + int num_struct_unions; + int num_enums; + int num_typenames; + const char *const *includes; + int num_types; + int flags; /* future extension */ +}; + +struct _cffi_parse_info_s { + const struct _cffi_type_context_s *ctx; + _cffi_opcode_t *output; + unsigned int output_size; + size_t error_location; + const char *error_message; +}; + +struct _cffi_externpy_s { + const char *name; + size_t size_of_result; + void *reserved1, *reserved2; +}; + +#ifdef _CFFI_INTERNAL +static int parse_c_type(struct _cffi_parse_info_s *info, const char *input); +static int search_in_globals(const struct _cffi_type_context_s *ctx, + const char *search, size_t search_len); +static int search_in_struct_unions(const struct _cffi_type_context_s *ctx, + const char *search, size_t search_len); +#endif diff --git a/miniconda3/lib/python3.13/site-packages/cffi/pkgconfig.py b/miniconda3/lib/python3.13/site-packages/cffi/pkgconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..5c93f15a60e6f904b2dd108d6e22044a5890bcb4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/pkgconfig.py @@ -0,0 +1,121 @@ +# pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi +import sys, os, subprocess + +from .error import PkgConfigError + + +def merge_flags(cfg1, cfg2): + """Merge values from cffi config flags cfg2 to cf1 + + Example: + merge_flags({"libraries": ["one"]}, {"libraries": ["two"]}) + {"libraries": ["one", "two"]} + """ + for key, value in cfg2.items(): + if key not in cfg1: + cfg1[key] = value + else: + if not isinstance(cfg1[key], list): + raise TypeError("cfg1[%r] should be a list of strings" % (key,)) + if not isinstance(value, list): + raise TypeError("cfg2[%r] should be a list of strings" % (key,)) + cfg1[key].extend(value) + return cfg1 + + +def call(libname, flag, encoding=sys.getfilesystemencoding()): + """Calls pkg-config and returns the output if found + """ + a = ["pkg-config", "--print-errors"] + a.append(flag) + a.append(libname) + try: + pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + except EnvironmentError as e: + raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),)) + + bout, berr = pc.communicate() + if pc.returncode != 0: + try: + berr = berr.decode(encoding) + except Exception: + pass + raise PkgConfigError(berr.strip()) + + if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x + try: + bout = bout.decode(encoding) + except UnicodeDecodeError: + raise PkgConfigError("pkg-config %s %s returned bytes that cannot " + "be decoded with encoding %r:\n%r" % + (flag, libname, encoding, bout)) + + if os.altsep != '\\' and '\\' in bout: + raise PkgConfigError("pkg-config %s %s returned an unsupported " + "backslash-escaped output:\n%r" % + (flag, libname, bout)) + return bout + + +def flags_from_pkgconfig(libs): + r"""Return compiler line flags for FFI.set_source based on pkg-config output + + Usage + ... + ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"]) + + If pkg-config is installed on build machine, then arguments include_dirs, + library_dirs, libraries, define_macros, extra_compile_args and + extra_link_args are extended with an output of pkg-config for libfoo and + libbar. + + Raises PkgConfigError in case the pkg-config call fails. + """ + + def get_include_dirs(string): + return [x[2:] for x in string.split() if x.startswith("-I")] + + def get_library_dirs(string): + return [x[2:] for x in string.split() if x.startswith("-L")] + + def get_libraries(string): + return [x[2:] for x in string.split() if x.startswith("-l")] + + # convert -Dfoo=bar to list of tuples [("foo", "bar")] expected by distutils + def get_macros(string): + def _macro(x): + x = x[2:] # drop "-D" + if '=' in x: + return tuple(x.split("=", 1)) # "-Dfoo=bar" => ("foo", "bar") + else: + return (x, None) # "-Dfoo" => ("foo", None) + return [_macro(x) for x in string.split() if x.startswith("-D")] + + def get_other_cflags(string): + return [x for x in string.split() if not x.startswith("-I") and + not x.startswith("-D")] + + def get_other_libs(string): + return [x for x in string.split() if not x.startswith("-L") and + not x.startswith("-l")] + + # return kwargs for given libname + def kwargs(libname): + fse = sys.getfilesystemencoding() + all_cflags = call(libname, "--cflags") + all_libs = call(libname, "--libs") + return { + "include_dirs": get_include_dirs(all_cflags), + "library_dirs": get_library_dirs(all_libs), + "libraries": get_libraries(all_libs), + "define_macros": get_macros(all_cflags), + "extra_compile_args": get_other_cflags(all_cflags), + "extra_link_args": get_other_libs(all_libs), + } + + # merge all arguments together + ret = {} + for libname in libs: + lib_flags = kwargs(libname) + merge_flags(ret, lib_flags) + return ret diff --git a/miniconda3/lib/python3.13/site-packages/cffi/recompiler.py b/miniconda3/lib/python3.13/site-packages/cffi/recompiler.py new file mode 100644 index 0000000000000000000000000000000000000000..7734a34863330766984a00d3ff496393471aebfd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/recompiler.py @@ -0,0 +1,1598 @@ +import io, os, sys, sysconfig +from . import ffiplatform, model +from .error import VerificationError +from .cffi_opcode import * + +VERSION_BASE = 0x2601 +VERSION_EMBEDDED = 0x2701 +VERSION_CHAR16CHAR32 = 0x2801 + +USE_LIMITED_API = ((sys.platform != 'win32' or sys.version_info < (3, 0) or + sys.version_info >= (3, 5)) and + not sysconfig.get_config_var("Py_GIL_DISABLED")) # free-threaded doesn't yet support limited API + +class GlobalExpr: + def __init__(self, name, address, type_op, size=0, check_value=0): + self.name = name + self.address = address + self.type_op = type_op + self.size = size + self.check_value = check_value + + def as_c_expr(self): + return ' { "%s", (void *)%s, %s, (void *)%s },' % ( + self.name, self.address, self.type_op.as_c_expr(), self.size) + + def as_python_expr(self): + return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name, + self.check_value) + +class FieldExpr: + def __init__(self, name, field_offset, field_size, fbitsize, field_type_op): + self.name = name + self.field_offset = field_offset + self.field_size = field_size + self.fbitsize = fbitsize + self.field_type_op = field_type_op + + def as_c_expr(self): + spaces = " " * len(self.name) + return (' { "%s", %s,\n' % (self.name, self.field_offset) + + ' %s %s,\n' % (spaces, self.field_size) + + ' %s %s },' % (spaces, self.field_type_op.as_c_expr())) + + def as_python_expr(self): + raise NotImplementedError + + def as_field_python_expr(self): + if self.field_type_op.op == OP_NOOP: + size_expr = '' + elif self.field_type_op.op == OP_BITFIELD: + size_expr = format_four_bytes(self.fbitsize) + else: + raise NotImplementedError + return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(), + size_expr, + self.name) + +class StructUnionExpr: + def __init__(self, name, type_index, flags, size, alignment, comment, + first_field_index, c_fields): + self.name = name + self.type_index = type_index + self.flags = flags + self.size = size + self.alignment = alignment + self.comment = comment + self.first_field_index = first_field_index + self.c_fields = c_fields + + def as_c_expr(self): + return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags) + + '\n %s, %s, ' % (self.size, self.alignment) + + '%d, %d ' % (self.first_field_index, len(self.c_fields)) + + ('/* %s */ ' % self.comment if self.comment else '') + + '},') + + def as_python_expr(self): + flags = eval(self.flags, G_FLAGS) + fields_expr = [c_field.as_field_python_expr() + for c_field in self.c_fields] + return "(b'%s%s%s',%s)" % ( + format_four_bytes(self.type_index), + format_four_bytes(flags), + self.name, + ','.join(fields_expr)) + +class EnumExpr: + def __init__(self, name, type_index, size, signed, allenums): + self.name = name + self.type_index = type_index + self.size = size + self.signed = signed + self.allenums = allenums + + def as_c_expr(self): + return (' { "%s", %d, _cffi_prim_int(%s, %s),\n' + ' "%s" },' % (self.name, self.type_index, + self.size, self.signed, self.allenums)) + + def as_python_expr(self): + prim_index = { + (1, 0): PRIM_UINT8, (1, 1): PRIM_INT8, + (2, 0): PRIM_UINT16, (2, 1): PRIM_INT16, + (4, 0): PRIM_UINT32, (4, 1): PRIM_INT32, + (8, 0): PRIM_UINT64, (8, 1): PRIM_INT64, + }[self.size, self.signed] + return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index), + format_four_bytes(prim_index), + self.name, self.allenums) + +class TypenameExpr: + def __init__(self, name, type_index): + self.name = name + self.type_index = type_index + + def as_c_expr(self): + return ' { "%s", %d },' % (self.name, self.type_index) + + def as_python_expr(self): + return "b'%s%s'" % (format_four_bytes(self.type_index), self.name) + + +# ____________________________________________________________ + + +class Recompiler: + _num_externpy = 0 + + def __init__(self, ffi, module_name, target_is_python=False): + self.ffi = ffi + self.module_name = module_name + self.target_is_python = target_is_python + self._version = VERSION_BASE + + def needs_version(self, ver): + self._version = max(self._version, ver) + + def collect_type_table(self): + self._typesdict = {} + self._generate("collecttype") + # + all_decls = sorted(self._typesdict, key=str) + # + # prepare all FUNCTION bytecode sequences first + self.cffi_types = [] + for tp in all_decls: + if tp.is_raw_function: + assert self._typesdict[tp] is None + self._typesdict[tp] = len(self.cffi_types) + self.cffi_types.append(tp) # placeholder + for tp1 in tp.args: + assert isinstance(tp1, (model.VoidType, + model.BasePrimitiveType, + model.PointerType, + model.StructOrUnionOrEnum, + model.FunctionPtrType)) + if self._typesdict[tp1] is None: + self._typesdict[tp1] = len(self.cffi_types) + self.cffi_types.append(tp1) # placeholder + self.cffi_types.append('END') # placeholder + # + # prepare all OTHER bytecode sequences + for tp in all_decls: + if not tp.is_raw_function and self._typesdict[tp] is None: + self._typesdict[tp] = len(self.cffi_types) + self.cffi_types.append(tp) # placeholder + if tp.is_array_type and tp.length is not None: + self.cffi_types.append('LEN') # placeholder + assert None not in self._typesdict.values() + # + # collect all structs and unions and enums + self._struct_unions = {} + self._enums = {} + for tp in all_decls: + if isinstance(tp, model.StructOrUnion): + self._struct_unions[tp] = None + elif isinstance(tp, model.EnumType): + self._enums[tp] = None + for i, tp in enumerate(sorted(self._struct_unions, + key=lambda tp: tp.name)): + self._struct_unions[tp] = i + for i, tp in enumerate(sorted(self._enums, + key=lambda tp: tp.name)): + self._enums[tp] = i + # + # emit all bytecode sequences now + for tp in all_decls: + method = getattr(self, '_emit_bytecode_' + tp.__class__.__name__) + method(tp, self._typesdict[tp]) + # + # consistency check + for op in self.cffi_types: + assert isinstance(op, CffiOp) + self.cffi_types = tuple(self.cffi_types) # don't change any more + + def _enum_fields(self, tp): + # When producing C, expand all anonymous struct/union fields. + # That's necessary to have C code checking the offsets of the + # individual fields contained in them. When producing Python, + # don't do it and instead write it like it is, with the + # corresponding fields having an empty name. Empty names are + # recognized at runtime when we import the generated Python + # file. + expand_anonymous_struct_union = not self.target_is_python + return tp.enumfields(expand_anonymous_struct_union) + + def _do_collect_type(self, tp): + if not isinstance(tp, model.BaseTypeByIdentity): + if isinstance(tp, tuple): + for x in tp: + self._do_collect_type(x) + return + if tp not in self._typesdict: + self._typesdict[tp] = None + if isinstance(tp, model.FunctionPtrType): + self._do_collect_type(tp.as_raw_function()) + elif isinstance(tp, model.StructOrUnion): + if tp.fldtypes is not None and ( + tp not in self.ffi._parser._included_declarations): + for name1, tp1, _, _ in self._enum_fields(tp): + self._do_collect_type(self._field_type(tp, name1, tp1)) + else: + for _, x in tp._get_items(): + self._do_collect_type(x) + + def _generate(self, step_name): + lst = self.ffi._parser._declarations.items() + for name, (tp, quals) in sorted(lst): + kind, realname = name.split(' ', 1) + try: + method = getattr(self, '_generate_cpy_%s_%s' % (kind, + step_name)) + except AttributeError: + raise VerificationError( + "not implemented in recompile(): %r" % name) + try: + self._current_quals = quals + method(tp, realname) + except Exception as e: + model.attach_exception_info(e, name) + raise + + # ---------- + + ALL_STEPS = ["global", "field", "struct_union", "enum", "typename"] + + def collect_step_tables(self): + # collect the declarations for '_cffi_globals', '_cffi_typenames', etc. + self._lsts = {} + for step_name in self.ALL_STEPS: + self._lsts[step_name] = [] + self._seen_struct_unions = set() + self._generate("ctx") + self._add_missing_struct_unions() + # + for step_name in self.ALL_STEPS: + lst = self._lsts[step_name] + if step_name != "field": + lst.sort(key=lambda entry: entry.name) + self._lsts[step_name] = tuple(lst) # don't change any more + # + # check for a possible internal inconsistency: _cffi_struct_unions + # should have been generated with exactly self._struct_unions + lst = self._lsts["struct_union"] + for tp, i in self._struct_unions.items(): + assert i < len(lst) + assert lst[i].name == tp.name + assert len(lst) == len(self._struct_unions) + # same with enums + lst = self._lsts["enum"] + for tp, i in self._enums.items(): + assert i < len(lst) + assert lst[i].name == tp.name + assert len(lst) == len(self._enums) + + # ---------- + + def _prnt(self, what=''): + self._f.write(what + '\n') + + def write_source_to_f(self, f, preamble): + if self.target_is_python: + assert preamble is None + self.write_py_source_to_f(f) + else: + assert preamble is not None + self.write_c_source_to_f(f, preamble) + + def _rel_readlines(self, filename): + g = open(os.path.join(os.path.dirname(__file__), filename), 'r') + lines = g.readlines() + g.close() + return lines + + def write_c_source_to_f(self, f, preamble): + self._f = f + prnt = self._prnt + if self.ffi._embedding is not None: + prnt('#define _CFFI_USE_EMBEDDING') + if not USE_LIMITED_API: + prnt('#define _CFFI_NO_LIMITED_API') + # + # first the '#include' (actually done by inlining the file's content) + lines = self._rel_readlines('_cffi_include.h') + i = lines.index('#include "parse_c_type.h"\n') + lines[i:i+1] = self._rel_readlines('parse_c_type.h') + prnt(''.join(lines)) + # + # if we have ffi._embedding != None, we give it here as a macro + # and include an extra file + base_module_name = self.module_name.split('.')[-1] + if self.ffi._embedding is not None: + prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,)) + prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {') + self._print_string_literal_in_array(self.ffi._embedding) + prnt('0 };') + prnt('#ifdef PYPY_VERSION') + prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % ( + base_module_name,)) + prnt('#elif PY_MAJOR_VERSION >= 3') + prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % ( + base_module_name,)) + prnt('#else') + prnt('# define _CFFI_PYTHON_STARTUP_FUNC init%s' % ( + base_module_name,)) + prnt('#endif') + lines = self._rel_readlines('_embedding.h') + i = lines.index('#include "_cffi_errors.h"\n') + lines[i:i+1] = self._rel_readlines('_cffi_errors.h') + prnt(''.join(lines)) + self.needs_version(VERSION_EMBEDDED) + # + # then paste the C source given by the user, verbatim. + prnt('/************************************************************/') + prnt() + prnt(preamble) + prnt() + prnt('/************************************************************/') + prnt() + # + # the declaration of '_cffi_types' + prnt('static void *_cffi_types[] = {') + typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()]) + for i, op in enumerate(self.cffi_types): + comment = '' + if i in typeindex2type: + comment = ' // ' + typeindex2type[i]._get_c_name() + prnt('/* %2d */ %s,%s' % (i, op.as_c_expr(), comment)) + if not self.cffi_types: + prnt(' 0') + prnt('};') + prnt() + # + # call generate_cpy_xxx_decl(), for every xxx found from + # ffi._parser._declarations. This generates all the functions. + self._seen_constants = set() + self._generate("decl") + # + # the declaration of '_cffi_globals' and '_cffi_typenames' + nums = {} + for step_name in self.ALL_STEPS: + lst = self._lsts[step_name] + nums[step_name] = len(lst) + if nums[step_name] > 0: + prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % ( + step_name, step_name)) + for entry in lst: + prnt(entry.as_c_expr()) + prnt('};') + prnt() + # + # the declaration of '_cffi_includes' + if self.ffi._included_ffis: + prnt('static const char * const _cffi_includes[] = {') + for ffi_to_include in self.ffi._included_ffis: + try: + included_module_name, included_source = ( + ffi_to_include._assigned_source[:2]) + except AttributeError: + raise VerificationError( + "ffi object %r includes %r, but the latter has not " + "been prepared with set_source()" % ( + self.ffi, ffi_to_include,)) + if included_source is None: + raise VerificationError( + "not implemented yet: ffi.include() of a Python-based " + "ffi inside a C-based ffi") + prnt(' "%s",' % (included_module_name,)) + prnt(' NULL') + prnt('};') + prnt() + # + # the declaration of '_cffi_type_context' + prnt('static const struct _cffi_type_context_s _cffi_type_context = {') + prnt(' _cffi_types,') + for step_name in self.ALL_STEPS: + if nums[step_name] > 0: + prnt(' _cffi_%ss,' % step_name) + else: + prnt(' NULL, /* no %ss */' % step_name) + for step_name in self.ALL_STEPS: + if step_name != "field": + prnt(' %d, /* num_%ss */' % (nums[step_name], step_name)) + if self.ffi._included_ffis: + prnt(' _cffi_includes,') + else: + prnt(' NULL, /* no includes */') + prnt(' %d, /* num_types */' % (len(self.cffi_types),)) + flags = 0 + if self._num_externpy > 0 or self.ffi._embedding is not None: + flags |= 1 # set to mean that we use extern "Python" + prnt(' %d, /* flags */' % flags) + prnt('};') + prnt() + # + # the init function + prnt('#ifdef __GNUC__') + prnt('# pragma GCC visibility push(default) /* for -fvisibility= */') + prnt('#endif') + prnt() + prnt('#ifdef PYPY_VERSION') + prnt('PyMODINIT_FUNC') + prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,)) + prnt('{') + if flags & 1: + prnt(' if (((intptr_t)p[0]) >= 0x0A03) {') + prnt(' _cffi_call_python_org = ' + '(void(*)(struct _cffi_externpy_s *, char *))p[1];') + prnt(' }') + prnt(' p[0] = (const void *)0x%x;' % self._version) + prnt(' p[1] = &_cffi_type_context;') + prnt('#if PY_MAJOR_VERSION >= 3') + prnt(' return NULL;') + prnt('#endif') + prnt('}') + # on Windows, distutils insists on putting init_cffi_xyz in + # 'export_symbols', so instead of fighting it, just give up and + # give it one + prnt('# ifdef _MSC_VER') + prnt(' PyMODINIT_FUNC') + prnt('# if PY_MAJOR_VERSION >= 3') + prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,)) + prnt('# else') + prnt(' init%s(void) { }' % (base_module_name,)) + prnt('# endif') + prnt('# endif') + prnt('#elif PY_MAJOR_VERSION >= 3') + prnt('PyMODINIT_FUNC') + prnt('PyInit_%s(void)' % (base_module_name,)) + prnt('{') + prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % ( + self.module_name, self._version)) + prnt('}') + prnt('#else') + prnt('PyMODINIT_FUNC') + prnt('init%s(void)' % (base_module_name,)) + prnt('{') + prnt(' _cffi_init("%s", 0x%x, &_cffi_type_context);' % ( + self.module_name, self._version)) + prnt('}') + prnt('#endif') + prnt() + prnt('#ifdef __GNUC__') + prnt('# pragma GCC visibility pop') + prnt('#endif') + self._version = None + + def _to_py(self, x): + if isinstance(x, str): + return "b'%s'" % (x,) + if isinstance(x, (list, tuple)): + rep = [self._to_py(item) for item in x] + if len(rep) == 1: + rep.append('') + return "(%s)" % (','.join(rep),) + return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp. + + def write_py_source_to_f(self, f): + self._f = f + prnt = self._prnt + # + # header + prnt("# auto-generated file") + prnt("import _cffi_backend") + # + # the 'import' of the included ffis + num_includes = len(self.ffi._included_ffis or ()) + for i in range(num_includes): + ffi_to_include = self.ffi._included_ffis[i] + try: + included_module_name, included_source = ( + ffi_to_include._assigned_source[:2]) + except AttributeError: + raise VerificationError( + "ffi object %r includes %r, but the latter has not " + "been prepared with set_source()" % ( + self.ffi, ffi_to_include,)) + if included_source is not None: + raise VerificationError( + "not implemented yet: ffi.include() of a C-based " + "ffi inside a Python-based ffi") + prnt('from %s import ffi as _ffi%d' % (included_module_name, i)) + prnt() + prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,)) + prnt(" _version = 0x%x," % (self._version,)) + self._version = None + # + # the '_types' keyword argument + self.cffi_types = tuple(self.cffi_types) # don't change any more + types_lst = [op.as_python_bytes() for op in self.cffi_types] + prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),)) + typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()]) + # + # the keyword arguments from ALL_STEPS + for step_name in self.ALL_STEPS: + lst = self._lsts[step_name] + if len(lst) > 0 and step_name != "field": + prnt(' _%ss = %s,' % (step_name, self._to_py(lst))) + # + # the '_includes' keyword argument + if num_includes > 0: + prnt(' _includes = (%s,),' % ( + ', '.join(['_ffi%d' % i for i in range(num_includes)]),)) + # + # the footer + prnt(')') + + # ---------- + + def _gettypenum(self, type): + # a KeyError here is a bug. please report it! :-) + return self._typesdict[type] + + def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): + extraarg = '' + if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type(): + if tp.is_integer_type() and tp.name != '_Bool': + converter = '_cffi_to_c_int' + extraarg = ', %s' % tp.name + elif isinstance(tp, model.UnknownFloatType): + # don't check with is_float_type(): it may be a 'long + # double' here, and _cffi_to_c_double would loose precision + converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),) + else: + cname = tp.get_c_name('') + converter = '(%s)_cffi_to_c_%s' % (cname, + tp.name.replace(' ', '_')) + if cname in ('char16_t', 'char32_t'): + self.needs_version(VERSION_CHAR16CHAR32) + errvalue = '-1' + # + elif isinstance(tp, model.PointerType): + self._convert_funcarg_to_c_ptr_or_array(tp, fromvar, + tovar, errcode) + return + # + elif (isinstance(tp, model.StructOrUnionOrEnum) or + isinstance(tp, model.BasePrimitiveType)): + # a struct (not a struct pointer) as a function argument; + # or, a complex (the same code works) + self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' + % (tovar, self._gettypenum(tp), fromvar)) + self._prnt(' %s;' % errcode) + return + # + elif isinstance(tp, model.FunctionPtrType): + converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') + extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) + errvalue = 'NULL' + # + else: + raise NotImplementedError(tp) + # + self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) + self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( + tovar, tp.get_c_name(''), errvalue)) + self._prnt(' %s;' % errcode) + + def _extra_local_variables(self, tp, localvars, freelines): + if isinstance(tp, model.PointerType): + localvars.add('Py_ssize_t datasize') + localvars.add('struct _cffi_freeme_s *large_args_free = NULL') + freelines.add('if (large_args_free != NULL)' + ' _cffi_free_array_arguments(large_args_free);') + + def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): + self._prnt(' datasize = _cffi_prepare_pointer_call_argument(') + self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( + self._gettypenum(tp), fromvar, tovar)) + self._prnt(' if (datasize != 0) {') + self._prnt(' %s = ((size_t)datasize) <= 640 ? ' + '(%s)alloca((size_t)datasize) : NULL;' % ( + tovar, tp.get_c_name(''))) + self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' + '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) + self._prnt(' datasize, &large_args_free) < 0)') + self._prnt(' %s;' % errcode) + self._prnt(' }') + + def _convert_expr_from_c(self, tp, var, context): + if isinstance(tp, model.BasePrimitiveType): + if tp.is_integer_type() and tp.name != '_Bool': + return '_cffi_from_c_int(%s, %s)' % (var, tp.name) + elif isinstance(tp, model.UnknownFloatType): + return '_cffi_from_c_double(%s)' % (var,) + elif tp.name != 'long double' and not tp.is_complex_type(): + cname = tp.name.replace(' ', '_') + if cname in ('char16_t', 'char32_t'): + self.needs_version(VERSION_CHAR16CHAR32) + return '_cffi_from_c_%s(%s)' % (cname, var) + else: + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, (model.PointerType, model.FunctionPtrType)): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.ArrayType): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(model.PointerType(tp.item))) + elif isinstance(tp, model.StructOrUnion): + if tp.fldnames is None: + raise TypeError("'%s' is used as %s, but is opaque" % ( + tp._get_c_name(), context)) + return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.EnumType): + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + else: + raise NotImplementedError(tp) + + # ---------- + # typedefs + + def _typedef_type(self, tp, name): + return self._global_type(tp, "(*(%s *)0)" % (name,)) + + def _generate_cpy_typedef_collecttype(self, tp, name): + self._do_collect_type(self._typedef_type(tp, name)) + + def _generate_cpy_typedef_decl(self, tp, name): + pass + + def _typedef_ctx(self, tp, name): + type_index = self._typesdict[tp] + self._lsts["typename"].append(TypenameExpr(name, type_index)) + + def _generate_cpy_typedef_ctx(self, tp, name): + tp = self._typedef_type(tp, name) + self._typedef_ctx(tp, name) + if getattr(tp, "origin", None) == "unknown_type": + self._struct_ctx(tp, tp.name, approxname=None) + elif isinstance(tp, model.NamedPointerType): + self._struct_ctx(tp.totype, tp.totype.name, approxname=tp.name, + named_ptr=tp) + + # ---------- + # function declarations + + def _generate_cpy_function_collecttype(self, tp, name): + self._do_collect_type(tp.as_raw_function()) + if tp.ellipsis and not self.target_is_python: + self._do_collect_type(tp) + + def _generate_cpy_function_decl(self, tp, name): + assert not self.target_is_python + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + # cannot support vararg functions better than this: check for its + # exact type (including the fixed arguments), and build it as a + # constant function pointer (no CPython wrapper) + self._generate_cpy_constant_decl(tp, name) + return + prnt = self._prnt + numargs = len(tp.args) + if numargs == 0: + argname = 'noarg' + elif numargs == 1: + argname = 'arg0' + else: + argname = 'args' + # + # ------------------------------ + # the 'd' version of the function, only for addressof(lib, 'func') + arguments = [] + call_arguments = [] + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + arguments.append(type.get_c_name(' x%d' % i, context)) + call_arguments.append('x%d' % i) + repr_arguments = ', '.join(arguments) + repr_arguments = repr_arguments or 'void' + if tp.abi: + abi = tp.abi + ' ' + else: + abi = '' + name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments) + prnt('static %s' % (tp.result.get_c_name(name_and_arguments),)) + prnt('{') + call_arguments = ', '.join(call_arguments) + result_code = 'return ' + if isinstance(tp.result, model.VoidType): + result_code = '' + prnt(' %s%s(%s);' % (result_code, name, call_arguments)) + prnt('}') + # + prnt('#ifndef PYPY_VERSION') # ------------------------------ + # + prnt('static PyObject *') + prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) + prnt('{') + # + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + arg = type.get_c_name(' x%d' % i, context) + prnt(' %s;' % arg) + # + localvars = set() + freelines = set() + for type in tp.args: + self._extra_local_variables(type, localvars, freelines) + for decl in sorted(localvars): + prnt(' %s;' % (decl,)) + # + if not isinstance(tp.result, model.VoidType): + result_code = 'result = ' + context = 'result of %s' % name + result_decl = ' %s;' % tp.result.get_c_name(' result', context) + prnt(result_decl) + prnt(' PyObject *pyresult;') + else: + result_decl = None + result_code = '' + # + if len(tp.args) > 1: + rng = range(len(tp.args)) + for i in rng: + prnt(' PyObject *arg%d;' % i) + prnt() + prnt(' if (!PyArg_UnpackTuple(args, "%s", %d, %d, %s))' % ( + name, len(rng), len(rng), + ', '.join(['&arg%d' % i for i in rng]))) + prnt(' return NULL;') + prnt() + # + for i, type in enumerate(tp.args): + self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i, + 'return NULL') + prnt() + # + prnt(' Py_BEGIN_ALLOW_THREADS') + prnt(' _cffi_restore_errno();') + call_arguments = ['x%d' % i for i in range(len(tp.args))] + call_arguments = ', '.join(call_arguments) + prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) + prnt(' _cffi_save_errno();') + prnt(' Py_END_ALLOW_THREADS') + prnt() + # + prnt(' (void)self; /* unused */') + if numargs == 0: + prnt(' (void)noarg; /* unused */') + if result_code: + prnt(' pyresult = %s;' % + self._convert_expr_from_c(tp.result, 'result', 'result type')) + for freeline in freelines: + prnt(' ' + freeline) + prnt(' return pyresult;') + else: + for freeline in freelines: + prnt(' ' + freeline) + prnt(' Py_INCREF(Py_None);') + prnt(' return Py_None;') + prnt('}') + # + prnt('#else') # ------------------------------ + # + # the PyPy version: need to replace struct/union arguments with + # pointers, and if the result is a struct/union, insert a first + # arg that is a pointer to the result. We also do that for + # complex args and return type. + def need_indirection(type): + return (isinstance(type, model.StructOrUnion) or + (isinstance(type, model.PrimitiveType) and + type.is_complex_type())) + difference = False + arguments = [] + call_arguments = [] + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + indirection = '' + if need_indirection(type): + indirection = '*' + difference = True + arg = type.get_c_name(' %sx%d' % (indirection, i), context) + arguments.append(arg) + call_arguments.append('%sx%d' % (indirection, i)) + tp_result = tp.result + if need_indirection(tp_result): + context = 'result of %s' % name + arg = tp_result.get_c_name(' *result', context) + arguments.insert(0, arg) + tp_result = model.void_type + result_decl = None + result_code = '*result = ' + difference = True + if difference: + repr_arguments = ', '.join(arguments) + repr_arguments = repr_arguments or 'void' + name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name, + repr_arguments) + prnt('static %s' % (tp_result.get_c_name(name_and_arguments),)) + prnt('{') + if result_decl: + prnt(result_decl) + call_arguments = ', '.join(call_arguments) + prnt(' { %s%s(%s); }' % (result_code, name, call_arguments)) + if result_decl: + prnt(' return result;') + prnt('}') + else: + prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name)) + # + prnt('#endif') # ------------------------------ + prnt() + + def _generate_cpy_function_ctx(self, tp, name): + if tp.ellipsis and not self.target_is_python: + self._generate_cpy_constant_ctx(tp, name) + return + type_index = self._typesdict[tp.as_raw_function()] + numargs = len(tp.args) + if self.target_is_python: + meth_kind = OP_DLOPEN_FUNC + elif numargs == 0: + meth_kind = OP_CPYTHON_BLTN_N # 'METH_NOARGS' + elif numargs == 1: + meth_kind = OP_CPYTHON_BLTN_O # 'METH_O' + else: + meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS' + self._lsts["global"].append( + GlobalExpr(name, '_cffi_f_%s' % name, + CffiOp(meth_kind, type_index), + size='_cffi_d_%s' % name)) + + # ---------- + # named structs or unions + + def _field_type(self, tp_struct, field_name, tp_field): + if isinstance(tp_field, model.ArrayType): + actual_length = tp_field.length + if actual_length == '...': + ptr_struct_name = tp_struct.get_c_name('*') + actual_length = '_cffi_array_len(((%s)0)->%s)' % ( + ptr_struct_name, field_name) + tp_item = self._field_type(tp_struct, '%s[0]' % field_name, + tp_field.item) + tp_field = model.ArrayType(tp_item, actual_length) + return tp_field + + def _struct_collecttype(self, tp): + self._do_collect_type(tp) + if self.target_is_python: + # also requires nested anon struct/unions in ABI mode, recursively + for fldtype in tp.anonymous_struct_fields(): + self._struct_collecttype(fldtype) + + def _struct_decl(self, tp, cname, approxname): + if tp.fldtypes is None: + return + prnt = self._prnt + checkfuncname = '_cffi_checkfld_%s' % (approxname,) + prnt('_CFFI_UNUSED_FN') + prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt('{') + prnt(' /* only to generate compile-time warnings or errors */') + prnt(' (void)p;') + for fname, ftype, fbitsize, fqual in self._enum_fields(tp): + try: + if ftype.is_integer_type() or fbitsize >= 0: + # accept all integers, but complain on float or double + if fname != '': + prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is " + "an integer */" % (fname, cname, fname)) + continue + # only accept exactly the type declared, except that '[]' + # is interpreted as a '*' and so will match any array length. + # (It would also match '*', but that's harder to detect...) + while (isinstance(ftype, model.ArrayType) + and (ftype.length is None or ftype.length == '...')): + ftype = ftype.item + fname = fname + '[0]' + prnt(' { %s = &p->%s; (void)tmp; }' % ( + ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + fname)) + except VerificationError as e: + prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt('}') + prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname)) + prnt() + + def _struct_ctx(self, tp, cname, approxname, named_ptr=None): + type_index = self._typesdict[tp] + reason_for_not_expanding = None + flags = [] + if isinstance(tp, model.UnionType): + flags.append("_CFFI_F_UNION") + if tp.fldtypes is None: + flags.append("_CFFI_F_OPAQUE") + reason_for_not_expanding = "opaque" + if (tp not in self.ffi._parser._included_declarations and + (named_ptr is None or + named_ptr not in self.ffi._parser._included_declarations)): + if tp.fldtypes is None: + pass # opaque + elif tp.partial or any(tp.anonymous_struct_fields()): + pass # field layout obtained silently from the C compiler + else: + flags.append("_CFFI_F_CHECK_FIELDS") + if tp.packed: + if tp.packed > 1: + raise NotImplementedError( + "%r is declared with 'pack=%r'; only 0 or 1 are " + "supported in API mode (try to use \"...;\", which " + "does not require a 'pack' declaration)" % + (tp, tp.packed)) + flags.append("_CFFI_F_PACKED") + else: + flags.append("_CFFI_F_EXTERNAL") + reason_for_not_expanding = "external" + flags = '|'.join(flags) or '0' + c_fields = [] + if reason_for_not_expanding is None: + enumfields = list(self._enum_fields(tp)) + for fldname, fldtype, fbitsize, fqual in enumfields: + fldtype = self._field_type(tp, fldname, fldtype) + self._check_not_opaque(fldtype, + "field '%s.%s'" % (tp.name, fldname)) + # cname is None for _add_missing_struct_unions() only + op = OP_NOOP + if fbitsize >= 0: + op = OP_BITFIELD + size = '%d /* bits */' % fbitsize + elif cname is None or ( + isinstance(fldtype, model.ArrayType) and + fldtype.length is None): + size = '(size_t)-1' + else: + size = 'sizeof(((%s)0)->%s)' % ( + tp.get_c_name('*') if named_ptr is None + else named_ptr.name, + fldname) + if cname is None or fbitsize >= 0: + offset = '(size_t)-1' + elif named_ptr is not None: + offset = '(size_t)(((char *)&((%s)4096)->%s) - (char *)4096)' % ( + named_ptr.name, fldname) + else: + offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname) + c_fields.append( + FieldExpr(fldname, offset, size, fbitsize, + CffiOp(op, self._typesdict[fldtype]))) + first_field_index = len(self._lsts["field"]) + self._lsts["field"].extend(c_fields) + # + if cname is None: # unknown name, for _add_missing_struct_unions + size = '(size_t)-2' + align = -2 + comment = "unnamed" + else: + if named_ptr is not None: + size = 'sizeof(*(%s)0)' % (named_ptr.name,) + align = '-1 /* unknown alignment */' + else: + size = 'sizeof(%s)' % (cname,) + align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,) + comment = None + else: + size = '(size_t)-1' + align = -1 + first_field_index = -1 + comment = reason_for_not_expanding + self._lsts["struct_union"].append( + StructUnionExpr(tp.name, type_index, flags, size, align, comment, + first_field_index, c_fields)) + self._seen_struct_unions.add(tp) + + def _check_not_opaque(self, tp, location): + while isinstance(tp, model.ArrayType): + tp = tp.item + if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None: + raise TypeError( + "%s is of an opaque type (not declared in cdef())" % location) + + def _add_missing_struct_unions(self): + # not very nice, but some struct declarations might be missing + # because they don't have any known C name. Check that they are + # not partial (we can't complete or verify them!) and emit them + # anonymously. + lst = list(self._struct_unions.items()) + lst.sort(key=lambda tp_order: tp_order[1]) + for tp, order in lst: + if tp not in self._seen_struct_unions: + if tp.partial: + raise NotImplementedError("internal inconsistency: %r is " + "partial but was not seen at " + "this point" % (tp,)) + if tp.name.startswith('$') and tp.name[1:].isdigit(): + approxname = tp.name[1:] + elif tp.name == '_IO_FILE' and tp.forcename == 'FILE': + approxname = 'FILE' + self._typedef_ctx(tp, 'FILE') + else: + raise NotImplementedError("internal inconsistency: %r" % + (tp,)) + self._struct_ctx(tp, None, approxname) + + def _generate_cpy_struct_collecttype(self, tp, name): + self._struct_collecttype(tp) + _generate_cpy_union_collecttype = _generate_cpy_struct_collecttype + + def _struct_names(self, tp): + cname = tp.get_c_name('') + if ' ' in cname: + return cname, cname.replace(' ', '_') + else: + return cname, '_' + cname + + def _generate_cpy_struct_decl(self, tp, name): + self._struct_decl(tp, *self._struct_names(tp)) + _generate_cpy_union_decl = _generate_cpy_struct_decl + + def _generate_cpy_struct_ctx(self, tp, name): + self._struct_ctx(tp, *self._struct_names(tp)) + _generate_cpy_union_ctx = _generate_cpy_struct_ctx + + # ---------- + # 'anonymous' declarations. These are produced for anonymous structs + # or unions; the 'name' is obtained by a typedef. + + def _generate_cpy_anonymous_collecttype(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_cpy_enum_collecttype(tp, name) + else: + self._struct_collecttype(tp) + + def _generate_cpy_anonymous_decl(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_cpy_enum_decl(tp) + else: + self._struct_decl(tp, name, 'typedef_' + name) + + def _generate_cpy_anonymous_ctx(self, tp, name): + if isinstance(tp, model.EnumType): + self._enum_ctx(tp, name) + else: + self._struct_ctx(tp, name, 'typedef_' + name) + + # ---------- + # constants, declared with "static const ..." + + def _generate_cpy_const(self, is_int, name, tp=None, category='const', + check_value=None): + if (category, name) in self._seen_constants: + raise VerificationError( + "duplicate declaration of %s '%s'" % (category, name)) + self._seen_constants.add((category, name)) + # + prnt = self._prnt + funcname = '_cffi_%s_%s' % (category, name) + if is_int: + prnt('static int %s(unsigned long long *o)' % funcname) + prnt('{') + prnt(' int n = (%s) <= 0;' % (name,)) + prnt(' *o = (unsigned long long)((%s) | 0);' + ' /* check that %s is an integer */' % (name, name)) + if check_value is not None: + if check_value > 0: + check_value = '%dU' % (check_value,) + prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,)) + prnt(' n |= 2;') + prnt(' return n;') + prnt('}') + else: + assert check_value is None + prnt('static void %s(char *o)' % funcname) + prnt('{') + prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name)) + prnt('}') + prnt() + + def _generate_cpy_constant_collecttype(self, tp, name): + is_int = tp.is_integer_type() + if not is_int or self.target_is_python: + self._do_collect_type(tp) + + def _generate_cpy_constant_decl(self, tp, name): + is_int = tp.is_integer_type() + self._generate_cpy_const(is_int, name, tp) + + def _generate_cpy_constant_ctx(self, tp, name): + if not self.target_is_python and tp.is_integer_type(): + type_op = CffiOp(OP_CONSTANT_INT, -1) + else: + if self.target_is_python: + const_kind = OP_DLOPEN_CONST + else: + const_kind = OP_CONSTANT + type_index = self._typesdict[tp] + type_op = CffiOp(const_kind, type_index) + self._lsts["global"].append( + GlobalExpr(name, '_cffi_const_%s' % name, type_op)) + + # ---------- + # enums + + def _generate_cpy_enum_collecttype(self, tp, name): + self._do_collect_type(tp) + + def _generate_cpy_enum_decl(self, tp, name=None): + for enumerator in tp.enumerators: + self._generate_cpy_const(True, enumerator) + + def _enum_ctx(self, tp, cname): + type_index = self._typesdict[tp] + type_op = CffiOp(OP_ENUM, -1) + if self.target_is_python: + tp.check_not_partial() + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + self._lsts["global"].append( + GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op, + check_value=enumvalue)) + # + if cname is not None and '$' not in cname and not self.target_is_python: + size = "sizeof(%s)" % cname + signed = "((%s)-1) <= 0" % cname + else: + basetp = tp.build_baseinttype(self.ffi, []) + size = self.ffi.sizeof(basetp) + signed = int(int(self.ffi.cast(basetp, -1)) < 0) + allenums = ",".join(tp.enumerators) + self._lsts["enum"].append( + EnumExpr(tp.name, type_index, size, signed, allenums)) + + def _generate_cpy_enum_ctx(self, tp, name): + self._enum_ctx(tp, tp._get_c_name()) + + # ---------- + # macros: for now only for integers + + def _generate_cpy_macro_collecttype(self, tp, name): + pass + + def _generate_cpy_macro_decl(self, tp, name): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + self._generate_cpy_const(True, name, check_value=check_value) + + def _generate_cpy_macro_ctx(self, tp, name): + if tp == '...': + if self.target_is_python: + raise VerificationError( + "cannot use the syntax '...' in '#define %s ...' when " + "using the ABI mode" % (name,)) + check_value = None + else: + check_value = tp # an integer + type_op = CffiOp(OP_CONSTANT_INT, -1) + self._lsts["global"].append( + GlobalExpr(name, '_cffi_const_%s' % name, type_op, + check_value=check_value)) + + # ---------- + # global variables + + def _global_type(self, tp, global_name): + if isinstance(tp, model.ArrayType): + actual_length = tp.length + if actual_length == '...': + actual_length = '_cffi_array_len(%s)' % (global_name,) + tp_item = self._global_type(tp.item, '%s[0]' % global_name) + tp = model.ArrayType(tp_item, actual_length) + return tp + + def _generate_cpy_variable_collecttype(self, tp, name): + self._do_collect_type(self._global_type(tp, name)) + + def _generate_cpy_variable_decl(self, tp, name): + prnt = self._prnt + tp = self._global_type(tp, name) + if isinstance(tp, model.ArrayType) and tp.length is None: + tp = tp.item + ampersand = '' + else: + ampersand = '&' + # This code assumes that casts from "tp *" to "void *" is a + # no-op, i.e. a function that returns a "tp *" can be called + # as if it returned a "void *". This should be generally true + # on any modern machine. The only exception to that rule (on + # uncommon architectures, and as far as I can tell) might be + # if 'tp' were a function type, but that is not possible here. + # (If 'tp' is a function _pointer_ type, then casts from "fn_t + # **" to "void *" are again no-ops, as far as I can tell.) + decl = '*_cffi_var_%s(void)' % (name,) + prnt('static ' + tp.get_c_name(decl, quals=self._current_quals)) + prnt('{') + prnt(' return %s(%s);' % (ampersand, name)) + prnt('}') + prnt() + + def _generate_cpy_variable_ctx(self, tp, name): + tp = self._global_type(tp, name) + type_index = self._typesdict[tp] + if self.target_is_python: + op = OP_GLOBAL_VAR + else: + op = OP_GLOBAL_VAR_F + self._lsts["global"].append( + GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index))) + + # ---------- + # extern "Python" + + def _generate_cpy_extern_python_collecttype(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + self._do_collect_type(tp) + _generate_cpy_dllexport_python_collecttype = \ + _generate_cpy_extern_python_plus_c_collecttype = \ + _generate_cpy_extern_python_collecttype + + def _extern_python_decl(self, tp, name, tag_and_space): + prnt = self._prnt + if isinstance(tp.result, model.VoidType): + size_of_result = '0' + else: + context = 'result of %s' % name + size_of_result = '(int)sizeof(%s)' % ( + tp.result.get_c_name('', context),) + prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name) + prnt(' { "%s.%s", %s, 0, 0 };' % ( + self.module_name, name, size_of_result)) + prnt() + # + arguments = [] + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + arg = type.get_c_name(' a%d' % i, context) + arguments.append(arg) + # + repr_arguments = ', '.join(arguments) + repr_arguments = repr_arguments or 'void' + name_and_arguments = '%s(%s)' % (name, repr_arguments) + if tp.abi == "__stdcall": + name_and_arguments = '_cffi_stdcall ' + name_and_arguments + # + def may_need_128_bits(tp): + return (isinstance(tp, model.PrimitiveType) and + tp.name == 'long double') + # + size_of_a = max(len(tp.args)*8, 8) + if may_need_128_bits(tp.result): + size_of_a = max(size_of_a, 16) + if isinstance(tp.result, model.StructOrUnion): + size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % ( + tp.result.get_c_name(''), size_of_a, + tp.result.get_c_name(''), size_of_a) + prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments))) + prnt('{') + prnt(' char a[%s];' % size_of_a) + prnt(' char *p = a;') + for i, type in enumerate(tp.args): + arg = 'a%d' % i + if (isinstance(type, model.StructOrUnion) or + may_need_128_bits(type)): + arg = '&' + arg + type = model.PointerType(type) + prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg)) + prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name) + if not isinstance(tp.result, model.VoidType): + prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),)) + prnt('}') + prnt() + self._num_externpy += 1 + + def _generate_cpy_extern_python_decl(self, tp, name): + self._extern_python_decl(tp, name, 'static ') + + def _generate_cpy_dllexport_python_decl(self, tp, name): + self._extern_python_decl(tp, name, 'CFFI_DLLEXPORT ') + + def _generate_cpy_extern_python_plus_c_decl(self, tp, name): + self._extern_python_decl(tp, name, '') + + def _generate_cpy_extern_python_ctx(self, tp, name): + if self.target_is_python: + raise VerificationError( + "cannot use 'extern \"Python\"' in the ABI mode") + if tp.ellipsis: + raise NotImplementedError("a vararg function is extern \"Python\"") + type_index = self._typesdict[tp] + type_op = CffiOp(OP_EXTERN_PYTHON, type_index) + self._lsts["global"].append( + GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name)) + + _generate_cpy_dllexport_python_ctx = \ + _generate_cpy_extern_python_plus_c_ctx = \ + _generate_cpy_extern_python_ctx + + def _print_string_literal_in_array(self, s): + prnt = self._prnt + prnt('// # NB. this is not a string because of a size limit in MSVC') + if not isinstance(s, bytes): # unicode + s = s.encode('utf-8') # -> bytes + else: + s.decode('utf-8') # got bytes, check for valid utf-8 + try: + s.decode('ascii') + except UnicodeDecodeError: + s = b'# -*- encoding: utf8 -*-\n' + s + for line in s.splitlines(True): + comment = line + if type('//') is bytes: # python2 + line = map(ord, line) # make a list of integers + else: # python3 + # type(line) is bytes, which enumerates like a list of integers + comment = ascii(comment)[1:-1] + prnt(('// ' + comment).rstrip()) + printed_line = '' + for c in line: + if len(printed_line) >= 76: + prnt(printed_line) + printed_line = '' + printed_line += '%d,' % (c,) + prnt(printed_line) + + # ---------- + # emitting the opcodes for individual types + + def _emit_bytecode_VoidType(self, tp, index): + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, PRIM_VOID) + + def _emit_bytecode_PrimitiveType(self, tp, index): + prim_index = PRIMITIVE_TO_INDEX[tp.name] + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index) + + def _emit_bytecode_UnknownIntegerType(self, tp, index): + s = ('_cffi_prim_int(sizeof(%s), (\n' + ' ((%s)-1) | 0 /* check that %s is an integer type */\n' + ' ) <= 0)' % (tp.name, tp.name, tp.name)) + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) + + def _emit_bytecode_UnknownFloatType(self, tp, index): + s = ('_cffi_prim_float(sizeof(%s) *\n' + ' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n' + ' )' % (tp.name, tp.name)) + self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s) + + def _emit_bytecode_RawFunctionType(self, tp, index): + self.cffi_types[index] = CffiOp(OP_FUNCTION, self._typesdict[tp.result]) + index += 1 + for tp1 in tp.args: + realindex = self._typesdict[tp1] + if index != realindex: + if isinstance(tp1, model.PrimitiveType): + self._emit_bytecode_PrimitiveType(tp1, index) + else: + self.cffi_types[index] = CffiOp(OP_NOOP, realindex) + index += 1 + flags = int(tp.ellipsis) + if tp.abi is not None: + if tp.abi == '__stdcall': + flags |= 2 + else: + raise NotImplementedError("abi=%r" % (tp.abi,)) + self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags) + + def _emit_bytecode_PointerType(self, tp, index): + self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[tp.totype]) + + _emit_bytecode_ConstPointerType = _emit_bytecode_PointerType + _emit_bytecode_NamedPointerType = _emit_bytecode_PointerType + + def _emit_bytecode_FunctionPtrType(self, tp, index): + raw = tp.as_raw_function() + self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[raw]) + + def _emit_bytecode_ArrayType(self, tp, index): + item_index = self._typesdict[tp.item] + if tp.length is None: + self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index) + elif tp.length == '...': + raise VerificationError( + "type %s badly placed: the '...' array length can only be " + "used on global arrays or on fields of structures" % ( + str(tp).replace('/*...*/', '...'),)) + else: + assert self.cffi_types[index + 1] == 'LEN' + self.cffi_types[index] = CffiOp(OP_ARRAY, item_index) + self.cffi_types[index + 1] = CffiOp(None, str(tp.length)) + + def _emit_bytecode_StructType(self, tp, index): + struct_index = self._struct_unions[tp] + self.cffi_types[index] = CffiOp(OP_STRUCT_UNION, struct_index) + _emit_bytecode_UnionType = _emit_bytecode_StructType + + def _emit_bytecode_EnumType(self, tp, index): + enum_index = self._enums[tp] + self.cffi_types[index] = CffiOp(OP_ENUM, enum_index) + + +if sys.version_info >= (3,): + NativeIO = io.StringIO +else: + class NativeIO(io.BytesIO): + def write(self, s): + if isinstance(s, unicode): + s = s.encode('ascii') + super(NativeIO, self).write(s) + +def _is_file_like(maybefile): + # compare to xml.etree.ElementTree._get_writer + return hasattr(maybefile, 'write') + +def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose): + if verbose: + print("generating %s" % (target_file,)) + recompiler = Recompiler(ffi, module_name, + target_is_python=(preamble is None)) + recompiler.collect_type_table() + recompiler.collect_step_tables() + if _is_file_like(target_file): + recompiler.write_source_to_f(target_file, preamble) + return True + f = NativeIO() + recompiler.write_source_to_f(f, preamble) + output = f.getvalue() + try: + with open(target_file, 'r') as f1: + if f1.read(len(output) + 1) != output: + raise IOError + if verbose: + print("(already up-to-date)") + return False # already up-to-date + except IOError: + tmp_file = '%s.~%d' % (target_file, os.getpid()) + with open(tmp_file, 'w') as f1: + f1.write(output) + try: + os.rename(tmp_file, target_file) + except OSError: + os.unlink(target_file) + os.rename(tmp_file, target_file) + return True + +def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False): + assert preamble is not None + return _make_c_or_py_source(ffi, module_name, preamble, target_c_file, + verbose) + +def make_py_source(ffi, module_name, target_py_file, verbose=False): + return _make_c_or_py_source(ffi, module_name, None, target_py_file, + verbose) + +def _modname_to_file(outputdir, modname, extension): + parts = modname.split('.') + try: + os.makedirs(os.path.join(outputdir, *parts[:-1])) + except OSError: + pass + parts[-1] += extension + return os.path.join(outputdir, *parts), parts + + +# Aaargh. Distutils is not tested at all for the purpose of compiling +# DLLs that are not extension modules. Here are some hacks to work +# around that, in the _patch_for_*() functions... + +def _patch_meth(patchlist, cls, name, new_meth): + old = getattr(cls, name) + patchlist.append((cls, name, old)) + setattr(cls, name, new_meth) + return old + +def _unpatch_meths(patchlist): + for cls, name, old_meth in reversed(patchlist): + setattr(cls, name, old_meth) + +def _patch_for_embedding(patchlist): + if sys.platform == 'win32': + # we must not remove the manifest when building for embedding! + # FUTURE: this module was removed in setuptools 74; this is likely dead code and should be removed, + # since the toolchain it supports (VS2005-2008) is also long dead. + from cffi._shimmed_dist_utils import MSVCCompiler + if MSVCCompiler is not None: + _patch_meth(patchlist, MSVCCompiler, '_remove_visual_c_ref', + lambda self, manifest_file: manifest_file) + + if sys.platform == 'darwin': + # we must not make a '-bundle', but a '-dynamiclib' instead + from cffi._shimmed_dist_utils import CCompiler + def my_link_shared_object(self, *args, **kwds): + if '-bundle' in self.linker_so: + self.linker_so = list(self.linker_so) + i = self.linker_so.index('-bundle') + self.linker_so[i] = '-dynamiclib' + return old_link_shared_object(self, *args, **kwds) + old_link_shared_object = _patch_meth(patchlist, CCompiler, + 'link_shared_object', + my_link_shared_object) + +def _patch_for_target(patchlist, target): + from cffi._shimmed_dist_utils import build_ext + # if 'target' is different from '*', we need to patch some internal + # method to just return this 'target' value, instead of having it + # built from module_name + if target.endswith('.*'): + target = target[:-2] + if sys.platform == 'win32': + target += '.dll' + elif sys.platform == 'darwin': + target += '.dylib' + else: + target += '.so' + _patch_meth(patchlist, build_ext, 'get_ext_filename', + lambda self, ext_name: target) + + +def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True, + c_file=None, source_extension='.c', extradir=None, + compiler_verbose=1, target=None, debug=None, + uses_ffiplatform=True, **kwds): + if not isinstance(module_name, str): + module_name = module_name.encode('ascii') + if ffi._windows_unicode: + ffi._apply_windows_unicode(kwds) + if preamble is not None: + if call_c_compiler and _is_file_like(c_file): + raise TypeError("Writing to file-like objects is not supported " + "with call_c_compiler=True") + embedding = (ffi._embedding is not None) + if embedding: + ffi._apply_embedding_fix(kwds) + if c_file is None: + c_file, parts = _modname_to_file(tmpdir, module_name, + source_extension) + if extradir: + parts = [extradir] + parts + ext_c_file = os.path.join(*parts) + else: + ext_c_file = c_file + # + if target is None: + if embedding: + target = '%s.*' % module_name + else: + target = '*' + # + if uses_ffiplatform: + ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds) + else: + ext = None + updated = make_c_source(ffi, module_name, preamble, c_file, + verbose=compiler_verbose) + if call_c_compiler: + patchlist = [] + cwd = os.getcwd() + try: + if embedding: + _patch_for_embedding(patchlist) + if target != '*': + _patch_for_target(patchlist, target) + if compiler_verbose: + if tmpdir == '.': + msg = 'the current directory is' + else: + msg = 'setting the current directory to' + print('%s %r' % (msg, os.path.abspath(tmpdir))) + os.chdir(tmpdir) + outputfilename = ffiplatform.compile('.', ext, + compiler_verbose, debug) + finally: + os.chdir(cwd) + _unpatch_meths(patchlist) + return outputfilename + else: + return ext, updated + else: + if c_file is None: + c_file, _ = _modname_to_file(tmpdir, module_name, '.py') + updated = make_py_source(ffi, module_name, c_file, + verbose=compiler_verbose) + if call_c_compiler: + return c_file + else: + return None, updated + diff --git a/miniconda3/lib/python3.13/site-packages/cffi/setuptools_ext.py b/miniconda3/lib/python3.13/site-packages/cffi/setuptools_ext.py new file mode 100644 index 0000000000000000000000000000000000000000..5cdd246fb4dfb808dc8b09df5724a68386fa4bc3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/setuptools_ext.py @@ -0,0 +1,229 @@ +import os +import sys +import sysconfig + +try: + basestring +except NameError: + # Python 3.x + basestring = str + +def error(msg): + from cffi._shimmed_dist_utils import DistutilsSetupError + raise DistutilsSetupError(msg) + + +def execfile(filename, glob): + # We use execfile() (here rewritten for Python 3) instead of + # __import__() to load the build script. The problem with + # a normal import is that in some packages, the intermediate + # __init__.py files may already try to import the file that + # we are generating. + with open(filename) as f: + src = f.read() + src += '\n' # Python 2.6 compatibility + code = compile(src, filename, 'exec') + exec(code, glob, glob) + + +def add_cffi_module(dist, mod_spec): + from cffi.api import FFI + + if not isinstance(mod_spec, basestring): + error("argument to 'cffi_modules=...' must be a str or a list of str," + " not %r" % (type(mod_spec).__name__,)) + mod_spec = str(mod_spec) + try: + build_file_name, ffi_var_name = mod_spec.split(':') + except ValueError: + error("%r must be of the form 'path/build.py:ffi_variable'" % + (mod_spec,)) + if not os.path.exists(build_file_name): + ext = '' + rewritten = build_file_name.replace('.', '/') + '.py' + if os.path.exists(rewritten): + ext = ' (rewrite cffi_modules to [%r])' % ( + rewritten + ':' + ffi_var_name,) + error("%r does not name an existing file%s" % (build_file_name, ext)) + + mod_vars = {'__name__': '__cffi__', '__file__': build_file_name} + execfile(build_file_name, mod_vars) + + try: + ffi = mod_vars[ffi_var_name] + except KeyError: + error("%r: object %r not found in module" % (mod_spec, + ffi_var_name)) + if not isinstance(ffi, FFI): + ffi = ffi() # maybe it's a function instead of directly an ffi + if not isinstance(ffi, FFI): + error("%r is not an FFI instance (got %r)" % (mod_spec, + type(ffi).__name__)) + if not hasattr(ffi, '_assigned_source'): + error("%r: the set_source() method was not called" % (mod_spec,)) + module_name, source, source_extension, kwds = ffi._assigned_source + if ffi._windows_unicode: + kwds = kwds.copy() + ffi._apply_windows_unicode(kwds) + + if source is None: + _add_py_module(dist, ffi, module_name) + else: + _add_c_module(dist, ffi, module_name, source, source_extension, kwds) + +def _set_py_limited_api(Extension, kwds): + """ + Add py_limited_api to kwds if setuptools >= 26 is in use. + Do not alter the setting if it already exists. + Setuptools takes care of ignoring the flag on Python 2 and PyPy. + + CPython itself should ignore the flag in a debugging version + (by not listing .abi3.so in the extensions it supports), but + it doesn't so far, creating troubles. That's why we check + for "not hasattr(sys, 'gettotalrefcount')" (the 2.7 compatible equivalent + of 'd' not in sys.abiflags). (http://bugs.python.org/issue28401) + + On Windows, with CPython <= 3.4, it's better not to use py_limited_api + because virtualenv *still* doesn't copy PYTHON3.DLL on these versions. + Recently (2020) we started shipping only >= 3.5 wheels, though. So + we'll give it another try and set py_limited_api on Windows >= 3.5. + """ + from cffi._shimmed_dist_utils import log + from cffi import recompiler + + if ('py_limited_api' not in kwds and not hasattr(sys, 'gettotalrefcount') + and recompiler.USE_LIMITED_API): + import setuptools + try: + setuptools_major_version = int(setuptools.__version__.partition('.')[0]) + if setuptools_major_version >= 26: + kwds['py_limited_api'] = True + except ValueError: # certain development versions of setuptools + # If we don't know the version number of setuptools, we + # try to set 'py_limited_api' anyway. At worst, we get a + # warning. + kwds['py_limited_api'] = True + + if sysconfig.get_config_var("Py_GIL_DISABLED"): + if kwds.get('py_limited_api'): + log.info("Ignoring py_limited_api=True for free-threaded build.") + + kwds['py_limited_api'] = False + + if kwds.get('py_limited_api') is False: + # avoid setting Py_LIMITED_API if py_limited_api=False + # which _cffi_include.h does unless _CFFI_NO_LIMITED_API is defined + kwds.setdefault("define_macros", []).append(("_CFFI_NO_LIMITED_API", None)) + return kwds + +def _add_c_module(dist, ffi, module_name, source, source_extension, kwds): + # We are a setuptools extension. Need this build_ext for py_limited_api. + from setuptools.command.build_ext import build_ext + from cffi._shimmed_dist_utils import Extension, log, mkpath + from cffi import recompiler + + allsources = ['$PLACEHOLDER'] + allsources.extend(kwds.pop('sources', [])) + kwds = _set_py_limited_api(Extension, kwds) + ext = Extension(name=module_name, sources=allsources, **kwds) + + def make_mod(tmpdir, pre_run=None): + c_file = os.path.join(tmpdir, module_name + source_extension) + log.info("generating cffi module %r" % c_file) + mkpath(tmpdir) + # a setuptools-only, API-only hook: called with the "ext" and "ffi" + # arguments just before we turn the ffi into C code. To use it, + # subclass the 'distutils.command.build_ext.build_ext' class and + # add a method 'def pre_run(self, ext, ffi)'. + if pre_run is not None: + pre_run(ext, ffi) + updated = recompiler.make_c_source(ffi, module_name, source, c_file) + if not updated: + log.info("already up-to-date") + return c_file + + if dist.ext_modules is None: + dist.ext_modules = [] + dist.ext_modules.append(ext) + + base_class = dist.cmdclass.get('build_ext', build_ext) + class build_ext_make_mod(base_class): + def run(self): + if ext.sources[0] == '$PLACEHOLDER': + pre_run = getattr(self, 'pre_run', None) + ext.sources[0] = make_mod(self.build_temp, pre_run) + base_class.run(self) + dist.cmdclass['build_ext'] = build_ext_make_mod + # NB. multiple runs here will create multiple 'build_ext_make_mod' + # classes. Even in this case the 'build_ext' command should be + # run once; but just in case, the logic above does nothing if + # called again. + + +def _add_py_module(dist, ffi, module_name): + from setuptools.command.build_py import build_py + from setuptools.command.build_ext import build_ext + from cffi._shimmed_dist_utils import log, mkpath + from cffi import recompiler + + def generate_mod(py_file): + log.info("generating cffi module %r" % py_file) + mkpath(os.path.dirname(py_file)) + updated = recompiler.make_py_source(ffi, module_name, py_file) + if not updated: + log.info("already up-to-date") + + base_class = dist.cmdclass.get('build_py', build_py) + class build_py_make_mod(base_class): + def run(self): + base_class.run(self) + module_path = module_name.split('.') + module_path[-1] += '.py' + generate_mod(os.path.join(self.build_lib, *module_path)) + def get_source_files(self): + # This is called from 'setup.py sdist' only. Exclude + # the generate .py module in this case. + saved_py_modules = self.py_modules + try: + if saved_py_modules: + self.py_modules = [m for m in saved_py_modules + if m != module_name] + return base_class.get_source_files(self) + finally: + self.py_modules = saved_py_modules + dist.cmdclass['build_py'] = build_py_make_mod + + # distutils and setuptools have no notion I could find of a + # generated python module. If we don't add module_name to + # dist.py_modules, then things mostly work but there are some + # combination of options (--root and --record) that will miss + # the module. So we add it here, which gives a few apparently + # harmless warnings about not finding the file outside the + # build directory. + # Then we need to hack more in get_source_files(); see above. + if dist.py_modules is None: + dist.py_modules = [] + dist.py_modules.append(module_name) + + # the following is only for "build_ext -i" + base_class_2 = dist.cmdclass.get('build_ext', build_ext) + class build_ext_make_mod(base_class_2): + def run(self): + base_class_2.run(self) + if self.inplace: + # from get_ext_fullpath() in distutils/command/build_ext.py + module_path = module_name.split('.') + package = '.'.join(module_path[:-1]) + build_py = self.get_finalized_command('build_py') + package_dir = build_py.get_package_dir(package) + file_name = module_path[-1] + '.py' + generate_mod(os.path.join(package_dir, file_name)) + dist.cmdclass['build_ext'] = build_ext_make_mod + +def cffi_modules(dist, attr, value): + assert attr == 'cffi_modules' + if isinstance(value, basestring): + value = [value] + + for cffi_module in value: + add_cffi_module(dist, cffi_module) diff --git a/miniconda3/lib/python3.13/site-packages/cffi/vengine_cpy.py b/miniconda3/lib/python3.13/site-packages/cffi/vengine_cpy.py new file mode 100644 index 0000000000000000000000000000000000000000..02e6a471d04e4cbf45eb7698aecd3355ecd32546 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/vengine_cpy.py @@ -0,0 +1,1087 @@ +# +# DEPRECATED: implementation for ffi.verify() +# +import sys +from . import model +from .error import VerificationError +from . import _imp_emulation as imp + + +class VCPythonEngine(object): + _class_key = 'x' + _gen_python_module = True + + def __init__(self, verifier): + self.verifier = verifier + self.ffi = verifier.ffi + self._struct_pending_verification = {} + self._types_of_builtin_functions = {} + + def patch_extension_kwds(self, kwds): + pass + + def find_module(self, module_name, path, so_suffixes): + try: + f, filename, descr = imp.find_module(module_name, path) + except ImportError: + return None + if f is not None: + f.close() + # Note that after a setuptools installation, there are both .py + # and .so files with the same basename. The code here relies on + # imp.find_module() locating the .so in priority. + if descr[0] not in so_suffixes: + return None + return filename + + def collect_types(self): + self._typesdict = {} + self._generate("collecttype") + + def _prnt(self, what=''): + self._f.write(what + '\n') + + def _gettypenum(self, type): + # a KeyError here is a bug. please report it! :-) + return self._typesdict[type] + + def _do_collect_type(self, tp): + if ((not isinstance(tp, model.PrimitiveType) + or tp.name == 'long double') + and tp not in self._typesdict): + num = len(self._typesdict) + self._typesdict[tp] = num + + def write_source_to_f(self): + self.collect_types() + # + # The new module will have a _cffi_setup() function that receives + # objects from the ffi world, and that calls some setup code in + # the module. This setup code is split in several independent + # functions, e.g. one per constant. The functions are "chained" + # by ending in a tail call to each other. + # + # This is further split in two chained lists, depending on if we + # can do it at import-time or if we must wait for _cffi_setup() to + # provide us with the objects. This is needed because we + # need the values of the enum constants in order to build the + # that we may have to pass to _cffi_setup(). + # + # The following two 'chained_list_constants' items contains + # the head of these two chained lists, as a string that gives the + # call to do, if any. + self._chained_list_constants = ['((void)lib,0)', '((void)lib,0)'] + # + prnt = self._prnt + # first paste some standard set of lines that are mostly '#define' + prnt(cffimod_header) + prnt() + # then paste the C source given by the user, verbatim. + prnt(self.verifier.preamble) + prnt() + # + # call generate_cpy_xxx_decl(), for every xxx found from + # ffi._parser._declarations. This generates all the functions. + self._generate("decl") + # + # implement the function _cffi_setup_custom() as calling the + # head of the chained list. + self._generate_setup_custom() + prnt() + # + # produce the method table, including the entries for the + # generated Python->C function wrappers, which are done + # by generate_cpy_function_method(). + prnt('static PyMethodDef _cffi_methods[] = {') + self._generate("method") + prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},') + prnt(' {NULL, NULL, 0, NULL} /* Sentinel */') + prnt('};') + prnt() + # + # standard init. + modname = self.verifier.get_module_name() + constants = self._chained_list_constants[False] + prnt('#if PY_MAJOR_VERSION >= 3') + prnt() + prnt('static struct PyModuleDef _cffi_module_def = {') + prnt(' PyModuleDef_HEAD_INIT,') + prnt(' "%s",' % modname) + prnt(' NULL,') + prnt(' -1,') + prnt(' _cffi_methods,') + prnt(' NULL, NULL, NULL, NULL') + prnt('};') + prnt() + prnt('PyMODINIT_FUNC') + prnt('PyInit_%s(void)' % modname) + prnt('{') + prnt(' PyObject *lib;') + prnt(' lib = PyModule_Create(&_cffi_module_def);') + prnt(' if (lib == NULL)') + prnt(' return NULL;') + prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,)) + prnt(' Py_DECREF(lib);') + prnt(' return NULL;') + prnt(' }') + prnt('#if Py_GIL_DISABLED') + prnt(' PyUnstable_Module_SetGIL(lib, Py_MOD_GIL_NOT_USED);') + prnt('#endif') + prnt(' return lib;') + prnt('}') + prnt() + prnt('#else') + prnt() + prnt('PyMODINIT_FUNC') + prnt('init%s(void)' % modname) + prnt('{') + prnt(' PyObject *lib;') + prnt(' lib = Py_InitModule("%s", _cffi_methods);' % modname) + prnt(' if (lib == NULL)') + prnt(' return;') + prnt(' if (%s < 0 || _cffi_init() < 0)' % (constants,)) + prnt(' return;') + prnt(' return;') + prnt('}') + prnt() + prnt('#endif') + + def load_library(self, flags=None): + # XXX review all usages of 'self' here! + # import it as a new extension module + imp.acquire_lock() + try: + if hasattr(sys, "getdlopenflags"): + previous_flags = sys.getdlopenflags() + try: + if hasattr(sys, "setdlopenflags") and flags is not None: + sys.setdlopenflags(flags) + module = imp.load_dynamic(self.verifier.get_module_name(), + self.verifier.modulefilename) + except ImportError as e: + error = "importing %r: %s" % (self.verifier.modulefilename, e) + raise VerificationError(error) + finally: + if hasattr(sys, "setdlopenflags"): + sys.setdlopenflags(previous_flags) + finally: + imp.release_lock() + # + # call loading_cpy_struct() to get the struct layout inferred by + # the C compiler + self._load(module, 'loading') + # + # the C code will need the objects. Collect them in + # order in a list. + revmapping = dict([(value, key) + for (key, value) in self._typesdict.items()]) + lst = [revmapping[i] for i in range(len(revmapping))] + lst = list(map(self.ffi._get_cached_btype, lst)) + # + # build the FFILibrary class and instance and call _cffi_setup(). + # this will set up some fields like '_cffi_types', and only then + # it will invoke the chained list of functions that will really + # build (notably) the constant objects, as if they are + # pointers, and store them as attributes on the 'library' object. + class FFILibrary(object): + _cffi_python_module = module + _cffi_ffi = self.ffi + _cffi_dir = [] + def __dir__(self): + return FFILibrary._cffi_dir + list(self.__dict__) + library = FFILibrary() + if module._cffi_setup(lst, VerificationError, library): + import warnings + warnings.warn("reimporting %r might overwrite older definitions" + % (self.verifier.get_module_name())) + # + # finally, call the loaded_cpy_xxx() functions. This will perform + # the final adjustments, like copying the Python->C wrapper + # functions from the module to the 'library' object, and setting + # up the FFILibrary class with properties for the global C variables. + self._load(module, 'loaded', library=library) + module._cffi_original_ffi = self.ffi + module._cffi_types_of_builtin_funcs = self._types_of_builtin_functions + return library + + def _get_declarations(self): + lst = [(key, tp) for (key, (tp, qual)) in + self.ffi._parser._declarations.items()] + lst.sort() + return lst + + def _generate(self, step_name): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + try: + method = getattr(self, '_generate_cpy_%s_%s' % (kind, + step_name)) + except AttributeError: + raise VerificationError( + "not implemented in verify(): %r" % name) + try: + method(tp, realname) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _load(self, module, step_name, **kwds): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + method = getattr(self, '_%s_cpy_%s' % (step_name, kind)) + try: + method(tp, realname, module, **kwds) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _generate_nothing(self, tp, name): + pass + + def _loaded_noop(self, tp, name, module, **kwds): + pass + + # ---------- + + def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode): + extraarg = '' + if isinstance(tp, model.PrimitiveType): + if tp.is_integer_type() and tp.name != '_Bool': + converter = '_cffi_to_c_int' + extraarg = ', %s' % tp.name + elif tp.is_complex_type(): + raise VerificationError( + "not implemented in verify(): complex types") + else: + converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''), + tp.name.replace(' ', '_')) + errvalue = '-1' + # + elif isinstance(tp, model.PointerType): + self._convert_funcarg_to_c_ptr_or_array(tp, fromvar, + tovar, errcode) + return + # + elif isinstance(tp, (model.StructOrUnion, model.EnumType)): + # a struct (not a struct pointer) as a function argument + self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)' + % (tovar, self._gettypenum(tp), fromvar)) + self._prnt(' %s;' % errcode) + return + # + elif isinstance(tp, model.FunctionPtrType): + converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('') + extraarg = ', _cffi_type(%d)' % self._gettypenum(tp) + errvalue = 'NULL' + # + else: + raise NotImplementedError(tp) + # + self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg)) + self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % ( + tovar, tp.get_c_name(''), errvalue)) + self._prnt(' %s;' % errcode) + + def _extra_local_variables(self, tp, localvars, freelines): + if isinstance(tp, model.PointerType): + localvars.add('Py_ssize_t datasize') + localvars.add('struct _cffi_freeme_s *large_args_free = NULL') + freelines.add('if (large_args_free != NULL)' + ' _cffi_free_array_arguments(large_args_free);') + + def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode): + self._prnt(' datasize = _cffi_prepare_pointer_call_argument(') + self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % ( + self._gettypenum(tp), fromvar, tovar)) + self._prnt(' if (datasize != 0) {') + self._prnt(' %s = ((size_t)datasize) <= 640 ? ' + 'alloca((size_t)datasize) : NULL;' % (tovar,)) + self._prnt(' if (_cffi_convert_array_argument(_cffi_type(%d), %s, ' + '(char **)&%s,' % (self._gettypenum(tp), fromvar, tovar)) + self._prnt(' datasize, &large_args_free) < 0)') + self._prnt(' %s;' % errcode) + self._prnt(' }') + + def _convert_expr_from_c(self, tp, var, context): + if isinstance(tp, model.PrimitiveType): + if tp.is_integer_type() and tp.name != '_Bool': + return '_cffi_from_c_int(%s, %s)' % (var, tp.name) + elif tp.name != 'long double': + return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var) + else: + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, (model.PointerType, model.FunctionPtrType)): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.ArrayType): + return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % ( + var, self._gettypenum(model.PointerType(tp.item))) + elif isinstance(tp, model.StructOrUnion): + if tp.fldnames is None: + raise TypeError("'%s' is used as %s, but is opaque" % ( + tp._get_c_name(), context)) + return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + elif isinstance(tp, model.EnumType): + return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % ( + var, self._gettypenum(tp)) + else: + raise NotImplementedError(tp) + + # ---------- + # typedefs: generates no code so far + + _generate_cpy_typedef_collecttype = _generate_nothing + _generate_cpy_typedef_decl = _generate_nothing + _generate_cpy_typedef_method = _generate_nothing + _loading_cpy_typedef = _loaded_noop + _loaded_cpy_typedef = _loaded_noop + + # ---------- + # function declarations + + def _generate_cpy_function_collecttype(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + self._do_collect_type(tp) + else: + # don't call _do_collect_type(tp) in this common case, + # otherwise test_autofilled_struct_as_argument fails + for type in tp.args: + self._do_collect_type(type) + self._do_collect_type(tp.result) + + def _generate_cpy_function_decl(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + # cannot support vararg functions better than this: check for its + # exact type (including the fixed arguments), and build it as a + # constant function pointer (no CPython wrapper) + self._generate_cpy_const(False, name, tp) + return + prnt = self._prnt + numargs = len(tp.args) + if numargs == 0: + argname = 'noarg' + elif numargs == 1: + argname = 'arg0' + else: + argname = 'args' + prnt('static PyObject *') + prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname)) + prnt('{') + # + context = 'argument of %s' % name + for i, type in enumerate(tp.args): + prnt(' %s;' % type.get_c_name(' x%d' % i, context)) + # + localvars = set() + freelines = set() + for type in tp.args: + self._extra_local_variables(type, localvars, freelines) + for decl in sorted(localvars): + prnt(' %s;' % (decl,)) + # + if not isinstance(tp.result, model.VoidType): + result_code = 'result = ' + context = 'result of %s' % name + prnt(' %s;' % tp.result.get_c_name(' result', context)) + prnt(' PyObject *pyresult;') + else: + result_code = '' + # + if len(tp.args) > 1: + rng = range(len(tp.args)) + for i in rng: + prnt(' PyObject *arg%d;' % i) + prnt() + prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % ( + 'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng]))) + prnt(' return NULL;') + prnt() + # + for i, type in enumerate(tp.args): + self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i, + 'return NULL') + prnt() + # + prnt(' Py_BEGIN_ALLOW_THREADS') + prnt(' _cffi_restore_errno();') + prnt(' { %s%s(%s); }' % ( + result_code, name, + ', '.join(['x%d' % i for i in range(len(tp.args))]))) + prnt(' _cffi_save_errno();') + prnt(' Py_END_ALLOW_THREADS') + prnt() + # + prnt(' (void)self; /* unused */') + if numargs == 0: + prnt(' (void)noarg; /* unused */') + if result_code: + prnt(' pyresult = %s;' % + self._convert_expr_from_c(tp.result, 'result', 'result type')) + for freeline in freelines: + prnt(' ' + freeline) + prnt(' return pyresult;') + else: + for freeline in freelines: + prnt(' ' + freeline) + prnt(' Py_INCREF(Py_None);') + prnt(' return Py_None;') + prnt('}') + prnt() + + def _generate_cpy_function_method(self, tp, name): + if tp.ellipsis: + return + numargs = len(tp.args) + if numargs == 0: + meth = 'METH_NOARGS' + elif numargs == 1: + meth = 'METH_O' + else: + meth = 'METH_VARARGS' + self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth)) + + _loading_cpy_function = _loaded_noop + + def _loaded_cpy_function(self, tp, name, module, library): + if tp.ellipsis: + return + func = getattr(module, name) + setattr(library, name, func) + self._types_of_builtin_functions[func] = tp + + # ---------- + # named structs + + _generate_cpy_struct_collecttype = _generate_nothing + def _generate_cpy_struct_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'struct', name) + def _generate_cpy_struct_method(self, tp, name): + self._generate_struct_or_union_method(tp, 'struct', name) + def _loading_cpy_struct(self, tp, name, module): + self._loading_struct_or_union(tp, 'struct', name, module) + def _loaded_cpy_struct(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + _generate_cpy_union_collecttype = _generate_nothing + def _generate_cpy_union_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'union', name) + def _generate_cpy_union_method(self, tp, name): + self._generate_struct_or_union_method(tp, 'union', name) + def _loading_cpy_union(self, tp, name, module): + self._loading_struct_or_union(tp, 'union', name, module) + def _loaded_cpy_union(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + def _generate_struct_or_union_decl(self, tp, prefix, name): + if tp.fldnames is None: + return # nothing to do with opaque structs + checkfuncname = '_cffi_check_%s_%s' % (prefix, name) + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + cname = ('%s %s' % (prefix, name)).strip() + # + prnt = self._prnt + prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt('{') + prnt(' /* only to generate compile-time warnings or errors */') + prnt(' (void)p;') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if (isinstance(ftype, model.PrimitiveType) + and ftype.is_integer_type()) or fbitsize >= 0: + # accept all integers, but complain on float or double + prnt(' (void)((p->%s) << 1);' % fname) + else: + # only accept exactly the type declared. + try: + prnt(' { %s = &p->%s; (void)tmp; }' % ( + ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + fname)) + except VerificationError as e: + prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt('}') + prnt('static PyObject *') + prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,)) + prnt('{') + prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) + prnt(' static Py_ssize_t nums[] = {') + prnt(' sizeof(%s),' % cname) + prnt(' offsetof(struct _cffi_aligncheck, y),') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + prnt(' offsetof(%s, %s),' % (cname, fname)) + if isinstance(ftype, model.ArrayType) and ftype.length is None: + prnt(' 0, /* %s */' % ftype._get_c_name()) + else: + prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) + prnt(' -1') + prnt(' };') + prnt(' (void)self; /* unused */') + prnt(' (void)noarg; /* unused */') + prnt(' return _cffi_get_struct_layout(nums);') + prnt(' /* the next line is not executed, but compiled */') + prnt(' %s(0);' % (checkfuncname,)) + prnt('}') + prnt() + + def _generate_struct_or_union_method(self, tp, prefix, name): + if tp.fldnames is None: + return # nothing to do with opaque structs + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname, + layoutfuncname)) + + def _loading_struct_or_union(self, tp, prefix, name, module): + if tp.fldnames is None: + return # nothing to do with opaque structs + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + # + function = getattr(module, layoutfuncname) + layout = function() + if isinstance(tp, model.StructOrUnion) and tp.partial: + # use the function()'s sizes and offsets to guide the + # layout of the struct + totalsize = layout[0] + totalalignment = layout[1] + fieldofs = layout[2::2] + fieldsize = layout[3::2] + tp.force_flatten() + assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) + tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment + else: + cname = ('%s %s' % (prefix, name)).strip() + self._struct_pending_verification[tp] = layout, cname + + def _loaded_struct_or_union(self, tp): + if tp.fldnames is None: + return # nothing to do with opaque structs + self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered + + if tp in self._struct_pending_verification: + # check that the layout sizes and offsets match the real ones + def check(realvalue, expectedvalue, msg): + if realvalue != expectedvalue: + raise VerificationError( + "%s (we have %d, but C compiler says %d)" + % (msg, expectedvalue, realvalue)) + ffi = self.ffi + BStruct = ffi._get_cached_btype(tp) + layout, cname = self._struct_pending_verification.pop(tp) + check(layout[0], ffi.sizeof(BStruct), "wrong total size") + check(layout[1], ffi.alignof(BStruct), "wrong total alignment") + i = 2 + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + check(layout[i], ffi.offsetof(BStruct, fname), + "wrong offset for field %r" % (fname,)) + if layout[i+1] != 0: + BField = ffi._get_cached_btype(ftype) + check(layout[i+1], ffi.sizeof(BField), + "wrong size for field %r" % (fname,)) + i += 2 + assert i == len(layout) + + # ---------- + # 'anonymous' declarations. These are produced for anonymous structs + # or unions; the 'name' is obtained by a typedef. + + _generate_cpy_anonymous_collecttype = _generate_nothing + + def _generate_cpy_anonymous_decl(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_cpy_enum_decl(tp, name, '') + else: + self._generate_struct_or_union_decl(tp, '', name) + + def _generate_cpy_anonymous_method(self, tp, name): + if not isinstance(tp, model.EnumType): + self._generate_struct_or_union_method(tp, '', name) + + def _loading_cpy_anonymous(self, tp, name, module): + if isinstance(tp, model.EnumType): + self._loading_cpy_enum(tp, name, module) + else: + self._loading_struct_or_union(tp, '', name, module) + + def _loaded_cpy_anonymous(self, tp, name, module, **kwds): + if isinstance(tp, model.EnumType): + self._loaded_cpy_enum(tp, name, module, **kwds) + else: + self._loaded_struct_or_union(tp) + + # ---------- + # constants, likely declared with '#define' + + def _generate_cpy_const(self, is_int, name, tp=None, category='const', + vartp=None, delayed=True, size_too=False, + check_value=None): + prnt = self._prnt + funcname = '_cffi_%s_%s' % (category, name) + prnt('static int %s(PyObject *lib)' % funcname) + prnt('{') + prnt(' PyObject *o;') + prnt(' int res;') + if not is_int: + prnt(' %s;' % (vartp or tp).get_c_name(' i', name)) + else: + assert category == 'const' + # + if check_value is not None: + self._check_int_constant_value(name, check_value) + # + if not is_int: + if category == 'var': + realexpr = '&' + name + else: + realexpr = name + prnt(' i = (%s);' % (realexpr,)) + prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i', + 'variable type'),)) + assert delayed + else: + prnt(' o = _cffi_from_c_int_const(%s);' % name) + prnt(' if (o == NULL)') + prnt(' return -1;') + if size_too: + prnt(' {') + prnt(' PyObject *o1 = o;') + prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));' + % (name,)) + prnt(' Py_DECREF(o1);') + prnt(' if (o == NULL)') + prnt(' return -1;') + prnt(' }') + prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name) + prnt(' Py_DECREF(o);') + prnt(' if (res < 0)') + prnt(' return -1;') + prnt(' return %s;' % self._chained_list_constants[delayed]) + self._chained_list_constants[delayed] = funcname + '(lib)' + prnt('}') + prnt() + + def _generate_cpy_constant_collecttype(self, tp, name): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + if not is_int: + self._do_collect_type(tp) + + def _generate_cpy_constant_decl(self, tp, name): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + self._generate_cpy_const(is_int, name, tp) + + _generate_cpy_constant_method = _generate_nothing + _loading_cpy_constant = _loaded_noop + _loaded_cpy_constant = _loaded_noop + + # ---------- + # enums + + def _check_int_constant_value(self, name, value, err_prefix=''): + prnt = self._prnt + if value <= 0: + prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % ( + name, name, value)) + else: + prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( + name, name, value)) + prnt(' char buf[64];') + prnt(' if ((%s) <= 0)' % name) + prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name) + prnt(' else') + prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' % + name) + prnt(' PyErr_Format(_cffi_VerificationError,') + prnt(' "%s%s has the real value %s, not %s",') + prnt(' "%s", "%s", buf, "%d");' % ( + err_prefix, name, value)) + prnt(' return -1;') + prnt(' }') + + def _enum_funcname(self, prefix, name): + # "$enum_$1" => "___D_enum____D_1" + name = name.replace('$', '___D_') + return '_cffi_e_%s_%s' % (prefix, name) + + def _generate_cpy_enum_decl(self, tp, name, prefix='enum'): + if tp.partial: + for enumerator in tp.enumerators: + self._generate_cpy_const(True, enumerator, delayed=False) + return + # + funcname = self._enum_funcname(prefix, name) + prnt = self._prnt + prnt('static int %s(PyObject *lib)' % funcname) + prnt('{') + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + self._check_int_constant_value(enumerator, enumvalue, + "enum %s: " % name) + prnt(' return %s;' % self._chained_list_constants[True]) + self._chained_list_constants[True] = funcname + '(lib)' + prnt('}') + prnt() + + _generate_cpy_enum_collecttype = _generate_nothing + _generate_cpy_enum_method = _generate_nothing + + def _loading_cpy_enum(self, tp, name, module): + if tp.partial: + enumvalues = [getattr(module, enumerator) + for enumerator in tp.enumerators] + tp.enumvalues = tuple(enumvalues) + tp.partial_resolved = True + + def _loaded_cpy_enum(self, tp, name, module, library): + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + setattr(library, enumerator, enumvalue) + + # ---------- + # macros: for now only for integers + + def _generate_cpy_macro_decl(self, tp, name): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + self._generate_cpy_const(True, name, check_value=check_value) + + _generate_cpy_macro_collecttype = _generate_nothing + _generate_cpy_macro_method = _generate_nothing + _loading_cpy_macro = _loaded_noop + _loaded_cpy_macro = _loaded_noop + + # ---------- + # global variables + + def _generate_cpy_variable_collecttype(self, tp, name): + if isinstance(tp, model.ArrayType): + tp_ptr = model.PointerType(tp.item) + else: + tp_ptr = model.PointerType(tp) + self._do_collect_type(tp_ptr) + + def _generate_cpy_variable_decl(self, tp, name): + if isinstance(tp, model.ArrayType): + tp_ptr = model.PointerType(tp.item) + self._generate_cpy_const(False, name, tp, vartp=tp_ptr, + size_too = tp.length_is_unknown()) + else: + tp_ptr = model.PointerType(tp) + self._generate_cpy_const(False, name, tp_ptr, category='var') + + _generate_cpy_variable_method = _generate_nothing + _loading_cpy_variable = _loaded_noop + + def _loaded_cpy_variable(self, tp, name, module, library): + value = getattr(library, name) + if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the + # sense that "a=..." is forbidden + if tp.length_is_unknown(): + assert isinstance(value, tuple) + (value, size) = value + BItemType = self.ffi._get_cached_btype(tp.item) + length, rest = divmod(size, self.ffi.sizeof(BItemType)) + if rest != 0: + raise VerificationError( + "bad size: %r does not seem to be an array of %s" % + (name, tp.item)) + tp = tp.resolve_length(length) + # 'value' is a which we have to replace with + # a if the N is actually known + if tp.length is not None: + BArray = self.ffi._get_cached_btype(tp) + value = self.ffi.cast(BArray, value) + setattr(library, name, value) + return + # remove ptr= from the library instance, and replace + # it by a property on the class, which reads/writes into ptr[0]. + ptr = value + delattr(library, name) + def getter(library): + return ptr[0] + def setter(library, value): + ptr[0] = value + setattr(type(library), name, property(getter, setter)) + type(library)._cffi_dir.append(name) + + # ---------- + + def _generate_setup_custom(self): + prnt = self._prnt + prnt('static int _cffi_setup_custom(PyObject *lib)') + prnt('{') + prnt(' return %s;' % self._chained_list_constants[True]) + prnt('}') + +cffimod_header = r''' +#include +#include + +/* this block of #ifs should be kept exactly identical between + c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py + and cffi/_cffi_include.h */ +#if defined(_MSC_VER) +# include /* for alloca() */ +# if _MSC_VER < 1600 /* MSVC < 2010 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; + typedef __int8 int_least8_t; + typedef __int16 int_least16_t; + typedef __int32 int_least32_t; + typedef __int64 int_least64_t; + typedef unsigned __int8 uint_least8_t; + typedef unsigned __int16 uint_least16_t; + typedef unsigned __int32 uint_least32_t; + typedef unsigned __int64 uint_least64_t; + typedef __int8 int_fast8_t; + typedef __int16 int_fast16_t; + typedef __int32 int_fast32_t; + typedef __int64 int_fast64_t; + typedef unsigned __int8 uint_fast8_t; + typedef unsigned __int16 uint_fast16_t; + typedef unsigned __int32 uint_fast32_t; + typedef unsigned __int64 uint_fast64_t; + typedef __int64 intmax_t; + typedef unsigned __int64 uintmax_t; +# else +# include +# endif +# if _MSC_VER < 1800 /* MSVC < 2013 */ +# ifndef __cplusplus + typedef unsigned char _Bool; +# endif +# endif +# define _cffi_float_complex_t _Fcomplex /* include for it */ +# define _cffi_double_complex_t _Dcomplex /* include for it */ +#else +# include +# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) +# include +# endif +# define _cffi_float_complex_t float _Complex +# define _cffi_double_complex_t double _Complex +#endif + +#if PY_MAJOR_VERSION < 3 +# undef PyCapsule_CheckExact +# undef PyCapsule_GetPointer +# define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule)) +# define PyCapsule_GetPointer(capsule, name) \ + (PyCObject_AsVoidPtr(capsule)) +#endif + +#if PY_MAJOR_VERSION >= 3 +# define PyInt_FromLong PyLong_FromLong +#endif + +#define _cffi_from_c_double PyFloat_FromDouble +#define _cffi_from_c_float PyFloat_FromDouble +#define _cffi_from_c_long PyInt_FromLong +#define _cffi_from_c_ulong PyLong_FromUnsignedLong +#define _cffi_from_c_longlong PyLong_FromLongLong +#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong +#define _cffi_from_c__Bool PyBool_FromLong + +#define _cffi_to_c_double PyFloat_AsDouble +#define _cffi_to_c_float PyFloat_AsDouble + +#define _cffi_from_c_int_const(x) \ + (((x) > 0) ? \ + ((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \ + PyInt_FromLong((long)(x)) : \ + PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \ + ((long long)(x) >= (long long)LONG_MIN) ? \ + PyInt_FromLong((long)(x)) : \ + PyLong_FromLongLong((long long)(x))) + +#define _cffi_from_c_int(x, type) \ + (((type)-1) > 0 ? /* unsigned */ \ + (sizeof(type) < sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + sizeof(type) == sizeof(long) ? \ + PyLong_FromUnsignedLong((unsigned long)x) : \ + PyLong_FromUnsignedLongLong((unsigned long long)x)) : \ + (sizeof(type) <= sizeof(long) ? \ + PyInt_FromLong((long)x) : \ + PyLong_FromLongLong((long long)x))) + +#define _cffi_to_c_int(o, type) \ + ((type)( \ + sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \ + : (type)_cffi_to_c_i8(o)) : \ + sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \ + : (type)_cffi_to_c_i16(o)) : \ + sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \ + : (type)_cffi_to_c_i32(o)) : \ + sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \ + : (type)_cffi_to_c_i64(o)) : \ + (Py_FatalError("unsupported size for type " #type), (type)0))) + +#define _cffi_to_c_i8 \ + ((int(*)(PyObject *))_cffi_exports[1]) +#define _cffi_to_c_u8 \ + ((int(*)(PyObject *))_cffi_exports[2]) +#define _cffi_to_c_i16 \ + ((int(*)(PyObject *))_cffi_exports[3]) +#define _cffi_to_c_u16 \ + ((int(*)(PyObject *))_cffi_exports[4]) +#define _cffi_to_c_i32 \ + ((int(*)(PyObject *))_cffi_exports[5]) +#define _cffi_to_c_u32 \ + ((unsigned int(*)(PyObject *))_cffi_exports[6]) +#define _cffi_to_c_i64 \ + ((long long(*)(PyObject *))_cffi_exports[7]) +#define _cffi_to_c_u64 \ + ((unsigned long long(*)(PyObject *))_cffi_exports[8]) +#define _cffi_to_c_char \ + ((int(*)(PyObject *))_cffi_exports[9]) +#define _cffi_from_c_pointer \ + ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10]) +#define _cffi_to_c_pointer \ + ((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11]) +#define _cffi_get_struct_layout \ + ((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12]) +#define _cffi_restore_errno \ + ((void(*)(void))_cffi_exports[13]) +#define _cffi_save_errno \ + ((void(*)(void))_cffi_exports[14]) +#define _cffi_from_c_char \ + ((PyObject *(*)(char))_cffi_exports[15]) +#define _cffi_from_c_deref \ + ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16]) +#define _cffi_to_c \ + ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17]) +#define _cffi_from_c_struct \ + ((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18]) +#define _cffi_to_c_wchar_t \ + ((wchar_t(*)(PyObject *))_cffi_exports[19]) +#define _cffi_from_c_wchar_t \ + ((PyObject *(*)(wchar_t))_cffi_exports[20]) +#define _cffi_to_c_long_double \ + ((long double(*)(PyObject *))_cffi_exports[21]) +#define _cffi_to_c__Bool \ + ((_Bool(*)(PyObject *))_cffi_exports[22]) +#define _cffi_prepare_pointer_call_argument \ + ((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23]) +#define _cffi_convert_array_from_object \ + ((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24]) +#define _CFFI_NUM_EXPORTS 25 + +typedef struct _ctypedescr CTypeDescrObject; + +static void *_cffi_exports[_CFFI_NUM_EXPORTS]; +static PyObject *_cffi_types, *_cffi_VerificationError; + +static int _cffi_setup_custom(PyObject *lib); /* forward */ + +static PyObject *_cffi_setup(PyObject *self, PyObject *args) +{ + PyObject *library; + int was_alive = (_cffi_types != NULL); + (void)self; /* unused */ + if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError, + &library)) + return NULL; + Py_INCREF(_cffi_types); + Py_INCREF(_cffi_VerificationError); + if (_cffi_setup_custom(library) < 0) + return NULL; + return PyBool_FromLong(was_alive); +} + +union _cffi_union_alignment_u { + unsigned char m_char; + unsigned short m_short; + unsigned int m_int; + unsigned long m_long; + unsigned long long m_longlong; + float m_float; + double m_double; + long double m_longdouble; +}; + +struct _cffi_freeme_s { + struct _cffi_freeme_s *next; + union _cffi_union_alignment_u alignment; +}; + +#ifdef __GNUC__ + __attribute__((unused)) +#endif +static int _cffi_convert_array_argument(CTypeDescrObject *ctptr, PyObject *arg, + char **output_data, Py_ssize_t datasize, + struct _cffi_freeme_s **freeme) +{ + char *p; + if (datasize < 0) + return -1; + + p = *output_data; + if (p == NULL) { + struct _cffi_freeme_s *fp = (struct _cffi_freeme_s *)PyObject_Malloc( + offsetof(struct _cffi_freeme_s, alignment) + (size_t)datasize); + if (fp == NULL) + return -1; + fp->next = *freeme; + *freeme = fp; + p = *output_data = (char *)&fp->alignment; + } + memset((void *)p, 0, (size_t)datasize); + return _cffi_convert_array_from_object(p, ctptr, arg); +} + +#ifdef __GNUC__ + __attribute__((unused)) +#endif +static void _cffi_free_array_arguments(struct _cffi_freeme_s *freeme) +{ + do { + void *p = (void *)freeme; + freeme = freeme->next; + PyObject_Free(p); + } while (freeme != NULL); +} + +static int _cffi_init(void) +{ + PyObject *module, *c_api_object = NULL; + + module = PyImport_ImportModule("_cffi_backend"); + if (module == NULL) + goto failure; + + c_api_object = PyObject_GetAttrString(module, "_C_API"); + if (c_api_object == NULL) + goto failure; + if (!PyCapsule_CheckExact(c_api_object)) { + PyErr_SetNone(PyExc_ImportError); + goto failure; + } + memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"), + _CFFI_NUM_EXPORTS * sizeof(void *)); + + Py_DECREF(module); + Py_DECREF(c_api_object); + return 0; + + failure: + Py_XDECREF(module); + Py_XDECREF(c_api_object); + return -1; +} + +#define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num)) + +/**********/ +''' diff --git a/miniconda3/lib/python3.13/site-packages/cffi/vengine_gen.py b/miniconda3/lib/python3.13/site-packages/cffi/vengine_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..bffc82122c353fbd15a395d77e829a95bf8546b0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/vengine_gen.py @@ -0,0 +1,679 @@ +# +# DEPRECATED: implementation for ffi.verify() +# +import sys, os +import types + +from . import model +from .error import VerificationError + + +class VGenericEngine(object): + _class_key = 'g' + _gen_python_module = False + + def __init__(self, verifier): + self.verifier = verifier + self.ffi = verifier.ffi + self.export_symbols = [] + self._struct_pending_verification = {} + + def patch_extension_kwds(self, kwds): + # add 'export_symbols' to the dictionary. Note that we add the + # list before filling it. When we fill it, it will thus also show + # up in kwds['export_symbols']. + kwds.setdefault('export_symbols', self.export_symbols) + + def find_module(self, module_name, path, so_suffixes): + for so_suffix in so_suffixes: + basename = module_name + so_suffix + if path is None: + path = sys.path + for dirname in path: + filename = os.path.join(dirname, basename) + if os.path.isfile(filename): + return filename + + def collect_types(self): + pass # not needed in the generic engine + + def _prnt(self, what=''): + self._f.write(what + '\n') + + def write_source_to_f(self): + prnt = self._prnt + # first paste some standard set of lines that are mostly '#include' + prnt(cffimod_header) + # then paste the C source given by the user, verbatim. + prnt(self.verifier.preamble) + # + # call generate_gen_xxx_decl(), for every xxx found from + # ffi._parser._declarations. This generates all the functions. + self._generate('decl') + # + # on Windows, distutils insists on putting init_cffi_xyz in + # 'export_symbols', so instead of fighting it, just give up and + # give it one + if sys.platform == 'win32': + if sys.version_info >= (3,): + prefix = 'PyInit_' + else: + prefix = 'init' + modname = self.verifier.get_module_name() + prnt("void %s%s(void) { }\n" % (prefix, modname)) + + def load_library(self, flags=0): + # import it with the CFFI backend + backend = self.ffi._backend + # needs to make a path that contains '/', on Posix + filename = os.path.join(os.curdir, self.verifier.modulefilename) + module = backend.load_library(filename, flags) + # + # call loading_gen_struct() to get the struct layout inferred by + # the C compiler + self._load(module, 'loading') + + # build the FFILibrary class and instance, this is a module subclass + # because modules are expected to have usually-constant-attributes and + # in PyPy this means the JIT is able to treat attributes as constant, + # which we want. + class FFILibrary(types.ModuleType): + _cffi_generic_module = module + _cffi_ffi = self.ffi + _cffi_dir = [] + def __dir__(self): + return FFILibrary._cffi_dir + library = FFILibrary("") + # + # finally, call the loaded_gen_xxx() functions. This will set + # up the 'library' object. + self._load(module, 'loaded', library=library) + return library + + def _get_declarations(self): + lst = [(key, tp) for (key, (tp, qual)) in + self.ffi._parser._declarations.items()] + lst.sort() + return lst + + def _generate(self, step_name): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + try: + method = getattr(self, '_generate_gen_%s_%s' % (kind, + step_name)) + except AttributeError: + raise VerificationError( + "not implemented in verify(): %r" % name) + try: + method(tp, realname) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _load(self, module, step_name, **kwds): + for name, tp in self._get_declarations(): + kind, realname = name.split(' ', 1) + method = getattr(self, '_%s_gen_%s' % (step_name, kind)) + try: + method(tp, realname, module, **kwds) + except Exception as e: + model.attach_exception_info(e, name) + raise + + def _generate_nothing(self, tp, name): + pass + + def _loaded_noop(self, tp, name, module, **kwds): + pass + + # ---------- + # typedefs: generates no code so far + + _generate_gen_typedef_decl = _generate_nothing + _loading_gen_typedef = _loaded_noop + _loaded_gen_typedef = _loaded_noop + + # ---------- + # function declarations + + def _generate_gen_function_decl(self, tp, name): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + # cannot support vararg functions better than this: check for its + # exact type (including the fixed arguments), and build it as a + # constant function pointer (no _cffi_f_%s wrapper) + self._generate_gen_const(False, name, tp) + return + prnt = self._prnt + numargs = len(tp.args) + argnames = [] + for i, type in enumerate(tp.args): + indirection = '' + if isinstance(type, model.StructOrUnion): + indirection = '*' + argnames.append('%sx%d' % (indirection, i)) + context = 'argument of %s' % name + arglist = [type.get_c_name(' %s' % arg, context) + for type, arg in zip(tp.args, argnames)] + tpresult = tp.result + if isinstance(tpresult, model.StructOrUnion): + arglist.insert(0, tpresult.get_c_name(' *r', context)) + tpresult = model.void_type + arglist = ', '.join(arglist) or 'void' + wrappername = '_cffi_f_%s' % name + self.export_symbols.append(wrappername) + if tp.abi: + abi = tp.abi + ' ' + else: + abi = '' + funcdecl = ' %s%s(%s)' % (abi, wrappername, arglist) + context = 'result of %s' % name + prnt(tpresult.get_c_name(funcdecl, context)) + prnt('{') + # + if isinstance(tp.result, model.StructOrUnion): + result_code = '*r = ' + elif not isinstance(tp.result, model.VoidType): + result_code = 'return ' + else: + result_code = '' + prnt(' %s%s(%s);' % (result_code, name, ', '.join(argnames))) + prnt('}') + prnt() + + _loading_gen_function = _loaded_noop + + def _loaded_gen_function(self, tp, name, module, library): + assert isinstance(tp, model.FunctionPtrType) + if tp.ellipsis: + newfunction = self._load_constant(False, tp, name, module) + else: + indirections = [] + base_tp = tp + if (any(isinstance(typ, model.StructOrUnion) for typ in tp.args) + or isinstance(tp.result, model.StructOrUnion)): + indirect_args = [] + for i, typ in enumerate(tp.args): + if isinstance(typ, model.StructOrUnion): + typ = model.PointerType(typ) + indirections.append((i, typ)) + indirect_args.append(typ) + indirect_result = tp.result + if isinstance(indirect_result, model.StructOrUnion): + if indirect_result.fldtypes is None: + raise TypeError("'%s' is used as result type, " + "but is opaque" % ( + indirect_result._get_c_name(),)) + indirect_result = model.PointerType(indirect_result) + indirect_args.insert(0, indirect_result) + indirections.insert(0, ("result", indirect_result)) + indirect_result = model.void_type + tp = model.FunctionPtrType(tuple(indirect_args), + indirect_result, tp.ellipsis) + BFunc = self.ffi._get_cached_btype(tp) + wrappername = '_cffi_f_%s' % name + newfunction = module.load_function(BFunc, wrappername) + for i, typ in indirections: + newfunction = self._make_struct_wrapper(newfunction, i, typ, + base_tp) + setattr(library, name, newfunction) + type(library)._cffi_dir.append(name) + + def _make_struct_wrapper(self, oldfunc, i, tp, base_tp): + backend = self.ffi._backend + BType = self.ffi._get_cached_btype(tp) + if i == "result": + ffi = self.ffi + def newfunc(*args): + res = ffi.new(BType) + oldfunc(res, *args) + return res[0] + else: + def newfunc(*args): + args = args[:i] + (backend.newp(BType, args[i]),) + args[i+1:] + return oldfunc(*args) + newfunc._cffi_base_type = base_tp + return newfunc + + # ---------- + # named structs + + def _generate_gen_struct_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'struct', name) + + def _loading_gen_struct(self, tp, name, module): + self._loading_struct_or_union(tp, 'struct', name, module) + + def _loaded_gen_struct(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + def _generate_gen_union_decl(self, tp, name): + assert name == tp.name + self._generate_struct_or_union_decl(tp, 'union', name) + + def _loading_gen_union(self, tp, name, module): + self._loading_struct_or_union(tp, 'union', name, module) + + def _loaded_gen_union(self, tp, name, module, **kwds): + self._loaded_struct_or_union(tp) + + def _generate_struct_or_union_decl(self, tp, prefix, name): + if tp.fldnames is None: + return # nothing to do with opaque structs + checkfuncname = '_cffi_check_%s_%s' % (prefix, name) + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + cname = ('%s %s' % (prefix, name)).strip() + # + prnt = self._prnt + prnt('static void %s(%s *p)' % (checkfuncname, cname)) + prnt('{') + prnt(' /* only to generate compile-time warnings or errors */') + prnt(' (void)p;') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if (isinstance(ftype, model.PrimitiveType) + and ftype.is_integer_type()) or fbitsize >= 0: + # accept all integers, but complain on float or double + prnt(' (void)((p->%s) << 1);' % fname) + else: + # only accept exactly the type declared. + try: + prnt(' { %s = &p->%s; (void)tmp; }' % ( + ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual), + fname)) + except VerificationError as e: + prnt(' /* %s */' % str(e)) # cannot verify it, ignore + prnt('}') + self.export_symbols.append(layoutfuncname) + prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,)) + prnt('{') + prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname) + prnt(' static intptr_t nums[] = {') + prnt(' sizeof(%s),' % cname) + prnt(' offsetof(struct _cffi_aligncheck, y),') + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + prnt(' offsetof(%s, %s),' % (cname, fname)) + if isinstance(ftype, model.ArrayType) and ftype.length is None: + prnt(' 0, /* %s */' % ftype._get_c_name()) + else: + prnt(' sizeof(((%s *)0)->%s),' % (cname, fname)) + prnt(' -1') + prnt(' };') + prnt(' return nums[i];') + prnt(' /* the next line is not executed, but compiled */') + prnt(' %s(0);' % (checkfuncname,)) + prnt('}') + prnt() + + def _loading_struct_or_union(self, tp, prefix, name, module): + if tp.fldnames is None: + return # nothing to do with opaque structs + layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name) + # + BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0] + function = module.load_function(BFunc, layoutfuncname) + layout = [] + num = 0 + while True: + x = function(num) + if x < 0: break + layout.append(x) + num += 1 + if isinstance(tp, model.StructOrUnion) and tp.partial: + # use the function()'s sizes and offsets to guide the + # layout of the struct + totalsize = layout[0] + totalalignment = layout[1] + fieldofs = layout[2::2] + fieldsize = layout[3::2] + tp.force_flatten() + assert len(fieldofs) == len(fieldsize) == len(tp.fldnames) + tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment + else: + cname = ('%s %s' % (prefix, name)).strip() + self._struct_pending_verification[tp] = layout, cname + + def _loaded_struct_or_union(self, tp): + if tp.fldnames is None: + return # nothing to do with opaque structs + self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered + + if tp in self._struct_pending_verification: + # check that the layout sizes and offsets match the real ones + def check(realvalue, expectedvalue, msg): + if realvalue != expectedvalue: + raise VerificationError( + "%s (we have %d, but C compiler says %d)" + % (msg, expectedvalue, realvalue)) + ffi = self.ffi + BStruct = ffi._get_cached_btype(tp) + layout, cname = self._struct_pending_verification.pop(tp) + check(layout[0], ffi.sizeof(BStruct), "wrong total size") + check(layout[1], ffi.alignof(BStruct), "wrong total alignment") + i = 2 + for fname, ftype, fbitsize, fqual in tp.enumfields(): + if fbitsize >= 0: + continue # xxx ignore fbitsize for now + check(layout[i], ffi.offsetof(BStruct, fname), + "wrong offset for field %r" % (fname,)) + if layout[i+1] != 0: + BField = ffi._get_cached_btype(ftype) + check(layout[i+1], ffi.sizeof(BField), + "wrong size for field %r" % (fname,)) + i += 2 + assert i == len(layout) + + # ---------- + # 'anonymous' declarations. These are produced for anonymous structs + # or unions; the 'name' is obtained by a typedef. + + def _generate_gen_anonymous_decl(self, tp, name): + if isinstance(tp, model.EnumType): + self._generate_gen_enum_decl(tp, name, '') + else: + self._generate_struct_or_union_decl(tp, '', name) + + def _loading_gen_anonymous(self, tp, name, module): + if isinstance(tp, model.EnumType): + self._loading_gen_enum(tp, name, module, '') + else: + self._loading_struct_or_union(tp, '', name, module) + + def _loaded_gen_anonymous(self, tp, name, module, **kwds): + if isinstance(tp, model.EnumType): + self._loaded_gen_enum(tp, name, module, **kwds) + else: + self._loaded_struct_or_union(tp) + + # ---------- + # constants, likely declared with '#define' + + def _generate_gen_const(self, is_int, name, tp=None, category='const', + check_value=None): + prnt = self._prnt + funcname = '_cffi_%s_%s' % (category, name) + self.export_symbols.append(funcname) + if check_value is not None: + assert is_int + assert category == 'const' + prnt('int %s(char *out_error)' % funcname) + prnt('{') + self._check_int_constant_value(name, check_value) + prnt(' return 0;') + prnt('}') + elif is_int: + assert category == 'const' + prnt('int %s(long long *out_value)' % funcname) + prnt('{') + prnt(' *out_value = (long long)(%s);' % (name,)) + prnt(' return (%s) <= 0;' % (name,)) + prnt('}') + else: + assert tp is not None + assert check_value is None + if category == 'var': + ampersand = '&' + else: + ampersand = '' + extra = '' + if category == 'const' and isinstance(tp, model.StructOrUnion): + extra = 'const *' + ampersand = '&' + prnt(tp.get_c_name(' %s%s(void)' % (extra, funcname), name)) + prnt('{') + prnt(' return (%s%s);' % (ampersand, name)) + prnt('}') + prnt() + + def _generate_gen_constant_decl(self, tp, name): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + self._generate_gen_const(is_int, name, tp) + + _loading_gen_constant = _loaded_noop + + def _load_constant(self, is_int, tp, name, module, check_value=None): + funcname = '_cffi_const_%s' % name + if check_value is not None: + assert is_int + self._load_known_int_constant(module, funcname) + value = check_value + elif is_int: + BType = self.ffi._typeof_locked("long long*")[0] + BFunc = self.ffi._typeof_locked("int(*)(long long*)")[0] + function = module.load_function(BFunc, funcname) + p = self.ffi.new(BType) + negative = function(p) + value = int(p[0]) + if value < 0 and not negative: + BLongLong = self.ffi._typeof_locked("long long")[0] + value += (1 << (8*self.ffi.sizeof(BLongLong))) + else: + assert check_value is None + fntypeextra = '(*)(void)' + if isinstance(tp, model.StructOrUnion): + fntypeextra = '*' + fntypeextra + BFunc = self.ffi._typeof_locked(tp.get_c_name(fntypeextra, name))[0] + function = module.load_function(BFunc, funcname) + value = function() + if isinstance(tp, model.StructOrUnion): + value = value[0] + return value + + def _loaded_gen_constant(self, tp, name, module, library): + is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type() + value = self._load_constant(is_int, tp, name, module) + setattr(library, name, value) + type(library)._cffi_dir.append(name) + + # ---------- + # enums + + def _check_int_constant_value(self, name, value): + prnt = self._prnt + if value <= 0: + prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % ( + name, name, value)) + else: + prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % ( + name, name, value)) + prnt(' char buf[64];') + prnt(' if ((%s) <= 0)' % name) + prnt(' sprintf(buf, "%%ld", (long)(%s));' % name) + prnt(' else') + prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' % + name) + prnt(' sprintf(out_error, "%s has the real value %s, not %s",') + prnt(' "%s", buf, "%d");' % (name[:100], value)) + prnt(' return -1;') + prnt(' }') + + def _load_known_int_constant(self, module, funcname): + BType = self.ffi._typeof_locked("char[]")[0] + BFunc = self.ffi._typeof_locked("int(*)(char*)")[0] + function = module.load_function(BFunc, funcname) + p = self.ffi.new(BType, 256) + if function(p) < 0: + error = self.ffi.string(p) + if sys.version_info >= (3,): + error = str(error, 'utf-8') + raise VerificationError(error) + + def _enum_funcname(self, prefix, name): + # "$enum_$1" => "___D_enum____D_1" + name = name.replace('$', '___D_') + return '_cffi_e_%s_%s' % (prefix, name) + + def _generate_gen_enum_decl(self, tp, name, prefix='enum'): + if tp.partial: + for enumerator in tp.enumerators: + self._generate_gen_const(True, enumerator) + return + # + funcname = self._enum_funcname(prefix, name) + self.export_symbols.append(funcname) + prnt = self._prnt + prnt('int %s(char *out_error)' % funcname) + prnt('{') + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + self._check_int_constant_value(enumerator, enumvalue) + prnt(' return 0;') + prnt('}') + prnt() + + def _loading_gen_enum(self, tp, name, module, prefix='enum'): + if tp.partial: + enumvalues = [self._load_constant(True, tp, enumerator, module) + for enumerator in tp.enumerators] + tp.enumvalues = tuple(enumvalues) + tp.partial_resolved = True + else: + funcname = self._enum_funcname(prefix, name) + self._load_known_int_constant(module, funcname) + + def _loaded_gen_enum(self, tp, name, module, library): + for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues): + setattr(library, enumerator, enumvalue) + type(library)._cffi_dir.append(enumerator) + + # ---------- + # macros: for now only for integers + + def _generate_gen_macro_decl(self, tp, name): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + self._generate_gen_const(True, name, check_value=check_value) + + _loading_gen_macro = _loaded_noop + + def _loaded_gen_macro(self, tp, name, module, library): + if tp == '...': + check_value = None + else: + check_value = tp # an integer + value = self._load_constant(True, tp, name, module, + check_value=check_value) + setattr(library, name, value) + type(library)._cffi_dir.append(name) + + # ---------- + # global variables + + def _generate_gen_variable_decl(self, tp, name): + if isinstance(tp, model.ArrayType): + if tp.length_is_unknown(): + prnt = self._prnt + funcname = '_cffi_sizeof_%s' % (name,) + self.export_symbols.append(funcname) + prnt("size_t %s(void)" % funcname) + prnt("{") + prnt(" return sizeof(%s);" % (name,)) + prnt("}") + tp_ptr = model.PointerType(tp.item) + self._generate_gen_const(False, name, tp_ptr) + else: + tp_ptr = model.PointerType(tp) + self._generate_gen_const(False, name, tp_ptr, category='var') + + _loading_gen_variable = _loaded_noop + + def _loaded_gen_variable(self, tp, name, module, library): + if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the + # sense that "a=..." is forbidden + if tp.length_is_unknown(): + funcname = '_cffi_sizeof_%s' % (name,) + BFunc = self.ffi._typeof_locked('size_t(*)(void)')[0] + function = module.load_function(BFunc, funcname) + size = function() + BItemType = self.ffi._get_cached_btype(tp.item) + length, rest = divmod(size, self.ffi.sizeof(BItemType)) + if rest != 0: + raise VerificationError( + "bad size: %r does not seem to be an array of %s" % + (name, tp.item)) + tp = tp.resolve_length(length) + tp_ptr = model.PointerType(tp.item) + value = self._load_constant(False, tp_ptr, name, module) + # 'value' is a which we have to replace with + # a if the N is actually known + if tp.length is not None: + BArray = self.ffi._get_cached_btype(tp) + value = self.ffi.cast(BArray, value) + setattr(library, name, value) + type(library)._cffi_dir.append(name) + return + # remove ptr= from the library instance, and replace + # it by a property on the class, which reads/writes into ptr[0]. + funcname = '_cffi_var_%s' % name + BFunc = self.ffi._typeof_locked(tp.get_c_name('*(*)(void)', name))[0] + function = module.load_function(BFunc, funcname) + ptr = function() + def getter(library): + return ptr[0] + def setter(library, value): + ptr[0] = value + setattr(type(library), name, property(getter, setter)) + type(library)._cffi_dir.append(name) + +cffimod_header = r''' +#include +#include +#include +#include +#include /* XXX for ssize_t on some platforms */ + +/* this block of #ifs should be kept exactly identical between + c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py + and cffi/_cffi_include.h */ +#if defined(_MSC_VER) +# include /* for alloca() */ +# if _MSC_VER < 1600 /* MSVC < 2010 */ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; + typedef __int8 int_least8_t; + typedef __int16 int_least16_t; + typedef __int32 int_least32_t; + typedef __int64 int_least64_t; + typedef unsigned __int8 uint_least8_t; + typedef unsigned __int16 uint_least16_t; + typedef unsigned __int32 uint_least32_t; + typedef unsigned __int64 uint_least64_t; + typedef __int8 int_fast8_t; + typedef __int16 int_fast16_t; + typedef __int32 int_fast32_t; + typedef __int64 int_fast64_t; + typedef unsigned __int8 uint_fast8_t; + typedef unsigned __int16 uint_fast16_t; + typedef unsigned __int32 uint_fast32_t; + typedef unsigned __int64 uint_fast64_t; + typedef __int64 intmax_t; + typedef unsigned __int64 uintmax_t; +# else +# include +# endif +# if _MSC_VER < 1800 /* MSVC < 2013 */ +# ifndef __cplusplus + typedef unsigned char _Bool; +# endif +# endif +# define _cffi_float_complex_t _Fcomplex /* include for it */ +# define _cffi_double_complex_t _Dcomplex /* include for it */ +#else +# include +# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux) +# include +# endif +# define _cffi_float_complex_t float _Complex +# define _cffi_double_complex_t double _Complex +#endif +''' diff --git a/miniconda3/lib/python3.13/site-packages/cffi/verifier.py b/miniconda3/lib/python3.13/site-packages/cffi/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..e392a2b7fdab66662f5a32885cbe865d6c538ebe --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/cffi/verifier.py @@ -0,0 +1,306 @@ +# +# DEPRECATED: implementation for ffi.verify() +# +import sys, os, binascii, shutil, io +from . import __version_verifier_modules__ +from . import ffiplatform +from .error import VerificationError + +if sys.version_info >= (3, 3): + import importlib.machinery + def _extension_suffixes(): + return importlib.machinery.EXTENSION_SUFFIXES[:] +else: + import imp + def _extension_suffixes(): + return [suffix for suffix, _, type in imp.get_suffixes() + if type == imp.C_EXTENSION] + + +if sys.version_info >= (3,): + NativeIO = io.StringIO +else: + class NativeIO(io.BytesIO): + def write(self, s): + if isinstance(s, unicode): + s = s.encode('ascii') + super(NativeIO, self).write(s) + + +class Verifier(object): + + def __init__(self, ffi, preamble, tmpdir=None, modulename=None, + ext_package=None, tag='', force_generic_engine=False, + source_extension='.c', flags=None, relative_to=None, **kwds): + if ffi._parser._uses_new_feature: + raise VerificationError( + "feature not supported with ffi.verify(), but only " + "with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,)) + self.ffi = ffi + self.preamble = preamble + if not modulename: + flattened_kwds = ffiplatform.flatten(kwds) + vengine_class = _locate_engine_class(ffi, force_generic_engine) + self._vengine = vengine_class(self) + self._vengine.patch_extension_kwds(kwds) + self.flags = flags + self.kwds = self.make_relative_to(kwds, relative_to) + # + if modulename: + if tag: + raise TypeError("can't specify both 'modulename' and 'tag'") + else: + key = '\x00'.join(['%d.%d' % sys.version_info[:2], + __version_verifier_modules__, + preamble, flattened_kwds] + + ffi._cdefsources) + if sys.version_info >= (3,): + key = key.encode('utf-8') + k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff) + k1 = k1.lstrip('0x').rstrip('L') + k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff) + k2 = k2.lstrip('0').rstrip('L') + modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key, + k1, k2) + suffix = _get_so_suffixes()[0] + self.tmpdir = tmpdir or _caller_dir_pycache() + self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension) + self.modulefilename = os.path.join(self.tmpdir, modulename + suffix) + self.ext_package = ext_package + self._has_source = False + self._has_module = False + + def write_source(self, file=None): + """Write the C source code. It is produced in 'self.sourcefilename', + which can be tweaked beforehand.""" + with self.ffi._lock: + if self._has_source and file is None: + raise VerificationError( + "source code already written") + self._write_source(file) + + def compile_module(self): + """Write the C source code (if not done already) and compile it. + This produces a dynamic link library in 'self.modulefilename'.""" + with self.ffi._lock: + if self._has_module: + raise VerificationError("module already compiled") + if not self._has_source: + self._write_source() + self._compile_module() + + def load_library(self): + """Get a C module from this Verifier instance. + Returns an instance of a FFILibrary class that behaves like the + objects returned by ffi.dlopen(), but that delegates all + operations to the C module. If necessary, the C code is written + and compiled first. + """ + with self.ffi._lock: + if not self._has_module: + self._locate_module() + if not self._has_module: + if not self._has_source: + self._write_source() + self._compile_module() + return self._load_library() + + def get_module_name(self): + basename = os.path.basename(self.modulefilename) + # kill both the .so extension and the other .'s, as introduced + # by Python 3: 'basename.cpython-33m.so' + basename = basename.split('.', 1)[0] + # and the _d added in Python 2 debug builds --- but try to be + # conservative and not kill a legitimate _d + if basename.endswith('_d') and hasattr(sys, 'gettotalrefcount'): + basename = basename[:-2] + return basename + + def get_extension(self): + if not self._has_source: + with self.ffi._lock: + if not self._has_source: + self._write_source() + sourcename = ffiplatform.maybe_relative_path(self.sourcefilename) + modname = self.get_module_name() + return ffiplatform.get_extension(sourcename, modname, **self.kwds) + + def generates_python_module(self): + return self._vengine._gen_python_module + + def make_relative_to(self, kwds, relative_to): + if relative_to and os.path.dirname(relative_to): + dirname = os.path.dirname(relative_to) + kwds = kwds.copy() + for key in ffiplatform.LIST_OF_FILE_NAMES: + if key in kwds: + lst = kwds[key] + if not isinstance(lst, (list, tuple)): + raise TypeError("keyword '%s' should be a list or tuple" + % (key,)) + lst = [os.path.join(dirname, fn) for fn in lst] + kwds[key] = lst + return kwds + + # ---------- + + def _locate_module(self): + if not os.path.isfile(self.modulefilename): + if self.ext_package: + try: + pkg = __import__(self.ext_package, None, None, ['__doc__']) + except ImportError: + return # cannot import the package itself, give up + # (e.g. it might be called differently before installation) + path = pkg.__path__ + else: + path = None + filename = self._vengine.find_module(self.get_module_name(), path, + _get_so_suffixes()) + if filename is None: + return + self.modulefilename = filename + self._vengine.collect_types() + self._has_module = True + + def _write_source_to(self, file): + self._vengine._f = file + try: + self._vengine.write_source_to_f() + finally: + del self._vengine._f + + def _write_source(self, file=None): + if file is not None: + self._write_source_to(file) + else: + # Write our source file to an in memory file. + f = NativeIO() + self._write_source_to(f) + source_data = f.getvalue() + + # Determine if this matches the current file + if os.path.exists(self.sourcefilename): + with open(self.sourcefilename, "r") as fp: + needs_written = not (fp.read() == source_data) + else: + needs_written = True + + # Actually write the file out if it doesn't match + if needs_written: + _ensure_dir(self.sourcefilename) + with open(self.sourcefilename, "w") as fp: + fp.write(source_data) + + # Set this flag + self._has_source = True + + def _compile_module(self): + # compile this C source + tmpdir = os.path.dirname(self.sourcefilename) + outputfilename = ffiplatform.compile(tmpdir, self.get_extension()) + try: + same = ffiplatform.samefile(outputfilename, self.modulefilename) + except OSError: + same = False + if not same: + _ensure_dir(self.modulefilename) + shutil.move(outputfilename, self.modulefilename) + self._has_module = True + + def _load_library(self): + assert self._has_module + if self.flags is not None: + return self._vengine.load_library(self.flags) + else: + return self._vengine.load_library() + +# ____________________________________________________________ + +_FORCE_GENERIC_ENGINE = False # for tests + +def _locate_engine_class(ffi, force_generic_engine): + if _FORCE_GENERIC_ENGINE: + force_generic_engine = True + if not force_generic_engine: + if '__pypy__' in sys.builtin_module_names: + force_generic_engine = True + else: + try: + import _cffi_backend + except ImportError: + _cffi_backend = '?' + if ffi._backend is not _cffi_backend: + force_generic_engine = True + if force_generic_engine: + from . import vengine_gen + return vengine_gen.VGenericEngine + else: + from . import vengine_cpy + return vengine_cpy.VCPythonEngine + +# ____________________________________________________________ + +_TMPDIR = None + +def _caller_dir_pycache(): + if _TMPDIR: + return _TMPDIR + result = os.environ.get('CFFI_TMPDIR') + if result: + return result + filename = sys._getframe(2).f_code.co_filename + return os.path.abspath(os.path.join(os.path.dirname(filename), + '__pycache__')) + +def set_tmpdir(dirname): + """Set the temporary directory to use instead of __pycache__.""" + global _TMPDIR + _TMPDIR = dirname + +def cleanup_tmpdir(tmpdir=None, keep_so=False): + """Clean up the temporary directory by removing all files in it + called `_cffi_*.{c,so}` as well as the `build` subdirectory.""" + tmpdir = tmpdir or _caller_dir_pycache() + try: + filelist = os.listdir(tmpdir) + except OSError: + return + if keep_so: + suffix = '.c' # only remove .c files + else: + suffix = _get_so_suffixes()[0].lower() + for fn in filelist: + if fn.lower().startswith('_cffi_') and ( + fn.lower().endswith(suffix) or fn.lower().endswith('.c')): + try: + os.unlink(os.path.join(tmpdir, fn)) + except OSError: + pass + clean_dir = [os.path.join(tmpdir, 'build')] + for dir in clean_dir: + try: + for fn in os.listdir(dir): + fn = os.path.join(dir, fn) + if os.path.isdir(fn): + clean_dir.append(fn) + else: + os.unlink(fn) + except OSError: + pass + +def _get_so_suffixes(): + suffixes = _extension_suffixes() + if not suffixes: + # bah, no C_EXTENSION available. Occurs on pypy without cpyext + if sys.platform == 'win32': + suffixes = [".pyd"] + else: + suffixes = [".so"] + + return suffixes + +def _ensure_dir(filename): + dirname = os.path.dirname(filename) + if dirname and not os.path.isdir(dirname): + os.makedirs(dirname) diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8d32edcc9f0aa2057cc7844f7bb36b2c8c2e41d7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/METADATA @@ -0,0 +1,764 @@ +Metadata-Version: 2.4 +Name: charset-normalizer +Version: 3.4.4 +Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet. +Author-email: "Ahmed R. TAHRI" +Maintainer-email: "Ahmed R. TAHRI" +License: MIT +Project-URL: Changelog, https://github.com/jawah/charset_normalizer/blob/master/CHANGELOG.md +Project-URL: Documentation, https://charset-normalizer.readthedocs.io/ +Project-URL: Code, https://github.com/jawah/charset_normalizer +Project-URL: Issue tracker, https://github.com/jawah/charset_normalizer/issues +Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Text Processing :: Linguistic +Classifier: Topic :: Utilities +Classifier: Typing :: Typed +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: unicode-backport +Dynamic: license-file + +

Charset Detection, for Everyone 👋

+ +

+ The Real First Universal Charset Detector
+ + + + + Download Count Total + + + + +

+

+ Featured Packages
+ + Static Badge + + + Static Badge + +

+

+ In other language (unofficial port - by the community)
+ + Static Badge + +

+ +> A library that helps you read text from an unknown charset encoding.
Motivated by `chardet`, +> I'm trying to resolve the issue by taking a new approach. +> All IANA character set names for which the Python core library provides codecs are supported. + +

+ >>>>> 👉 Try Me Online Now, Then Adopt Me 👈 <<<<< +

+ +This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**. + +| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) | +|--------------------------------------------------|:---------------------------------------------:|:--------------------------------------------------------------------------------------------------:|:-----------------------------------------------:| +| `Fast` | ❌ | ✅ | ✅ | +| `Universal**` | ❌ | ✅ | ❌ | +| `Reliable` **without** distinguishable standards | ❌ | ✅ | ✅ | +| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ | +| `License` | LGPL-2.1
_restrictive_ | MIT | MPL-1.1
_restrictive_ | +| `Native Python` | ✅ | ✅ | ❌ | +| `Detect spoken language` | ❌ | ✅ | N/A | +| `UnicodeDecodeError Safety` | ❌ | ✅ | ❌ | +| `Whl Size (min)` | 193.6 kB | 42 kB | ~200 kB | +| `Supported Encoding` | 33 | 🎉 [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 | + +

+Reading Normalized TextCat Reading Text +

+ +*\*\* : They are clearly using specific code for a specific encoding even if covering most of used one*
+ +## ⚡ Performance + +This package offer better performance than its counterpart Chardet. Here are some numbers. + +| Package | Accuracy | Mean per file (ms) | File per sec (est) | +|-----------------------------------------------|:--------:|:------------------:|:------------------:| +| [chardet](https://github.com/chardet/chardet) | 86 % | 63 ms | 16 file/sec | +| charset-normalizer | **98 %** | **10 ms** | 100 file/sec | + +| Package | 99th percentile | 95th percentile | 50th percentile | +|-----------------------------------------------|:---------------:|:---------------:|:---------------:| +| [chardet](https://github.com/chardet/chardet) | 265 ms | 71 ms | 7 ms | +| charset-normalizer | 100 ms | 50 ms | 5 ms | + +_updated as of december 2024 using CPython 3.12_ + +Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload. + +> Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows. +> And yes, these results might change at any time. The dataset can be updated to include more files. +> The actual delays heavily depends on your CPU capabilities. The factors should remain the same. +> Keep in mind that the stats are generous and that Chardet accuracy vs our is measured using Chardet initial capability +> (e.g. Supported Encoding) Challenge-them if you want. + +## ✨ Installation + +Using pip: + +```sh +pip install charset-normalizer -U +``` + +## 🚀 Basic Usage + +### CLI +This package comes with a CLI. + +``` +usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD] + file [file ...] + +The Real First Universal Charset Detector. Discover originating encoding used +on text file. Normalize text to unicode. + +positional arguments: + files File(s) to be analysed + +optional arguments: + -h, --help show this help message and exit + -v, --verbose Display complementary information about file if any. + Stdout will contain logs about the detection process. + -a, --with-alternative + Output complementary possibilities if any. Top-level + JSON WILL be a list. + -n, --normalize Permit to normalize input file. If not set, program + does not write anything. + -m, --minimal Only output the charset detected to STDOUT. Disabling + JSON output. + -r, --replace Replace file when trying to normalize it instead of + creating a new one. + -f, --force Replace file without asking if you are sure, use this + flag with caution. + -t THRESHOLD, --threshold THRESHOLD + Define a custom maximum amount of chaos allowed in + decoded content. 0. <= chaos <= 1. + --version Show version information and exit. +``` + +```bash +normalizer ./data/sample.1.fr.srt +``` + +or + +```bash +python -m charset_normalizer ./data/sample.1.fr.srt +``` + +🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format. + +```json +{ + "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt", + "encoding": "cp1252", + "encoding_aliases": [ + "1252", + "windows_1252" + ], + "alternative_encodings": [ + "cp1254", + "cp1256", + "cp1258", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + "mbcs" + ], + "language": "French", + "alphabets": [ + "Basic Latin", + "Latin-1 Supplement" + ], + "has_sig_or_bom": false, + "chaos": 0.149, + "coherence": 97.152, + "unicode_path": null, + "is_preferred": true +} +``` + +### Python +*Just print out normalized text* +```python +from charset_normalizer import from_path + +results = from_path('./my_subtitle.srt') + +print(str(results.best())) +``` + +*Upgrade your code without effort* +```python +from charset_normalizer import detect +``` + +The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible. + +See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/) + +## 😇 Why + +When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a +reliable alternative using a completely different method. Also! I never back down on a good challenge! + +I **don't care** about the **originating charset** encoding, because **two different tables** can +produce **two identical rendered string.** +What I want is to get readable text, the best I can. + +In a way, **I'm brute forcing text decoding.** How cool is that ? 😎 + +Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair Unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode. + +## 🍰 How + + - Discard all charset encoding table that could not fit the binary content. + - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding. + - Extract matches with the lowest mess detected. + - Additionally, we measure coherence / probe for a language. + +**Wait a minute**, what is noise/mess and coherence according to **YOU ?** + +*Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then +**I established** some ground rules about **what is obvious** when **it seems like** a mess (aka. defining noise in rendered text). + I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to + improve or rewrite it. + +*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought +that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design. + +## ⚡ Known limitations + + - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters)) + - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content. + +## ⚠️ About Python EOLs + +**If you are running:** + +- Python >=2.7,<3.5: Unsupported +- Python 3.5: charset-normalizer < 2.1 +- Python 3.6: charset-normalizer < 3.1 +- Python 3.7: charset-normalizer < 4.0 + +Upgrade your Python interpreter as soon as possible. + +## 👤 Contributing + +Contributions, issues and feature requests are very much welcome.
+Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute. + +## 📝 License + +Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).
+This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed. + +Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/) + +## 💼 For Enterprise + +Professional support for charset-normalizer is available as part of the [Tidelift +Subscription][1]. Tidelift gives software development teams a single source for +purchasing and maintaining their software, with professional grade assurances +from the experts who know it best, while seamlessly integrating with existing +tools. + +[1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme + +[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7297/badge)](https://www.bestpractices.dev/projects/7297) + +# Changelog +All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## [3.4.4](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.4) (2025-10-13) + +### Changed +- Bound `setuptools` to a specific constraint `setuptools>=68,<=81`. +- Raised upper bound of mypyc for the optional pre-built extension to v1.18.2 + +### Removed +- `setuptools-scm` as a build dependency. + +### Misc +- Enforced hashes in `dev-requirements.txt` and created `ci-requirements.txt` for security purposes. +- Additional pre-built wheels for riscv64, s390x, and armv7l architectures. +- Restore ` multiple.intoto.jsonl` in GitHub releases in addition to individual attestation file per wheel. + +## [3.4.3](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.3) (2025-08-09) + +### Changed +- mypy(c) is no longer a required dependency at build time if `CHARSET_NORMALIZER_USE_MYPYC` isn't set to `1`. (#595) (#583) +- automatically lower confidence on small bytes samples that are not Unicode in `detect` output legacy function. (#391) + +### Added +- Custom build backend to overcome inability to mark mypy as an optional dependency in the build phase. +- Support for Python 3.14 + +### Fixed +- sdist archive contained useless directories. +- automatically fallback on valid UTF-16 or UTF-32 even if the md says it's noisy. (#633) + +### Misc +- SBOM are automatically published to the relevant GitHub release to comply with regulatory changes. + Each published wheel comes with its SBOM. We choose CycloneDX as the format. +- Prebuilt optimized wheel are no longer distributed by default for CPython 3.7 due to a change in cibuildwheel. + +## [3.4.2](https://github.com/Ousret/charset_normalizer/compare/3.4.1...3.4.2) (2025-05-02) + +### Fixed +- Addressed the DeprecationWarning in our CLI regarding `argparse.FileType` by backporting the target class into the package. (#591) +- Improved the overall reliability of the detector with CJK Ideographs. (#605) (#587) + +### Changed +- Optional mypyc compilation upgraded to version 1.15 for Python >= 3.8 + +## [3.4.1](https://github.com/Ousret/charset_normalizer/compare/3.4.0...3.4.1) (2024-12-24) + +### Changed +- Project metadata are now stored using `pyproject.toml` instead of `setup.cfg` using setuptools as the build backend. +- Enforce annotation delayed loading for a simpler and consistent types in the project. +- Optional mypyc compilation upgraded to version 1.14 for Python >= 3.8 + +### Added +- pre-commit configuration. +- noxfile. + +### Removed +- `build-requirements.txt` as per using `pyproject.toml` native build configuration. +- `bin/integration.py` and `bin/serve.py` in favor of downstream integration test (see noxfile). +- `setup.cfg` in favor of `pyproject.toml` metadata configuration. +- Unused `utils.range_scan` function. + +### Fixed +- Converting content to Unicode bytes may insert `utf_8` instead of preferred `utf-8`. (#572) +- Deprecation warning "'count' is passed as positional argument" when converting to Unicode bytes on Python 3.13+ + +## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08) + +### Added +- Argument `--no-preemptive` in the CLI to prevent the detector to search for hints. +- Support for Python 3.13 (#512) + +### Fixed +- Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch. +- Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537) +- Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381) + +## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31) + +### Fixed +- Unintentional memory usage regression when using large payload that match several encoding (#376) +- Regression on some detection case showcased in the documentation (#371) + +### Added +- Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife) + +## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22) + +### Changed +- Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8 +- Improved the general detection reliability based on reports from the community + +## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30) + +### Added +- Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer` +- Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323) + +### Removed +- (internal) Redundant utils.is_ascii function and unused function is_private_use_only +- (internal) charset_normalizer.assets is moved inside charset_normalizer.constant + +### Changed +- (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection +- Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8 + +### Fixed +- Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350) + +## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07) + +### Changed +- Typehint for function `from_path` no longer enforce `PathLike` as its first argument +- Minor improvement over the global detection reliability + +### Added +- Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries +- Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True) +- Explicit support for Python 3.12 + +### Fixed +- Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289) + +## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06) + +### Added +- Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262) + +### Removed +- Support for Python 3.6 (PR #260) + +### Changed +- Optional speedup provided by mypy/c 1.0.1 + +## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18) + +### Fixed +- Multi-bytes cutter/chunk generator did not always cut correctly (PR #233) + +### Changed +- Speedup provided by mypy/c 0.990 on Python >= 3.7 + +## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it +- Sphinx warnings when generating the documentation + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18) + +### Added +- Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results +- Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES +- Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio + +### Changed +- Build with static metadata using 'build' frontend +- Make the language detection stricter + +### Fixed +- CLI with opt --normalize fail when using full path for files +- TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it + +### Removed +- Coherence detector no longer return 'Simple English' instead return 'English' +- Coherence detector no longer return 'Classical Chinese' instead return 'Chinese' + +## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21) + +### Added +- `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl) + +### Removed +- Breaking: Method `first()` and `best()` from CharsetMatch +- UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII) + +### Fixed +- Sphinx warnings when generating the documentation + +## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15) + +### Changed +- Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1 + +### Removed +- Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches +- Breaking: Top-level function `normalize` +- Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch +- Support for the backport `unicodedata2` + +## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19) + +### Deprecated +- Function `normalize` scheduled for removal in 3.0 + +### Changed +- Removed useless call to decode in fn is_unprintable (#206) + +### Fixed +- Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204) + +## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19) + +### Added +- Output the Unicode table version when running the CLI with `--version` (PR #194) + +### Changed +- Re-use decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175) +- Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183) + +### Fixed +- Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175) +- CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181) + +### Removed +- Support for Python 3.5 (PR #192) + +### Deprecated +- Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194) + +## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12) + +### Fixed +- ASCII miss-detection on rare cases (PR #170) + +## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30) + +### Added +- Explicit support for Python 3.11 (PR #164) + +### Changed +- The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165) + +## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04) + +### Fixed +- Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154) + +### Changed +- Skipping the language-detection (CD) on ASCII (PR #155) + +## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03) + +### Changed +- Moderating the logging impact (since 2.0.8) for specific environments (PR #147) + +### Fixed +- Wrong logging level applied when setting kwarg `explain` to True (PR #146) + +## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24) +### Changed +- Improvement over Vietnamese detection (PR #126) +- MD improvement on trailing data and long foreign (non-pure latin) data (PR #124) +- Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122) +- call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129) +- Code style as refactored by Sourcery-AI (PR #131) +- Minor adjustment on the MD around european words (PR #133) +- Remove and replace SRTs from assets / tests (PR #139) +- Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135) + +### Fixed +- Fix large (misleading) sequence giving UnicodeDecodeError (PR #137) +- Avoid using too insignificant chunk (PR #137) + +### Added +- Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135) +- Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141) + +## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11) +### Added +- Add support for Kazakh (Cyrillic) language detection (PR #109) + +### Changed +- Further, improve inferring the language from a given single-byte code page (PR #112) +- Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116) +- Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113) +- Various detection improvement (MD+CD) (PR #117) + +### Removed +- Remove redundant logging entry about detected language(s) (PR #115) + +### Fixed +- Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102) + +## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18) +### Fixed +- Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100) +- Fix CLI crash when using --minimal output in certain cases (PR #103) + +### Changed +- Minor improvement to the detection efficiency (less than 1%) (PR #106 #101) + +## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14) +### Changed +- The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81) +- The BC-support with v1.x was improved, the old staticmethods are restored (PR #82) +- The Unicode detection is slightly improved (PR #93) +- Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91) + +### Removed +- The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92) + +### Fixed +- In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95) +- Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96) +- The MANIFEST.in was not exhaustive (PR #78) + +## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30) +### Fixed +- The CLI no longer raise an unexpected exception when no encoding has been found (PR #70) +- Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68) +- The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72) +- Submatch factoring could be wrong in rare edge cases (PR #72) +- Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72) +- Fix line endings from CRLF to LF for certain project files (PR #67) + +### Changed +- Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76) +- Allow fallback on specified encoding if any (PR #71) + +## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16) +### Changed +- Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63) +- According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64) + +## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15) +### Fixed +- Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59) + +### Changed +- Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57) + +## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13) +### Fixed +- Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55) +- Using explain=False permanently disable the verbose output in the current runtime (PR #47) +- One log entry (language target preemptive) was not show in logs when using explain=True (PR #47) +- Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52) + +### Changed +- Public function normalize default args values were not aligned with from_bytes (PR #53) + +### Added +- You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47) + +## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02) +### Changed +- 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet. +- Accent has been made on UTF-8 detection, should perform rather instantaneous. +- The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible. +- The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time) +- The program has been rewritten to ease the readability and maintainability. (+Using static typing)+ +- utf_7 detection has been reinstated. + +### Removed +- This package no longer require anything when used with Python 3.5 (Dropped cached_property) +- Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian. +- The exception hook on UnicodeDecodeError has been removed. + +### Deprecated +- Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0 + +### Fixed +- The CLI output used the relative path of the file(s). Should be absolute. + +## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28) +### Fixed +- Logger configuration/usage no longer conflict with others (PR #44) + +## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21) +### Removed +- Using standard logging instead of using the package loguru. +- Dropping nose test framework in favor of the maintained pytest. +- Choose to not use dragonmapper package to help with gibberish Chinese/CJK text. +- Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version. +- Stop support for UTF-7 that does not contain a SIG. +- Dropping PrettyTable, replaced with pure JSON output in CLI. + +### Fixed +- BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process. +- Not searching properly for the BOM when trying utf32/16 parent codec. + +### Changed +- Improving the package final size by compressing frequencies.json. +- Huge improvement over the larges payload. + +### Added +- CLI now produces JSON consumable output. +- Return ASCII if given sequences fit. Given reasonable confidence. + +## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13) + +### Fixed +- In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40) + +## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12) + +### Fixed +- Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39) + +## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12) + +### Fixed +- The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38) + +## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09) + +### Changed +- Amend the previous release to allow prettytable 2.0 (PR #35) + +## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08) + +### Fixed +- Fix error while using the package with a python pre-release interpreter (PR #33) + +### Changed +- Dependencies refactoring, constraints revised. + +### Added +- Add python 3.9 and 3.10 to the supported interpreters + +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..25c3b759281a52b16eea9e818cea01e8df91f373 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/RECORD @@ -0,0 +1,35 @@ +../../../bin/normalizer,sha256=s5v8Ryd-_lpO2PkK5C9ZdpVwagkAdUiW5pCMn9OzTfc,489 +charset_normalizer-3.4.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +charset_normalizer-3.4.4.dist-info/METADATA,sha256=jVuUFBti8dav19YLvWissTihVdF2ozUY4KKMw7jdkBQ,37303 +charset_normalizer-3.4.4.dist-info/RECORD,, +charset_normalizer-3.4.4.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +charset_normalizer-3.4.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +charset_normalizer-3.4.4.dist-info/direct_url.json,sha256=6aqycCnV6a-o8iGsXH78ZoChM3iBG1zOfPuoOW7PAAY,108 +charset_normalizer-3.4.4.dist-info/entry_points.txt,sha256=ADSTKrkXZ3hhdOVFi6DcUEHQRS0xfxDIE_pEz4wLIXA,65 +charset_normalizer-3.4.4.dist-info/licenses/LICENSE,sha256=bQ1Bv-FwrGx9wkjJpj4lTQ-0WmDVCoJX0K-SxuJJuIc,1071 +charset_normalizer-3.4.4.dist-info/top_level.txt,sha256=7ASyzePr8_xuZWJsnqJjIBtyV8vhEo0wBCv1MPRRi3Q,19 +charset_normalizer/__init__.py,sha256=OKRxRv2Zhnqk00tqkN0c1BtJjm165fWXLydE52IKuHc,1590 +charset_normalizer/__main__.py,sha256=yzYxMR-IhKRHYwcSlavEv8oGdwxsR89mr2X09qXGdps,109 +charset_normalizer/__pycache__/__init__.cpython-313.pyc,, +charset_normalizer/__pycache__/__main__.cpython-313.pyc,, +charset_normalizer/__pycache__/api.cpython-313.pyc,, +charset_normalizer/__pycache__/cd.cpython-313.pyc,, +charset_normalizer/__pycache__/constant.cpython-313.pyc,, +charset_normalizer/__pycache__/legacy.cpython-313.pyc,, +charset_normalizer/__pycache__/md.cpython-313.pyc,, +charset_normalizer/__pycache__/models.cpython-313.pyc,, +charset_normalizer/__pycache__/utils.cpython-313.pyc,, +charset_normalizer/__pycache__/version.cpython-313.pyc,, +charset_normalizer/api.py,sha256=V07i8aVeCD8T2fSia3C-fn0i9t8qQguEBhsqszg32Ns,22668 +charset_normalizer/cd.py,sha256=WKTo1HDb-H9HfCDc3Bfwq5jzS25Ziy9SE2a74SgTq88,12522 +charset_normalizer/cli/__init__.py,sha256=D8I86lFk2-py45JvqxniTirSj_sFyE6sjaY_0-G1shc,136 +charset_normalizer/cli/__main__.py,sha256=dMaXG6IJXRvqq8z2tig7Qb83-BpWTln55ooiku5_uvg,12646 +charset_normalizer/cli/__pycache__/__init__.cpython-313.pyc,, +charset_normalizer/cli/__pycache__/__main__.cpython-313.pyc,, +charset_normalizer/constant.py,sha256=7UVY4ldYhmQMHUdgQ_sgZmzcQ0xxYxpBunqSZ-XJZ8U,42713 +charset_normalizer/legacy.py,sha256=sYBzSpzsRrg_wF4LP536pG64BItw7Tqtc3SMQAHvFLM,2731 +charset_normalizer/md.py,sha256=-_oN3h3_X99nkFfqamD3yu45DC_wfk5odH0Tr_CQiXs,20145 +charset_normalizer/models.py,sha256=lKXhOnIPtiakbK3i__J9wpOfzx3JDTKj7Dn3Rg0VaRI,12394 +charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +charset_normalizer/utils.py,sha256=sTejPgrdlNsKNucZfJCxJ95lMTLA0ShHLLE3n5wpT9Q,12170 +charset_normalizer/version.py,sha256=nKE4qBNk5WA4LIJ_yIH_aSDfvtsyizkWMg-PUG-UZVk,115 diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..ce8bd019755866d8cf7937f7b31ff445d2709dcc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176174481524083/conda-bld/charset-normalizer_1761744828711/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..65619e73ec06c20c2a70c9507b872ad624d1a85c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +normalizer = charset_normalizer.cli:cli_detect diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9725772c7967075d97dc78d60f3735435eccba63 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/top_level.txt b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..66958f0a069d7aea7939bed40b9197608e93b243 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/top_level.txt @@ -0,0 +1 @@ +charset_normalizer diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d3a37990145e94ad85406166dbaf52f4c311e5e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/__init__.py @@ -0,0 +1,48 @@ +""" +Charset-Normalizer +~~~~~~~~~~~~~~ +The Real First Universal Charset Detector. +A library that helps you read text from an unknown charset encoding. +Motivated by chardet, This package is trying to resolve the issue by taking a new approach. +All IANA character set names for which the Python core library provides codecs are supported. + +Basic usage: + >>> from charset_normalizer import from_bytes + >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8')) + >>> best_guess = results.best() + >>> str(best_guess) + 'Bсеки човек има право на образование. Oбразованието!' + +Others methods and usages are available - see the full documentation +at . +:copyright: (c) 2021 by Ahmed TAHRI +:license: MIT, see LICENSE for more details. +""" + +from __future__ import annotations + +import logging + +from .api import from_bytes, from_fp, from_path, is_binary +from .legacy import detect +from .models import CharsetMatch, CharsetMatches +from .utils import set_logging_handler +from .version import VERSION, __version__ + +__all__ = ( + "from_fp", + "from_path", + "from_bytes", + "is_binary", + "detect", + "CharsetMatch", + "CharsetMatches", + "__version__", + "VERSION", + "set_logging_handler", +) + +# Attach a NullHandler to the top level logger by default +# https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library + +logging.getLogger("charset_normalizer").addHandler(logging.NullHandler()) diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/__main__.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e76f7bfbb411d4424d3a1834b0ea803d80ea7e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/__main__.py @@ -0,0 +1,6 @@ +from __future__ import annotations + +from .cli import cli_detect + +if __name__ == "__main__": + cli_detect() diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd96390507bac07ae21d513b45777011a539892 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/api.py @@ -0,0 +1,669 @@ +from __future__ import annotations + +import logging +from os import PathLike +from typing import BinaryIO + +from .cd import ( + coherence_ratio, + encoding_languages, + mb_encoding_languages, + merge_coherence_ratios, +) +from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE +from .md import mess_ratio +from .models import CharsetMatch, CharsetMatches +from .utils import ( + any_specified_encoding, + cut_sequence_chunks, + iana_name, + identify_sig_or_bom, + is_cp_similar, + is_multi_byte_encoding, + should_strip_sig_or_bom, +) + +logger = logging.getLogger("charset_normalizer") +explain_handler = logging.StreamHandler() +explain_handler.setFormatter( + logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") +) + + +def from_bytes( + sequences: bytes | bytearray, + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.2, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Given a raw bytes sequence, return the best possibles charset usable to render str objects. + If there is no results, it is a strong indicator that the source is binary/not text. + By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence. + And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will. + + The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page + but never take it for granted. Can improve the performance. + + You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that + purpose. + + This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. + By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' + toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. + Custom logging format and handler can be set manually. + """ + + if not isinstance(sequences, (bytearray, bytes)): + raise TypeError( + "Expected object of type bytes or bytearray, got: {}".format( + type(sequences) + ) + ) + + if explain: + previous_logger_level: int = logger.level + logger.addHandler(explain_handler) + logger.setLevel(TRACE) + + length: int = len(sequences) + + if length == 0: + logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level or logging.WARNING) + return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")]) + + if cp_isolation is not None: + logger.log( + TRACE, + "cp_isolation is set. use this flag for debugging purpose. " + "limited list of encoding allowed : %s.", + ", ".join(cp_isolation), + ) + cp_isolation = [iana_name(cp, False) for cp in cp_isolation] + else: + cp_isolation = [] + + if cp_exclusion is not None: + logger.log( + TRACE, + "cp_exclusion is set. use this flag for debugging purpose. " + "limited list of encoding excluded : %s.", + ", ".join(cp_exclusion), + ) + cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] + else: + cp_exclusion = [] + + if length <= (chunk_size * steps): + logger.log( + TRACE, + "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", + steps, + chunk_size, + length, + ) + steps = 1 + chunk_size = length + + if steps > 1 and length / steps < chunk_size: + chunk_size = int(length / steps) + + is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE + is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE + + if is_too_small_sequence: + logger.log( + TRACE, + "Trying to detect encoding from a tiny portion of ({}) byte(s).".format( + length + ), + ) + elif is_too_large_sequence: + logger.log( + TRACE, + "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format( + length + ), + ) + + prioritized_encodings: list[str] = [] + + specified_encoding: str | None = ( + any_specified_encoding(sequences) if preemptive_behaviour else None + ) + + if specified_encoding is not None: + prioritized_encodings.append(specified_encoding) + logger.log( + TRACE, + "Detected declarative mark in sequence. Priority +1 given for %s.", + specified_encoding, + ) + + tested: set[str] = set() + tested_but_hard_failure: list[str] = [] + tested_but_soft_failure: list[str] = [] + + fallback_ascii: CharsetMatch | None = None + fallback_u8: CharsetMatch | None = None + fallback_specified: CharsetMatch | None = None + + results: CharsetMatches = CharsetMatches() + + early_stop_results: CharsetMatches = CharsetMatches() + + sig_encoding, sig_payload = identify_sig_or_bom(sequences) + + if sig_encoding is not None: + prioritized_encodings.append(sig_encoding) + logger.log( + TRACE, + "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", + len(sig_payload), + sig_encoding, + ) + + prioritized_encodings.append("ascii") + + if "utf_8" not in prioritized_encodings: + prioritized_encodings.append("utf_8") + + for encoding_iana in prioritized_encodings + IANA_SUPPORTED: + if cp_isolation and encoding_iana not in cp_isolation: + continue + + if cp_exclusion and encoding_iana in cp_exclusion: + continue + + if encoding_iana in tested: + continue + + tested.add(encoding_iana) + + decoded_payload: str | None = None + bom_or_sig_available: bool = sig_encoding == encoding_iana + strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom( + encoding_iana + ) + + if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: + logger.log( + TRACE, + "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", + encoding_iana, + ) + continue + if encoding_iana in {"utf_7"} and not bom_or_sig_available: + logger.log( + TRACE, + "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.", + encoding_iana, + ) + continue + + try: + is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana) + except (ModuleNotFoundError, ImportError): + logger.log( + TRACE, + "Encoding %s does not provide an IncrementalDecoder", + encoding_iana, + ) + continue + + try: + if is_too_large_sequence and is_multi_byte_decoder is False: + str( + ( + sequences[: int(50e4)] + if strip_sig_or_bom is False + else sequences[len(sig_payload) : int(50e4)] + ), + encoding=encoding_iana, + ) + else: + decoded_payload = str( + ( + sequences + if strip_sig_or_bom is False + else sequences[len(sig_payload) :] + ), + encoding=encoding_iana, + ) + except (UnicodeDecodeError, LookupError) as e: + if not isinstance(e, LookupError): + logger.log( + TRACE, + "Code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + tested_but_hard_failure.append(encoding_iana) + continue + + similar_soft_failure_test: bool = False + + for encoding_soft_failed in tested_but_soft_failure: + if is_cp_similar(encoding_iana, encoding_soft_failed): + similar_soft_failure_test = True + break + + if similar_soft_failure_test: + logger.log( + TRACE, + "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!", + encoding_iana, + encoding_soft_failed, + ) + continue + + r_ = range( + 0 if not bom_or_sig_available else len(sig_payload), + length, + int(length / steps), + ) + + multi_byte_bonus: bool = ( + is_multi_byte_decoder + and decoded_payload is not None + and len(decoded_payload) < length + ) + + if multi_byte_bonus: + logger.log( + TRACE, + "Code page %s is a multi byte encoding table and it appear that at least one character " + "was encoded using n-bytes.", + encoding_iana, + ) + + max_chunk_gave_up: int = int(len(r_) / 4) + + max_chunk_gave_up = max(max_chunk_gave_up, 2) + early_stop_count: int = 0 + lazy_str_hard_failure = False + + md_chunks: list[str] = [] + md_ratios = [] + + try: + for chunk in cut_sequence_chunks( + sequences, + encoding_iana, + r_, + chunk_size, + bom_or_sig_available, + strip_sig_or_bom, + sig_payload, + is_multi_byte_decoder, + decoded_payload, + ): + md_chunks.append(chunk) + + md_ratios.append( + mess_ratio( + chunk, + threshold, + explain is True and 1 <= len(cp_isolation) <= 2, + ) + ) + + if md_ratios[-1] >= threshold: + early_stop_count += 1 + + if (early_stop_count >= max_chunk_gave_up) or ( + bom_or_sig_available and strip_sig_or_bom is False + ): + break + except ( + UnicodeDecodeError + ) as e: # Lazy str loading may have missed something there + logger.log( + TRACE, + "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + early_stop_count = max_chunk_gave_up + lazy_str_hard_failure = True + + # We might want to check the sequence again with the whole content + # Only if initial MD tests passes + if ( + not lazy_str_hard_failure + and is_too_large_sequence + and not is_multi_byte_decoder + ): + try: + sequences[int(50e3) :].decode(encoding_iana, errors="strict") + except UnicodeDecodeError as e: + logger.log( + TRACE, + "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", + encoding_iana, + str(e), + ) + tested_but_hard_failure.append(encoding_iana) + continue + + mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 + if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: + tested_but_soft_failure.append(encoding_iana) + logger.log( + TRACE, + "%s was excluded because of initial chaos probing. Gave up %i time(s). " + "Computed mean chaos is %f %%.", + encoding_iana, + early_stop_count, + round(mean_mess_ratio * 100, ndigits=3), + ) + # Preparing those fallbacks in case we got nothing. + if ( + enable_fallback + and encoding_iana + in ["ascii", "utf_8", specified_encoding, "utf_16", "utf_32"] + and not lazy_str_hard_failure + ): + fallback_entry = CharsetMatch( + sequences, + encoding_iana, + threshold, + bom_or_sig_available, + [], + decoded_payload, + preemptive_declaration=specified_encoding, + ) + if encoding_iana == specified_encoding: + fallback_specified = fallback_entry + elif encoding_iana == "ascii": + fallback_ascii = fallback_entry + else: + fallback_u8 = fallback_entry + continue + + logger.log( + TRACE, + "%s passed initial chaos probing. Mean measured chaos is %f %%", + encoding_iana, + round(mean_mess_ratio * 100, ndigits=3), + ) + + if not is_multi_byte_decoder: + target_languages: list[str] = encoding_languages(encoding_iana) + else: + target_languages = mb_encoding_languages(encoding_iana) + + if target_languages: + logger.log( + TRACE, + "{} should target any language(s) of {}".format( + encoding_iana, str(target_languages) + ), + ) + + cd_ratios = [] + + # We shall skip the CD when its about ASCII + # Most of the time its not relevant to run "language-detection" on it. + if encoding_iana != "ascii": + for chunk in md_chunks: + chunk_languages = coherence_ratio( + chunk, + language_threshold, + ",".join(target_languages) if target_languages else None, + ) + + cd_ratios.append(chunk_languages) + + cd_ratios_merged = merge_coherence_ratios(cd_ratios) + + if cd_ratios_merged: + logger.log( + TRACE, + "We detected language {} using {}".format( + cd_ratios_merged, encoding_iana + ), + ) + + current_match = CharsetMatch( + sequences, + encoding_iana, + mean_mess_ratio, + bom_or_sig_available, + cd_ratios_merged, + ( + decoded_payload + if ( + is_too_large_sequence is False + or encoding_iana in [specified_encoding, "ascii", "utf_8"] + ) + else None + ), + preemptive_declaration=specified_encoding, + ) + + results.append(current_match) + + if ( + encoding_iana in [specified_encoding, "ascii", "utf_8"] + and mean_mess_ratio < 0.1 + ): + # If md says nothing to worry about, then... stop immediately! + if mean_mess_ratio == 0.0: + logger.debug( + "Encoding detection: %s is most likely the one.", + current_match.encoding, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + return CharsetMatches([current_match]) + + early_stop_results.append(current_match) + + if ( + len(early_stop_results) + and (specified_encoding is None or specified_encoding in tested) + and "ascii" in tested + and "utf_8" in tested + ): + probable_result: CharsetMatch = early_stop_results.best() # type: ignore[assignment] + logger.debug( + "Encoding detection: %s is most likely the one.", + probable_result.encoding, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + + return CharsetMatches([probable_result]) + + if encoding_iana == sig_encoding: + logger.debug( + "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " + "the beginning of the sequence.", + encoding_iana, + ) + if explain: # Defensive: ensure exit path clean handler + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + return CharsetMatches([results[encoding_iana]]) + + if len(results) == 0: + if fallback_u8 or fallback_ascii or fallback_specified: + logger.log( + TRACE, + "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", + ) + + if fallback_specified: + logger.debug( + "Encoding detection: %s will be used as a fallback match", + fallback_specified.encoding, + ) + results.append(fallback_specified) + elif ( + (fallback_u8 and fallback_ascii is None) + or ( + fallback_u8 + and fallback_ascii + and fallback_u8.fingerprint != fallback_ascii.fingerprint + ) + or (fallback_u8 is not None) + ): + logger.debug("Encoding detection: utf_8 will be used as a fallback match") + results.append(fallback_u8) + elif fallback_ascii: + logger.debug("Encoding detection: ascii will be used as a fallback match") + results.append(fallback_ascii) + + if results: + logger.debug( + "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", + results.best().encoding, # type: ignore + len(results) - 1, + ) + else: + logger.debug("Encoding detection: Unable to determine any suitable charset.") + + if explain: + logger.removeHandler(explain_handler) + logger.setLevel(previous_logger_level) + + return results + + +def from_fp( + fp: BinaryIO, + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Same thing than the function from_bytes but using a file pointer that is already ready. + Will not close the file pointer. + """ + return from_bytes( + fp.read(), + steps, + chunk_size, + threshold, + cp_isolation, + cp_exclusion, + preemptive_behaviour, + explain, + language_threshold, + enable_fallback, + ) + + +def from_path( + path: str | bytes | PathLike, # type: ignore[type-arg] + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = True, +) -> CharsetMatches: + """ + Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. + Can raise IOError. + """ + with open(path, "rb") as fp: + return from_fp( + fp, + steps, + chunk_size, + threshold, + cp_isolation, + cp_exclusion, + preemptive_behaviour, + explain, + language_threshold, + enable_fallback, + ) + + +def is_binary( + fp_or_path_or_payload: PathLike | str | BinaryIO | bytes, # type: ignore[type-arg] + steps: int = 5, + chunk_size: int = 512, + threshold: float = 0.20, + cp_isolation: list[str] | None = None, + cp_exclusion: list[str] | None = None, + preemptive_behaviour: bool = True, + explain: bool = False, + language_threshold: float = 0.1, + enable_fallback: bool = False, +) -> bool: + """ + Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string. + Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match + are disabled to be stricter around ASCII-compatible but unlikely to be a string. + """ + if isinstance(fp_or_path_or_payload, (str, PathLike)): + guesses = from_path( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + elif isinstance( + fp_or_path_or_payload, + ( + bytes, + bytearray, + ), + ): + guesses = from_bytes( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + else: + guesses = from_fp( + fp_or_path_or_payload, + steps=steps, + chunk_size=chunk_size, + threshold=threshold, + cp_isolation=cp_isolation, + cp_exclusion=cp_exclusion, + preemptive_behaviour=preemptive_behaviour, + explain=explain, + language_threshold=language_threshold, + enable_fallback=enable_fallback, + ) + + return not guesses diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py new file mode 100644 index 0000000000000000000000000000000000000000..71a3ed5197f788135bb700a15a64594780aa6337 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/cd.py @@ -0,0 +1,395 @@ +from __future__ import annotations + +import importlib +from codecs import IncrementalDecoder +from collections import Counter +from functools import lru_cache +from typing import Counter as TypeCounter + +from .constant import ( + FREQUENCIES, + KO_NAMES, + LANGUAGE_SUPPORTED_COUNT, + TOO_SMALL_SEQUENCE, + ZH_NAMES, +) +from .md import is_suspiciously_successive_range +from .models import CoherenceMatches +from .utils import ( + is_accentuated, + is_latin, + is_multi_byte_encoding, + is_unicode_range_secondary, + unicode_range, +) + + +def encoding_unicode_range(iana_name: str) -> list[str]: + """ + Return associated unicode ranges in a single byte code page. + """ + if is_multi_byte_encoding(iana_name): + raise OSError("Function not supported on multi-byte code page") + + decoder = importlib.import_module(f"encodings.{iana_name}").IncrementalDecoder + + p: IncrementalDecoder = decoder(errors="ignore") + seen_ranges: dict[str, int] = {} + character_count: int = 0 + + for i in range(0x40, 0xFF): + chunk: str = p.decode(bytes([i])) + + if chunk: + character_range: str | None = unicode_range(chunk) + + if character_range is None: + continue + + if is_unicode_range_secondary(character_range) is False: + if character_range not in seen_ranges: + seen_ranges[character_range] = 0 + seen_ranges[character_range] += 1 + character_count += 1 + + return sorted( + [ + character_range + for character_range in seen_ranges + if seen_ranges[character_range] / character_count >= 0.15 + ] + ) + + +def unicode_range_languages(primary_range: str) -> list[str]: + """ + Return inferred languages used with a unicode range. + """ + languages: list[str] = [] + + for language, characters in FREQUENCIES.items(): + for character in characters: + if unicode_range(character) == primary_range: + languages.append(language) + break + + return languages + + +@lru_cache() +def encoding_languages(iana_name: str) -> list[str]: + """ + Single-byte encoding language association. Some code page are heavily linked to particular language(s). + This function does the correspondence. + """ + unicode_ranges: list[str] = encoding_unicode_range(iana_name) + primary_range: str | None = None + + for specified_range in unicode_ranges: + if "Latin" not in specified_range: + primary_range = specified_range + break + + if primary_range is None: + return ["Latin Based"] + + return unicode_range_languages(primary_range) + + +@lru_cache() +def mb_encoding_languages(iana_name: str) -> list[str]: + """ + Multi-byte encoding language association. Some code page are heavily linked to particular language(s). + This function does the correspondence. + """ + if ( + iana_name.startswith("shift_") + or iana_name.startswith("iso2022_jp") + or iana_name.startswith("euc_j") + or iana_name == "cp932" + ): + return ["Japanese"] + if iana_name.startswith("gb") or iana_name in ZH_NAMES: + return ["Chinese"] + if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: + return ["Korean"] + + return [] + + +@lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) +def get_target_features(language: str) -> tuple[bool, bool]: + """ + Determine main aspects from a supported language if it contains accents and if is pure Latin. + """ + target_have_accents: bool = False + target_pure_latin: bool = True + + for character in FREQUENCIES[language]: + if not target_have_accents and is_accentuated(character): + target_have_accents = True + if target_pure_latin and is_latin(character) is False: + target_pure_latin = False + + return target_have_accents, target_pure_latin + + +def alphabet_languages( + characters: list[str], ignore_non_latin: bool = False +) -> list[str]: + """ + Return associated languages associated to given characters. + """ + languages: list[tuple[str, float]] = [] + + source_have_accents = any(is_accentuated(character) for character in characters) + + for language, language_characters in FREQUENCIES.items(): + target_have_accents, target_pure_latin = get_target_features(language) + + if ignore_non_latin and target_pure_latin is False: + continue + + if target_have_accents is False and source_have_accents: + continue + + character_count: int = len(language_characters) + + character_match_count: int = len( + [c for c in language_characters if c in characters] + ) + + ratio: float = character_match_count / character_count + + if ratio >= 0.2: + languages.append((language, ratio)) + + languages = sorted(languages, key=lambda x: x[1], reverse=True) + + return [compatible_language[0] for compatible_language in languages] + + +def characters_popularity_compare( + language: str, ordered_characters: list[str] +) -> float: + """ + Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. + The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). + Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) + """ + if language not in FREQUENCIES: + raise ValueError(f"{language} not available") + + character_approved_count: int = 0 + FREQUENCIES_language_set = set(FREQUENCIES[language]) + + ordered_characters_count: int = len(ordered_characters) + target_language_characters_count: int = len(FREQUENCIES[language]) + + large_alphabet: bool = target_language_characters_count > 26 + + for character, character_rank in zip( + ordered_characters, range(0, ordered_characters_count) + ): + if character not in FREQUENCIES_language_set: + continue + + character_rank_in_language: int = FREQUENCIES[language].index(character) + expected_projection_ratio: float = ( + target_language_characters_count / ordered_characters_count + ) + character_rank_projection: int = int(character_rank * expected_projection_ratio) + + if ( + large_alphabet is False + and abs(character_rank_projection - character_rank_in_language) > 4 + ): + continue + + if ( + large_alphabet is True + and abs(character_rank_projection - character_rank_in_language) + < target_language_characters_count / 3 + ): + character_approved_count += 1 + continue + + characters_before_source: list[str] = FREQUENCIES[language][ + 0:character_rank_in_language + ] + characters_after_source: list[str] = FREQUENCIES[language][ + character_rank_in_language: + ] + characters_before: list[str] = ordered_characters[0:character_rank] + characters_after: list[str] = ordered_characters[character_rank:] + + before_match_count: int = len( + set(characters_before) & set(characters_before_source) + ) + + after_match_count: int = len( + set(characters_after) & set(characters_after_source) + ) + + if len(characters_before_source) == 0 and before_match_count <= 4: + character_approved_count += 1 + continue + + if len(characters_after_source) == 0 and after_match_count <= 4: + character_approved_count += 1 + continue + + if ( + before_match_count / len(characters_before_source) >= 0.4 + or after_match_count / len(characters_after_source) >= 0.4 + ): + character_approved_count += 1 + continue + + return character_approved_count / len(ordered_characters) + + +def alpha_unicode_split(decoded_sequence: str) -> list[str]: + """ + Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. + Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; + One containing the latin letters and the other hebrew. + """ + layers: dict[str, str] = {} + + for character in decoded_sequence: + if character.isalpha() is False: + continue + + character_range: str | None = unicode_range(character) + + if character_range is None: + continue + + layer_target_range: str | None = None + + for discovered_range in layers: + if ( + is_suspiciously_successive_range(discovered_range, character_range) + is False + ): + layer_target_range = discovered_range + break + + if layer_target_range is None: + layer_target_range = character_range + + if layer_target_range not in layers: + layers[layer_target_range] = character.lower() + continue + + layers[layer_target_range] += character.lower() + + return list(layers.values()) + + +def merge_coherence_ratios(results: list[CoherenceMatches]) -> CoherenceMatches: + """ + This function merge results previously given by the function coherence_ratio. + The return type is the same as coherence_ratio. + """ + per_language_ratios: dict[str, list[float]] = {} + for result in results: + for sub_result in result: + language, ratio = sub_result + if language not in per_language_ratios: + per_language_ratios[language] = [ratio] + continue + per_language_ratios[language].append(ratio) + + merge = [ + ( + language, + round( + sum(per_language_ratios[language]) / len(per_language_ratios[language]), + 4, + ), + ) + for language in per_language_ratios + ] + + return sorted(merge, key=lambda x: x[1], reverse=True) + + +def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches: + """ + We shall NOT return "English—" in CoherenceMatches because it is an alternative + of "English". This function only keeps the best match and remove the em-dash in it. + """ + index_results: dict[str, list[float]] = dict() + + for result in results: + language, ratio = result + no_em_name: str = language.replace("—", "") + + if no_em_name not in index_results: + index_results[no_em_name] = [] + + index_results[no_em_name].append(ratio) + + if any(len(index_results[e]) > 1 for e in index_results): + filtered_results: CoherenceMatches = [] + + for language in index_results: + filtered_results.append((language, max(index_results[language]))) + + return filtered_results + + return results + + +@lru_cache(maxsize=2048) +def coherence_ratio( + decoded_sequence: str, threshold: float = 0.1, lg_inclusion: str | None = None +) -> CoherenceMatches: + """ + Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers. + A layer = Character extraction by alphabets/ranges. + """ + + results: list[tuple[str, float]] = [] + ignore_non_latin: bool = False + + sufficient_match_count: int = 0 + + lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else [] + if "Latin Based" in lg_inclusion_list: + ignore_non_latin = True + lg_inclusion_list.remove("Latin Based") + + for layer in alpha_unicode_split(decoded_sequence): + sequence_frequencies: TypeCounter[str] = Counter(layer) + most_common = sequence_frequencies.most_common() + + character_count: int = sum(o for c, o in most_common) + + if character_count <= TOO_SMALL_SEQUENCE: + continue + + popular_character_ordered: list[str] = [c for c, o in most_common] + + for language in lg_inclusion_list or alphabet_languages( + popular_character_ordered, ignore_non_latin + ): + ratio: float = characters_popularity_compare( + language, popular_character_ordered + ) + + if ratio < threshold: + continue + elif ratio >= 0.8: + sufficient_match_count += 1 + + results.append((language, round(ratio, 4))) + + if sufficient_match_count >= 3: + break + + return sorted( + filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True + ) diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/cli/__init__.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..543a5a4de49d07690e73df778aa580589d0789c6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/cli/__init__.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +from .__main__ import cli_detect, query_yes_no + +__all__ = ( + "cli_detect", + "query_yes_no", +) diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/cli/__main__.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/cli/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb64156a0fc164442acc4f4517975a5699d26354 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/cli/__main__.py @@ -0,0 +1,381 @@ +from __future__ import annotations + +import argparse +import sys +import typing +from json import dumps +from os.path import abspath, basename, dirname, join, realpath +from platform import python_version +from unicodedata import unidata_version + +import charset_normalizer.md as md_module +from charset_normalizer import from_fp +from charset_normalizer.models import CliDetectionResult +from charset_normalizer.version import __version__ + + +def query_yes_no(question: str, default: str = "yes") -> bool: + """Ask a yes/no question via input() and return their answer. + + "question" is a string that is presented to the user. + "default" is the presumed answer if the user just hits . + It must be "yes" (the default), "no" or None (meaning + an answer is required of the user). + + The "answer" return value is True for "yes" or False for "no". + + Credit goes to (c) https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input + """ + valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} + if default is None: + prompt = " [y/n] " + elif default == "yes": + prompt = " [Y/n] " + elif default == "no": + prompt = " [y/N] " + else: + raise ValueError("invalid default answer: '%s'" % default) + + while True: + sys.stdout.write(question + prompt) + choice = input().lower() + if default is not None and choice == "": + return valid[default] + elif choice in valid: + return valid[choice] + else: + sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n") + + +class FileType: + """Factory for creating file object types + + Instances of FileType are typically passed as type= arguments to the + ArgumentParser add_argument() method. + + Keyword Arguments: + - mode -- A string indicating how the file is to be opened. Accepts the + same values as the builtin open() function. + - bufsize -- The file's desired buffer size. Accepts the same values as + the builtin open() function. + - encoding -- The file's encoding. Accepts the same values as the + builtin open() function. + - errors -- A string indicating how encoding and decoding errors are to + be handled. Accepts the same value as the builtin open() function. + + Backported from CPython 3.12 + """ + + def __init__( + self, + mode: str = "r", + bufsize: int = -1, + encoding: str | None = None, + errors: str | None = None, + ): + self._mode = mode + self._bufsize = bufsize + self._encoding = encoding + self._errors = errors + + def __call__(self, string: str) -> typing.IO: # type: ignore[type-arg] + # the special argument "-" means sys.std{in,out} + if string == "-": + if "r" in self._mode: + return sys.stdin.buffer if "b" in self._mode else sys.stdin + elif any(c in self._mode for c in "wax"): + return sys.stdout.buffer if "b" in self._mode else sys.stdout + else: + msg = f'argument "-" with mode {self._mode}' + raise ValueError(msg) + + # all other arguments are used as file names + try: + return open(string, self._mode, self._bufsize, self._encoding, self._errors) + except OSError as e: + message = f"can't open '{string}': {e}" + raise argparse.ArgumentTypeError(message) + + def __repr__(self) -> str: + args = self._mode, self._bufsize + kwargs = [("encoding", self._encoding), ("errors", self._errors)] + args_str = ", ".join( + [repr(arg) for arg in args if arg != -1] + + [f"{kw}={arg!r}" for kw, arg in kwargs if arg is not None] + ) + return f"{type(self).__name__}({args_str})" + + +def cli_detect(argv: list[str] | None = None) -> int: + """ + CLI assistant using ARGV and ArgumentParser + :param argv: + :return: 0 if everything is fine, anything else equal trouble + """ + parser = argparse.ArgumentParser( + description="The Real First Universal Charset Detector. " + "Discover originating encoding used on text file. " + "Normalize text to unicode." + ) + + parser.add_argument( + "files", type=FileType("rb"), nargs="+", help="File(s) to be analysed" + ) + parser.add_argument( + "-v", + "--verbose", + action="store_true", + default=False, + dest="verbose", + help="Display complementary information about file if any. " + "Stdout will contain logs about the detection process.", + ) + parser.add_argument( + "-a", + "--with-alternative", + action="store_true", + default=False, + dest="alternatives", + help="Output complementary possibilities if any. Top-level JSON WILL be a list.", + ) + parser.add_argument( + "-n", + "--normalize", + action="store_true", + default=False, + dest="normalize", + help="Permit to normalize input file. If not set, program does not write anything.", + ) + parser.add_argument( + "-m", + "--minimal", + action="store_true", + default=False, + dest="minimal", + help="Only output the charset detected to STDOUT. Disabling JSON output.", + ) + parser.add_argument( + "-r", + "--replace", + action="store_true", + default=False, + dest="replace", + help="Replace file when trying to normalize it instead of creating a new one.", + ) + parser.add_argument( + "-f", + "--force", + action="store_true", + default=False, + dest="force", + help="Replace file without asking if you are sure, use this flag with caution.", + ) + parser.add_argument( + "-i", + "--no-preemptive", + action="store_true", + default=False, + dest="no_preemptive", + help="Disable looking at a charset declaration to hint the detector.", + ) + parser.add_argument( + "-t", + "--threshold", + action="store", + default=0.2, + type=float, + dest="threshold", + help="Define a custom maximum amount of noise allowed in decoded content. 0. <= noise <= 1.", + ) + parser.add_argument( + "--version", + action="version", + version="Charset-Normalizer {} - Python {} - Unicode {} - SpeedUp {}".format( + __version__, + python_version(), + unidata_version, + "OFF" if md_module.__file__.lower().endswith(".py") else "ON", + ), + help="Show version information and exit.", + ) + + args = parser.parse_args(argv) + + if args.replace is True and args.normalize is False: + if args.files: + for my_file in args.files: + my_file.close() + print("Use --replace in addition of --normalize only.", file=sys.stderr) + return 1 + + if args.force is True and args.replace is False: + if args.files: + for my_file in args.files: + my_file.close() + print("Use --force in addition of --replace only.", file=sys.stderr) + return 1 + + if args.threshold < 0.0 or args.threshold > 1.0: + if args.files: + for my_file in args.files: + my_file.close() + print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr) + return 1 + + x_ = [] + + for my_file in args.files: + matches = from_fp( + my_file, + threshold=args.threshold, + explain=args.verbose, + preemptive_behaviour=args.no_preemptive is False, + ) + + best_guess = matches.best() + + if best_guess is None: + print( + 'Unable to identify originating encoding for "{}". {}'.format( + my_file.name, + ( + "Maybe try increasing maximum amount of chaos." + if args.threshold < 1.0 + else "" + ), + ), + file=sys.stderr, + ) + x_.append( + CliDetectionResult( + abspath(my_file.name), + None, + [], + [], + "Unknown", + [], + False, + 1.0, + 0.0, + None, + True, + ) + ) + else: + x_.append( + CliDetectionResult( + abspath(my_file.name), + best_guess.encoding, + best_guess.encoding_aliases, + [ + cp + for cp in best_guess.could_be_from_charset + if cp != best_guess.encoding + ], + best_guess.language, + best_guess.alphabets, + best_guess.bom, + best_guess.percent_chaos, + best_guess.percent_coherence, + None, + True, + ) + ) + + if len(matches) > 1 and args.alternatives: + for el in matches: + if el != best_guess: + x_.append( + CliDetectionResult( + abspath(my_file.name), + el.encoding, + el.encoding_aliases, + [ + cp + for cp in el.could_be_from_charset + if cp != el.encoding + ], + el.language, + el.alphabets, + el.bom, + el.percent_chaos, + el.percent_coherence, + None, + False, + ) + ) + + if args.normalize is True: + if best_guess.encoding.startswith("utf") is True: + print( + '"{}" file does not need to be normalized, as it already came from unicode.'.format( + my_file.name + ), + file=sys.stderr, + ) + if my_file.closed is False: + my_file.close() + continue + + dir_path = dirname(realpath(my_file.name)) + file_name = basename(realpath(my_file.name)) + + o_: list[str] = file_name.split(".") + + if args.replace is False: + o_.insert(-1, best_guess.encoding) + if my_file.closed is False: + my_file.close() + elif ( + args.force is False + and query_yes_no( + 'Are you sure to normalize "{}" by replacing it ?'.format( + my_file.name + ), + "no", + ) + is False + ): + if my_file.closed is False: + my_file.close() + continue + + try: + x_[0].unicode_path = join(dir_path, ".".join(o_)) + + with open(x_[0].unicode_path, "wb") as fp: + fp.write(best_guess.output()) + except OSError as e: + print(str(e), file=sys.stderr) + if my_file.closed is False: + my_file.close() + return 2 + + if my_file.closed is False: + my_file.close() + + if args.minimal is False: + print( + dumps( + [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__, + ensure_ascii=True, + indent=4, + ) + ) + else: + for my_file in args.files: + print( + ", ".join( + [ + el.encoding or "undefined" + for el in x_ + if el.path == abspath(my_file.name) + ] + ) + ) + + return 0 + + +if __name__ == "__main__": + cli_detect() diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..cc71a019c7fdd7b99c7fdd5b6bb084ab2840ff63 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/constant.py @@ -0,0 +1,2015 @@ +from __future__ import annotations + +from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE +from encodings.aliases import aliases +from re import IGNORECASE +from re import compile as re_compile + +# Contain for each eligible encoding a list of/item bytes SIG/BOM +ENCODING_MARKS: dict[str, bytes | list[bytes]] = { + "utf_8": BOM_UTF8, + "utf_7": [ + b"\x2b\x2f\x76\x38", + b"\x2b\x2f\x76\x39", + b"\x2b\x2f\x76\x2b", + b"\x2b\x2f\x76\x2f", + b"\x2b\x2f\x76\x38\x2d", + ], + "gb18030": b"\x84\x31\x95\x33", + "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE], + "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE], +} + +TOO_SMALL_SEQUENCE: int = 32 +TOO_BIG_SEQUENCE: int = int(10e6) + +UTF8_MAXIMAL_ALLOCATION: int = 1_112_064 + +# Up-to-date Unicode ucd/15.0.0 +UNICODE_RANGES_COMBINED: dict[str, range] = { + "Control character": range(32), + "Basic Latin": range(32, 128), + "Latin-1 Supplement": range(128, 256), + "Latin Extended-A": range(256, 384), + "Latin Extended-B": range(384, 592), + "IPA Extensions": range(592, 688), + "Spacing Modifier Letters": range(688, 768), + "Combining Diacritical Marks": range(768, 880), + "Greek and Coptic": range(880, 1024), + "Cyrillic": range(1024, 1280), + "Cyrillic Supplement": range(1280, 1328), + "Armenian": range(1328, 1424), + "Hebrew": range(1424, 1536), + "Arabic": range(1536, 1792), + "Syriac": range(1792, 1872), + "Arabic Supplement": range(1872, 1920), + "Thaana": range(1920, 1984), + "NKo": range(1984, 2048), + "Samaritan": range(2048, 2112), + "Mandaic": range(2112, 2144), + "Syriac Supplement": range(2144, 2160), + "Arabic Extended-B": range(2160, 2208), + "Arabic Extended-A": range(2208, 2304), + "Devanagari": range(2304, 2432), + "Bengali": range(2432, 2560), + "Gurmukhi": range(2560, 2688), + "Gujarati": range(2688, 2816), + "Oriya": range(2816, 2944), + "Tamil": range(2944, 3072), + "Telugu": range(3072, 3200), + "Kannada": range(3200, 3328), + "Malayalam": range(3328, 3456), + "Sinhala": range(3456, 3584), + "Thai": range(3584, 3712), + "Lao": range(3712, 3840), + "Tibetan": range(3840, 4096), + "Myanmar": range(4096, 4256), + "Georgian": range(4256, 4352), + "Hangul Jamo": range(4352, 4608), + "Ethiopic": range(4608, 4992), + "Ethiopic Supplement": range(4992, 5024), + "Cherokee": range(5024, 5120), + "Unified Canadian Aboriginal Syllabics": range(5120, 5760), + "Ogham": range(5760, 5792), + "Runic": range(5792, 5888), + "Tagalog": range(5888, 5920), + "Hanunoo": range(5920, 5952), + "Buhid": range(5952, 5984), + "Tagbanwa": range(5984, 6016), + "Khmer": range(6016, 6144), + "Mongolian": range(6144, 6320), + "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400), + "Limbu": range(6400, 6480), + "Tai Le": range(6480, 6528), + "New Tai Lue": range(6528, 6624), + "Khmer Symbols": range(6624, 6656), + "Buginese": range(6656, 6688), + "Tai Tham": range(6688, 6832), + "Combining Diacritical Marks Extended": range(6832, 6912), + "Balinese": range(6912, 7040), + "Sundanese": range(7040, 7104), + "Batak": range(7104, 7168), + "Lepcha": range(7168, 7248), + "Ol Chiki": range(7248, 7296), + "Cyrillic Extended-C": range(7296, 7312), + "Georgian Extended": range(7312, 7360), + "Sundanese Supplement": range(7360, 7376), + "Vedic Extensions": range(7376, 7424), + "Phonetic Extensions": range(7424, 7552), + "Phonetic Extensions Supplement": range(7552, 7616), + "Combining Diacritical Marks Supplement": range(7616, 7680), + "Latin Extended Additional": range(7680, 7936), + "Greek Extended": range(7936, 8192), + "General Punctuation": range(8192, 8304), + "Superscripts and Subscripts": range(8304, 8352), + "Currency Symbols": range(8352, 8400), + "Combining Diacritical Marks for Symbols": range(8400, 8448), + "Letterlike Symbols": range(8448, 8528), + "Number Forms": range(8528, 8592), + "Arrows": range(8592, 8704), + "Mathematical Operators": range(8704, 8960), + "Miscellaneous Technical": range(8960, 9216), + "Control Pictures": range(9216, 9280), + "Optical Character Recognition": range(9280, 9312), + "Enclosed Alphanumerics": range(9312, 9472), + "Box Drawing": range(9472, 9600), + "Block Elements": range(9600, 9632), + "Geometric Shapes": range(9632, 9728), + "Miscellaneous Symbols": range(9728, 9984), + "Dingbats": range(9984, 10176), + "Miscellaneous Mathematical Symbols-A": range(10176, 10224), + "Supplemental Arrows-A": range(10224, 10240), + "Braille Patterns": range(10240, 10496), + "Supplemental Arrows-B": range(10496, 10624), + "Miscellaneous Mathematical Symbols-B": range(10624, 10752), + "Supplemental Mathematical Operators": range(10752, 11008), + "Miscellaneous Symbols and Arrows": range(11008, 11264), + "Glagolitic": range(11264, 11360), + "Latin Extended-C": range(11360, 11392), + "Coptic": range(11392, 11520), + "Georgian Supplement": range(11520, 11568), + "Tifinagh": range(11568, 11648), + "Ethiopic Extended": range(11648, 11744), + "Cyrillic Extended-A": range(11744, 11776), + "Supplemental Punctuation": range(11776, 11904), + "CJK Radicals Supplement": range(11904, 12032), + "Kangxi Radicals": range(12032, 12256), + "Ideographic Description Characters": range(12272, 12288), + "CJK Symbols and Punctuation": range(12288, 12352), + "Hiragana": range(12352, 12448), + "Katakana": range(12448, 12544), + "Bopomofo": range(12544, 12592), + "Hangul Compatibility Jamo": range(12592, 12688), + "Kanbun": range(12688, 12704), + "Bopomofo Extended": range(12704, 12736), + "CJK Strokes": range(12736, 12784), + "Katakana Phonetic Extensions": range(12784, 12800), + "Enclosed CJK Letters and Months": range(12800, 13056), + "CJK Compatibility": range(13056, 13312), + "CJK Unified Ideographs Extension A": range(13312, 19904), + "Yijing Hexagram Symbols": range(19904, 19968), + "CJK Unified Ideographs": range(19968, 40960), + "Yi Syllables": range(40960, 42128), + "Yi Radicals": range(42128, 42192), + "Lisu": range(42192, 42240), + "Vai": range(42240, 42560), + "Cyrillic Extended-B": range(42560, 42656), + "Bamum": range(42656, 42752), + "Modifier Tone Letters": range(42752, 42784), + "Latin Extended-D": range(42784, 43008), + "Syloti Nagri": range(43008, 43056), + "Common Indic Number Forms": range(43056, 43072), + "Phags-pa": range(43072, 43136), + "Saurashtra": range(43136, 43232), + "Devanagari Extended": range(43232, 43264), + "Kayah Li": range(43264, 43312), + "Rejang": range(43312, 43360), + "Hangul Jamo Extended-A": range(43360, 43392), + "Javanese": range(43392, 43488), + "Myanmar Extended-B": range(43488, 43520), + "Cham": range(43520, 43616), + "Myanmar Extended-A": range(43616, 43648), + "Tai Viet": range(43648, 43744), + "Meetei Mayek Extensions": range(43744, 43776), + "Ethiopic Extended-A": range(43776, 43824), + "Latin Extended-E": range(43824, 43888), + "Cherokee Supplement": range(43888, 43968), + "Meetei Mayek": range(43968, 44032), + "Hangul Syllables": range(44032, 55216), + "Hangul Jamo Extended-B": range(55216, 55296), + "High Surrogates": range(55296, 56192), + "High Private Use Surrogates": range(56192, 56320), + "Low Surrogates": range(56320, 57344), + "Private Use Area": range(57344, 63744), + "CJK Compatibility Ideographs": range(63744, 64256), + "Alphabetic Presentation Forms": range(64256, 64336), + "Arabic Presentation Forms-A": range(64336, 65024), + "Variation Selectors": range(65024, 65040), + "Vertical Forms": range(65040, 65056), + "Combining Half Marks": range(65056, 65072), + "CJK Compatibility Forms": range(65072, 65104), + "Small Form Variants": range(65104, 65136), + "Arabic Presentation Forms-B": range(65136, 65280), + "Halfwidth and Fullwidth Forms": range(65280, 65520), + "Specials": range(65520, 65536), + "Linear B Syllabary": range(65536, 65664), + "Linear B Ideograms": range(65664, 65792), + "Aegean Numbers": range(65792, 65856), + "Ancient Greek Numbers": range(65856, 65936), + "Ancient Symbols": range(65936, 66000), + "Phaistos Disc": range(66000, 66048), + "Lycian": range(66176, 66208), + "Carian": range(66208, 66272), + "Coptic Epact Numbers": range(66272, 66304), + "Old Italic": range(66304, 66352), + "Gothic": range(66352, 66384), + "Old Permic": range(66384, 66432), + "Ugaritic": range(66432, 66464), + "Old Persian": range(66464, 66528), + "Deseret": range(66560, 66640), + "Shavian": range(66640, 66688), + "Osmanya": range(66688, 66736), + "Osage": range(66736, 66816), + "Elbasan": range(66816, 66864), + "Caucasian Albanian": range(66864, 66928), + "Vithkuqi": range(66928, 67008), + "Linear A": range(67072, 67456), + "Latin Extended-F": range(67456, 67520), + "Cypriot Syllabary": range(67584, 67648), + "Imperial Aramaic": range(67648, 67680), + "Palmyrene": range(67680, 67712), + "Nabataean": range(67712, 67760), + "Hatran": range(67808, 67840), + "Phoenician": range(67840, 67872), + "Lydian": range(67872, 67904), + "Meroitic Hieroglyphs": range(67968, 68000), + "Meroitic Cursive": range(68000, 68096), + "Kharoshthi": range(68096, 68192), + "Old South Arabian": range(68192, 68224), + "Old North Arabian": range(68224, 68256), + "Manichaean": range(68288, 68352), + "Avestan": range(68352, 68416), + "Inscriptional Parthian": range(68416, 68448), + "Inscriptional Pahlavi": range(68448, 68480), + "Psalter Pahlavi": range(68480, 68528), + "Old Turkic": range(68608, 68688), + "Old Hungarian": range(68736, 68864), + "Hanifi Rohingya": range(68864, 68928), + "Rumi Numeral Symbols": range(69216, 69248), + "Yezidi": range(69248, 69312), + "Arabic Extended-C": range(69312, 69376), + "Old Sogdian": range(69376, 69424), + "Sogdian": range(69424, 69488), + "Old Uyghur": range(69488, 69552), + "Chorasmian": range(69552, 69600), + "Elymaic": range(69600, 69632), + "Brahmi": range(69632, 69760), + "Kaithi": range(69760, 69840), + "Sora Sompeng": range(69840, 69888), + "Chakma": range(69888, 69968), + "Mahajani": range(69968, 70016), + "Sharada": range(70016, 70112), + "Sinhala Archaic Numbers": range(70112, 70144), + "Khojki": range(70144, 70224), + "Multani": range(70272, 70320), + "Khudawadi": range(70320, 70400), + "Grantha": range(70400, 70528), + "Newa": range(70656, 70784), + "Tirhuta": range(70784, 70880), + "Siddham": range(71040, 71168), + "Modi": range(71168, 71264), + "Mongolian Supplement": range(71264, 71296), + "Takri": range(71296, 71376), + "Ahom": range(71424, 71504), + "Dogra": range(71680, 71760), + "Warang Citi": range(71840, 71936), + "Dives Akuru": range(71936, 72032), + "Nandinagari": range(72096, 72192), + "Zanabazar Square": range(72192, 72272), + "Soyombo": range(72272, 72368), + "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384), + "Pau Cin Hau": range(72384, 72448), + "Devanagari Extended-A": range(72448, 72544), + "Bhaiksuki": range(72704, 72816), + "Marchen": range(72816, 72896), + "Masaram Gondi": range(72960, 73056), + "Gunjala Gondi": range(73056, 73136), + "Makasar": range(73440, 73472), + "Kawi": range(73472, 73568), + "Lisu Supplement": range(73648, 73664), + "Tamil Supplement": range(73664, 73728), + "Cuneiform": range(73728, 74752), + "Cuneiform Numbers and Punctuation": range(74752, 74880), + "Early Dynastic Cuneiform": range(74880, 75088), + "Cypro-Minoan": range(77712, 77824), + "Egyptian Hieroglyphs": range(77824, 78896), + "Egyptian Hieroglyph Format Controls": range(78896, 78944), + "Anatolian Hieroglyphs": range(82944, 83584), + "Bamum Supplement": range(92160, 92736), + "Mro": range(92736, 92784), + "Tangsa": range(92784, 92880), + "Bassa Vah": range(92880, 92928), + "Pahawh Hmong": range(92928, 93072), + "Medefaidrin": range(93760, 93856), + "Miao": range(93952, 94112), + "Ideographic Symbols and Punctuation": range(94176, 94208), + "Tangut": range(94208, 100352), + "Tangut Components": range(100352, 101120), + "Khitan Small Script": range(101120, 101632), + "Tangut Supplement": range(101632, 101760), + "Kana Extended-B": range(110576, 110592), + "Kana Supplement": range(110592, 110848), + "Kana Extended-A": range(110848, 110896), + "Small Kana Extension": range(110896, 110960), + "Nushu": range(110960, 111360), + "Duployan": range(113664, 113824), + "Shorthand Format Controls": range(113824, 113840), + "Znamenny Musical Notation": range(118528, 118736), + "Byzantine Musical Symbols": range(118784, 119040), + "Musical Symbols": range(119040, 119296), + "Ancient Greek Musical Notation": range(119296, 119376), + "Kaktovik Numerals": range(119488, 119520), + "Mayan Numerals": range(119520, 119552), + "Tai Xuan Jing Symbols": range(119552, 119648), + "Counting Rod Numerals": range(119648, 119680), + "Mathematical Alphanumeric Symbols": range(119808, 120832), + "Sutton SignWriting": range(120832, 121520), + "Latin Extended-G": range(122624, 122880), + "Glagolitic Supplement": range(122880, 122928), + "Cyrillic Extended-D": range(122928, 123024), + "Nyiakeng Puachue Hmong": range(123136, 123216), + "Toto": range(123536, 123584), + "Wancho": range(123584, 123648), + "Nag Mundari": range(124112, 124160), + "Ethiopic Extended-B": range(124896, 124928), + "Mende Kikakui": range(124928, 125152), + "Adlam": range(125184, 125280), + "Indic Siyaq Numbers": range(126064, 126144), + "Ottoman Siyaq Numbers": range(126208, 126288), + "Arabic Mathematical Alphabetic Symbols": range(126464, 126720), + "Mahjong Tiles": range(126976, 127024), + "Domino Tiles": range(127024, 127136), + "Playing Cards": range(127136, 127232), + "Enclosed Alphanumeric Supplement": range(127232, 127488), + "Enclosed Ideographic Supplement": range(127488, 127744), + "Miscellaneous Symbols and Pictographs": range(127744, 128512), + "Emoticons range(Emoji)": range(128512, 128592), + "Ornamental Dingbats": range(128592, 128640), + "Transport and Map Symbols": range(128640, 128768), + "Alchemical Symbols": range(128768, 128896), + "Geometric Shapes Extended": range(128896, 129024), + "Supplemental Arrows-C": range(129024, 129280), + "Supplemental Symbols and Pictographs": range(129280, 129536), + "Chess Symbols": range(129536, 129648), + "Symbols and Pictographs Extended-A": range(129648, 129792), + "Symbols for Legacy Computing": range(129792, 130048), + "CJK Unified Ideographs Extension B": range(131072, 173792), + "CJK Unified Ideographs Extension C": range(173824, 177984), + "CJK Unified Ideographs Extension D": range(177984, 178208), + "CJK Unified Ideographs Extension E": range(178208, 183984), + "CJK Unified Ideographs Extension F": range(183984, 191472), + "CJK Compatibility Ideographs Supplement": range(194560, 195104), + "CJK Unified Ideographs Extension G": range(196608, 201552), + "CJK Unified Ideographs Extension H": range(201552, 205744), + "Tags": range(917504, 917632), + "Variation Selectors Supplement": range(917760, 918000), + "Supplementary Private Use Area-A": range(983040, 1048576), + "Supplementary Private Use Area-B": range(1048576, 1114112), +} + + +UNICODE_SECONDARY_RANGE_KEYWORD: list[str] = [ + "Supplement", + "Extended", + "Extensions", + "Modifier", + "Marks", + "Punctuation", + "Symbols", + "Forms", + "Operators", + "Miscellaneous", + "Drawing", + "Block", + "Shapes", + "Supplemental", + "Tags", +] + +RE_POSSIBLE_ENCODING_INDICATION = re_compile( + r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", + IGNORECASE, +) + +IANA_NO_ALIASES = [ + "cp720", + "cp737", + "cp856", + "cp874", + "cp875", + "cp1006", + "koi8_r", + "koi8_t", + "koi8_u", +] + +IANA_SUPPORTED: list[str] = sorted( + filter( + lambda x: x.endswith("_codec") is False + and x not in {"rot_13", "tactis", "mbcs"}, + list(set(aliases.values())) + IANA_NO_ALIASES, + ) +) + +IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED) + +# pre-computed code page that are similar using the function cp_similarity. +IANA_SUPPORTED_SIMILAR: dict[str, list[str]] = { + "cp037": ["cp1026", "cp1140", "cp273", "cp500"], + "cp1026": ["cp037", "cp1140", "cp273", "cp500"], + "cp1125": ["cp866"], + "cp1140": ["cp037", "cp1026", "cp273", "cp500"], + "cp1250": ["iso8859_2"], + "cp1251": ["kz1048", "ptcp154"], + "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], + "cp1253": ["iso8859_7"], + "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], + "cp1257": ["iso8859_13"], + "cp273": ["cp037", "cp1026", "cp1140", "cp500"], + "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], + "cp500": ["cp037", "cp1026", "cp1140", "cp273"], + "cp850": ["cp437", "cp857", "cp858", "cp865"], + "cp857": ["cp850", "cp858", "cp865"], + "cp858": ["cp437", "cp850", "cp857", "cp865"], + "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], + "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], + "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], + "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], + "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], + "cp866": ["cp1125"], + "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], + "iso8859_11": ["tis_620"], + "iso8859_13": ["cp1257"], + "iso8859_14": [ + "iso8859_10", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_15": [ + "cp1252", + "cp1254", + "iso8859_10", + "iso8859_14", + "iso8859_16", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_16": [ + "iso8859_14", + "iso8859_15", + "iso8859_2", + "iso8859_3", + "iso8859_9", + "latin_1", + ], + "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], + "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], + "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], + "iso8859_7": ["cp1253"], + "iso8859_9": [ + "cp1252", + "cp1254", + "cp1258", + "iso8859_10", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_4", + "latin_1", + ], + "kz1048": ["cp1251", "ptcp154"], + "latin_1": [ + "cp1252", + "cp1254", + "cp1258", + "iso8859_10", + "iso8859_14", + "iso8859_15", + "iso8859_16", + "iso8859_3", + "iso8859_4", + "iso8859_9", + ], + "mac_iceland": ["mac_roman", "mac_turkish"], + "mac_roman": ["mac_iceland", "mac_turkish"], + "mac_turkish": ["mac_iceland", "mac_roman"], + "ptcp154": ["cp1251", "kz1048"], + "tis_620": ["iso8859_11"], +} + + +CHARDET_CORRESPONDENCE: dict[str, str] = { + "iso2022_kr": "ISO-2022-KR", + "iso2022_jp": "ISO-2022-JP", + "euc_kr": "EUC-KR", + "tis_620": "TIS-620", + "utf_32": "UTF-32", + "euc_jp": "EUC-JP", + "koi8_r": "KOI8-R", + "iso8859_1": "ISO-8859-1", + "iso8859_2": "ISO-8859-2", + "iso8859_5": "ISO-8859-5", + "iso8859_6": "ISO-8859-6", + "iso8859_7": "ISO-8859-7", + "iso8859_8": "ISO-8859-8", + "utf_16": "UTF-16", + "cp855": "IBM855", + "mac_cyrillic": "MacCyrillic", + "gb2312": "GB2312", + "gb18030": "GB18030", + "cp932": "CP932", + "cp866": "IBM866", + "utf_8": "utf-8", + "utf_8_sig": "UTF-8-SIG", + "shift_jis": "SHIFT_JIS", + "big5": "Big5", + "cp1250": "windows-1250", + "cp1251": "windows-1251", + "cp1252": "Windows-1252", + "cp1253": "windows-1253", + "cp1255": "windows-1255", + "cp1256": "windows-1256", + "cp1254": "Windows-1254", + "cp949": "CP949", +} + + +COMMON_SAFE_ASCII_CHARACTERS: set[str] = { + "<", + ">", + "=", + ":", + "/", + "&", + ";", + "{", + "}", + "[", + "]", + ",", + "|", + '"', + "-", + "(", + ")", +} + +# Sample character sets — replace with full lists if needed +COMMON_CHINESE_CHARACTERS = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严龙飞" + +COMMON_JAPANESE_CHARACTERS = "日一国年大十二本中長出三時行見月分後前生五間上東四今金九入学高円子外八六下来気小七山話女北午百書先名川千水半男西電校語土木聞食車何南万毎白天母火右読友左休父雨" + +COMMON_KOREAN_CHARACTERS = "一二三四五六七八九十百千萬上下左右中人女子大小山川日月火水木金土父母天地國名年時文校學生" + +# Combine all into a set +COMMON_CJK_CHARACTERS = set( + "".join( + [ + COMMON_CHINESE_CHARACTERS, + COMMON_JAPANESE_CHARACTERS, + COMMON_KOREAN_CHARACTERS, + ] + ) +) + +KO_NAMES: set[str] = {"johab", "cp949", "euc_kr"} +ZH_NAMES: set[str] = {"big5", "cp950", "big5hkscs", "hz"} + +# Logging LEVEL below DEBUG +TRACE: int = 5 + + +# Language label that contain the em dash "—" +# character are to be considered alternative seq to origin +FREQUENCIES: dict[str, list[str]] = { + "English": [ + "e", + "a", + "t", + "i", + "o", + "n", + "s", + "r", + "h", + "l", + "d", + "c", + "u", + "m", + "f", + "p", + "g", + "w", + "y", + "b", + "v", + "k", + "x", + "j", + "z", + "q", + ], + "English—": [ + "e", + "a", + "t", + "i", + "o", + "n", + "s", + "r", + "h", + "l", + "d", + "c", + "m", + "u", + "f", + "p", + "g", + "w", + "b", + "y", + "v", + "k", + "j", + "x", + "z", + "q", + ], + "German": [ + "e", + "n", + "i", + "r", + "s", + "t", + "a", + "d", + "h", + "u", + "l", + "g", + "o", + "c", + "m", + "b", + "f", + "k", + "w", + "z", + "p", + "v", + "ü", + "ä", + "ö", + "j", + ], + "French": [ + "e", + "a", + "s", + "n", + "i", + "t", + "r", + "l", + "u", + "o", + "d", + "c", + "p", + "m", + "é", + "v", + "g", + "f", + "b", + "h", + "q", + "à", + "x", + "è", + "y", + "j", + ], + "Dutch": [ + "e", + "n", + "a", + "i", + "r", + "t", + "o", + "d", + "s", + "l", + "g", + "h", + "v", + "m", + "u", + "k", + "c", + "p", + "b", + "w", + "j", + "z", + "f", + "y", + "x", + "ë", + ], + "Italian": [ + "e", + "i", + "a", + "o", + "n", + "l", + "t", + "r", + "s", + "c", + "d", + "u", + "p", + "m", + "g", + "v", + "f", + "b", + "z", + "h", + "q", + "è", + "à", + "k", + "y", + "ò", + ], + "Polish": [ + "a", + "i", + "o", + "e", + "n", + "r", + "z", + "w", + "s", + "c", + "t", + "k", + "y", + "d", + "p", + "m", + "u", + "l", + "j", + "ł", + "g", + "b", + "h", + "ą", + "ę", + "ó", + ], + "Spanish": [ + "e", + "a", + "o", + "n", + "s", + "r", + "i", + "l", + "d", + "t", + "c", + "u", + "m", + "p", + "b", + "g", + "v", + "f", + "y", + "ó", + "h", + "q", + "í", + "j", + "z", + "á", + ], + "Russian": [ + "о", + "а", + "е", + "и", + "н", + "с", + "т", + "р", + "в", + "л", + "к", + "м", + "д", + "п", + "у", + "г", + "я", + "ы", + "з", + "б", + "й", + "ь", + "ч", + "х", + "ж", + "ц", + ], + # Jap-Kanji + "Japanese": [ + "人", + "一", + "大", + "亅", + "丁", + "丨", + "竹", + "笑", + "口", + "日", + "今", + "二", + "彳", + "行", + "十", + "土", + "丶", + "寸", + "寺", + "時", + "乙", + "丿", + "乂", + "气", + "気", + "冂", + "巾", + "亠", + "市", + "目", + "儿", + "見", + "八", + "小", + "凵", + "県", + "月", + "彐", + "門", + "間", + "木", + "東", + "山", + "出", + "本", + "中", + "刀", + "分", + "耳", + "又", + "取", + "最", + "言", + "田", + "心", + "思", + "刂", + "前", + "京", + "尹", + "事", + "生", + "厶", + "云", + "会", + "未", + "来", + "白", + "冫", + "楽", + "灬", + "馬", + "尸", + "尺", + "駅", + "明", + "耂", + "者", + "了", + "阝", + "都", + "高", + "卜", + "占", + "厂", + "广", + "店", + "子", + "申", + "奄", + "亻", + "俺", + "上", + "方", + "冖", + "学", + "衣", + "艮", + "食", + "自", + ], + # Jap-Katakana + "Japanese—": [ + "ー", + "ン", + "ス", + "・", + "ル", + "ト", + "リ", + "イ", + "ア", + "ラ", + "ッ", + "ク", + "ド", + "シ", + "レ", + "ジ", + "タ", + "フ", + "ロ", + "カ", + "テ", + "マ", + "ィ", + "グ", + "バ", + "ム", + "プ", + "オ", + "コ", + "デ", + "ニ", + "ウ", + "メ", + "サ", + "ビ", + "ナ", + "ブ", + "ャ", + "エ", + "ュ", + "チ", + "キ", + "ズ", + "ダ", + "パ", + "ミ", + "ェ", + "ョ", + "ハ", + "セ", + "ベ", + "ガ", + "モ", + "ツ", + "ネ", + "ボ", + "ソ", + "ノ", + "ァ", + "ヴ", + "ワ", + "ポ", + "ペ", + "ピ", + "ケ", + "ゴ", + "ギ", + "ザ", + "ホ", + "ゲ", + "ォ", + "ヤ", + "ヒ", + "ユ", + "ヨ", + "ヘ", + "ゼ", + "ヌ", + "ゥ", + "ゾ", + "ヶ", + "ヂ", + "ヲ", + "ヅ", + "ヵ", + "ヱ", + "ヰ", + "ヮ", + "ヽ", + "゠", + "ヾ", + "ヷ", + "ヿ", + "ヸ", + "ヹ", + "ヺ", + ], + # Jap-Hiragana + "Japanese——": [ + "の", + "に", + "る", + "た", + "と", + "は", + "し", + "い", + "を", + "で", + "て", + "が", + "な", + "れ", + "か", + "ら", + "さ", + "っ", + "り", + "す", + "あ", + "も", + "こ", + "ま", + "う", + "く", + "よ", + "き", + "ん", + "め", + "お", + "け", + "そ", + "つ", + "だ", + "や", + "え", + "ど", + "わ", + "ち", + "み", + "せ", + "じ", + "ば", + "へ", + "び", + "ず", + "ろ", + "ほ", + "げ", + "む", + "べ", + "ひ", + "ょ", + "ゆ", + "ぶ", + "ご", + "ゃ", + "ね", + "ふ", + "ぐ", + "ぎ", + "ぼ", + "ゅ", + "づ", + "ざ", + "ぞ", + "ぬ", + "ぜ", + "ぱ", + "ぽ", + "ぷ", + "ぴ", + "ぃ", + "ぁ", + "ぇ", + "ぺ", + "ゞ", + "ぢ", + "ぉ", + "ぅ", + "ゐ", + "ゝ", + "ゑ", + "゛", + "゜", + "ゎ", + "ゔ", + "゚", + "ゟ", + "゙", + "ゕ", + "ゖ", + ], + "Portuguese": [ + "a", + "e", + "o", + "s", + "i", + "r", + "d", + "n", + "t", + "m", + "u", + "c", + "l", + "p", + "g", + "v", + "b", + "f", + "h", + "ã", + "q", + "é", + "ç", + "á", + "z", + "í", + ], + "Swedish": [ + "e", + "a", + "n", + "r", + "t", + "s", + "i", + "l", + "d", + "o", + "m", + "k", + "g", + "v", + "h", + "f", + "u", + "p", + "ä", + "c", + "b", + "ö", + "å", + "y", + "j", + "x", + ], + "Chinese": [ + "的", + "一", + "是", + "不", + "了", + "在", + "人", + "有", + "我", + "他", + "这", + "个", + "们", + "中", + "来", + "上", + "大", + "为", + "和", + "国", + "地", + "到", + "以", + "说", + "时", + "要", + "就", + "出", + "会", + "可", + "也", + "你", + "对", + "生", + "能", + "而", + "子", + "那", + "得", + "于", + "着", + "下", + "自", + "之", + "年", + "过", + "发", + "后", + "作", + "里", + "用", + "道", + "行", + "所", + "然", + "家", + "种", + "事", + "成", + "方", + "多", + "经", + "么", + "去", + "法", + "学", + "如", + "都", + "同", + "现", + "当", + "没", + "动", + "面", + "起", + "看", + "定", + "天", + "分", + "还", + "进", + "好", + "小", + "部", + "其", + "些", + "主", + "样", + "理", + "心", + "她", + "本", + "前", + "开", + "但", + "因", + "只", + "从", + "想", + "实", + ], + "Ukrainian": [ + "о", + "а", + "н", + "і", + "и", + "р", + "в", + "т", + "е", + "с", + "к", + "л", + "у", + "д", + "м", + "п", + "з", + "я", + "ь", + "б", + "г", + "й", + "ч", + "х", + "ц", + "ї", + ], + "Norwegian": [ + "e", + "r", + "n", + "t", + "a", + "s", + "i", + "o", + "l", + "d", + "g", + "k", + "m", + "v", + "f", + "p", + "u", + "b", + "h", + "å", + "y", + "j", + "ø", + "c", + "æ", + "w", + ], + "Finnish": [ + "a", + "i", + "n", + "t", + "e", + "s", + "l", + "o", + "u", + "k", + "ä", + "m", + "r", + "v", + "j", + "h", + "p", + "y", + "d", + "ö", + "g", + "c", + "b", + "f", + "w", + "z", + ], + "Vietnamese": [ + "n", + "h", + "t", + "i", + "c", + "g", + "a", + "o", + "u", + "m", + "l", + "r", + "à", + "đ", + "s", + "e", + "v", + "p", + "b", + "y", + "ư", + "d", + "á", + "k", + "ộ", + "ế", + ], + "Czech": [ + "o", + "e", + "a", + "n", + "t", + "s", + "i", + "l", + "v", + "r", + "k", + "d", + "u", + "m", + "p", + "í", + "c", + "h", + "z", + "á", + "y", + "j", + "b", + "ě", + "é", + "ř", + ], + "Hungarian": [ + "e", + "a", + "t", + "l", + "s", + "n", + "k", + "r", + "i", + "o", + "z", + "á", + "é", + "g", + "m", + "b", + "y", + "v", + "d", + "h", + "u", + "p", + "j", + "ö", + "f", + "c", + ], + "Korean": [ + "이", + "다", + "에", + "의", + "는", + "로", + "하", + "을", + "가", + "고", + "지", + "서", + "한", + "은", + "기", + "으", + "년", + "대", + "사", + "시", + "를", + "리", + "도", + "인", + "스", + "일", + ], + "Indonesian": [ + "a", + "n", + "e", + "i", + "r", + "t", + "u", + "s", + "d", + "k", + "m", + "l", + "g", + "p", + "b", + "o", + "h", + "y", + "j", + "c", + "w", + "f", + "v", + "z", + "x", + "q", + ], + "Turkish": [ + "a", + "e", + "i", + "n", + "r", + "l", + "ı", + "k", + "d", + "t", + "s", + "m", + "y", + "u", + "o", + "b", + "ü", + "ş", + "v", + "g", + "z", + "h", + "c", + "p", + "ç", + "ğ", + ], + "Romanian": [ + "e", + "i", + "a", + "r", + "n", + "t", + "u", + "l", + "o", + "c", + "s", + "d", + "p", + "m", + "ă", + "f", + "v", + "î", + "g", + "b", + "ș", + "ț", + "z", + "h", + "â", + "j", + ], + "Farsi": [ + "ا", + "ی", + "ر", + "د", + "ن", + "ه", + "و", + "م", + "ت", + "ب", + "س", + "ل", + "ک", + "ش", + "ز", + "ف", + "گ", + "ع", + "خ", + "ق", + "ج", + "آ", + "پ", + "ح", + "ط", + "ص", + ], + "Arabic": [ + "ا", + "ل", + "ي", + "م", + "و", + "ن", + "ر", + "ت", + "ب", + "ة", + "ع", + "د", + "س", + "ف", + "ه", + "ك", + "ق", + "أ", + "ح", + "ج", + "ش", + "ط", + "ص", + "ى", + "خ", + "إ", + ], + "Danish": [ + "e", + "r", + "n", + "t", + "a", + "i", + "s", + "d", + "l", + "o", + "g", + "m", + "k", + "f", + "v", + "u", + "b", + "h", + "p", + "å", + "y", + "ø", + "æ", + "c", + "j", + "w", + ], + "Serbian": [ + "а", + "и", + "о", + "е", + "н", + "р", + "с", + "у", + "т", + "к", + "ј", + "в", + "д", + "м", + "п", + "л", + "г", + "з", + "б", + "a", + "i", + "e", + "o", + "n", + "ц", + "ш", + ], + "Lithuanian": [ + "i", + "a", + "s", + "o", + "r", + "e", + "t", + "n", + "u", + "k", + "m", + "l", + "p", + "v", + "d", + "j", + "g", + "ė", + "b", + "y", + "ų", + "š", + "ž", + "c", + "ą", + "į", + ], + "Slovene": [ + "e", + "a", + "i", + "o", + "n", + "r", + "s", + "l", + "t", + "j", + "v", + "k", + "d", + "p", + "m", + "u", + "z", + "b", + "g", + "h", + "č", + "c", + "š", + "ž", + "f", + "y", + ], + "Slovak": [ + "o", + "a", + "e", + "n", + "i", + "r", + "v", + "t", + "s", + "l", + "k", + "d", + "m", + "p", + "u", + "c", + "h", + "j", + "b", + "z", + "á", + "y", + "ý", + "í", + "č", + "é", + ], + "Hebrew": [ + "י", + "ו", + "ה", + "ל", + "ר", + "ב", + "ת", + "מ", + "א", + "ש", + "נ", + "ע", + "ם", + "ד", + "ק", + "ח", + "פ", + "ס", + "כ", + "ג", + "ט", + "צ", + "ן", + "ז", + "ך", + ], + "Bulgarian": [ + "а", + "и", + "о", + "е", + "н", + "т", + "р", + "с", + "в", + "л", + "к", + "д", + "п", + "м", + "з", + "г", + "я", + "ъ", + "у", + "б", + "ч", + "ц", + "й", + "ж", + "щ", + "х", + ], + "Croatian": [ + "a", + "i", + "o", + "e", + "n", + "r", + "j", + "s", + "t", + "u", + "k", + "l", + "v", + "d", + "m", + "p", + "g", + "z", + "b", + "c", + "č", + "h", + "š", + "ž", + "ć", + "f", + ], + "Hindi": [ + "क", + "र", + "स", + "न", + "त", + "म", + "ह", + "प", + "य", + "ल", + "व", + "ज", + "द", + "ग", + "ब", + "श", + "ट", + "अ", + "ए", + "थ", + "भ", + "ड", + "च", + "ध", + "ष", + "इ", + ], + "Estonian": [ + "a", + "i", + "e", + "s", + "t", + "l", + "u", + "n", + "o", + "k", + "r", + "d", + "m", + "v", + "g", + "p", + "j", + "h", + "ä", + "b", + "õ", + "ü", + "f", + "c", + "ö", + "y", + ], + "Thai": [ + "า", + "น", + "ร", + "อ", + "ก", + "เ", + "ง", + "ม", + "ย", + "ล", + "ว", + "ด", + "ท", + "ส", + "ต", + "ะ", + "ป", + "บ", + "ค", + "ห", + "แ", + "จ", + "พ", + "ช", + "ข", + "ใ", + ], + "Greek": [ + "α", + "τ", + "ο", + "ι", + "ε", + "ν", + "ρ", + "σ", + "κ", + "η", + "π", + "ς", + "υ", + "μ", + "λ", + "ί", + "ό", + "ά", + "γ", + "έ", + "δ", + "ή", + "ω", + "χ", + "θ", + "ύ", + ], + "Tamil": [ + "க", + "த", + "ப", + "ட", + "ர", + "ம", + "ல", + "ன", + "வ", + "ற", + "ய", + "ள", + "ச", + "ந", + "இ", + "ண", + "அ", + "ஆ", + "ழ", + "ங", + "எ", + "உ", + "ஒ", + "ஸ", + ], + "Kazakh": [ + "а", + "ы", + "е", + "н", + "т", + "р", + "л", + "і", + "д", + "с", + "м", + "қ", + "к", + "о", + "б", + "и", + "у", + "ғ", + "ж", + "ң", + "з", + "ш", + "й", + "п", + "г", + "ө", + ], +} + +LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES) diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..360a3107bdce817594db33de158e71d9fe793a3b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/legacy.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from warnings import warn + +from .api import from_bytes +from .constant import CHARDET_CORRESPONDENCE, TOO_SMALL_SEQUENCE + +# TODO: remove this check when dropping Python 3.7 support +if TYPE_CHECKING: + from typing_extensions import TypedDict + + class ResultDict(TypedDict): + encoding: str | None + language: str + confidence: float | None + + +def detect( + byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any +) -> ResultDict: + """ + chardet legacy method + Detect the encoding of the given byte string. It should be mostly backward-compatible. + Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it) + This function is deprecated and should be used to migrate your project easily, consult the documentation for + further information. Not planned for removal. + + :param byte_str: The byte sequence to examine. + :param should_rename_legacy: Should we rename legacy encodings + to their more modern equivalents? + """ + if len(kwargs): + warn( + f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()" + ) + + if not isinstance(byte_str, (bytearray, bytes)): + raise TypeError( # pragma: nocover + f"Expected object of type bytes or bytearray, got: {type(byte_str)}" + ) + + if isinstance(byte_str, bytearray): + byte_str = bytes(byte_str) + + r = from_bytes(byte_str).best() + + encoding = r.encoding if r is not None else None + language = r.language if r is not None and r.language != "Unknown" else "" + confidence = 1.0 - r.chaos if r is not None else None + + # automatically lower confidence + # on small bytes samples. + # https://github.com/jawah/charset_normalizer/issues/391 + if ( + confidence is not None + and confidence >= 0.9 + and encoding + not in { + "utf_8", + "ascii", + } + and r.bom is False # type: ignore[union-attr] + and len(byte_str) < TOO_SMALL_SEQUENCE + ): + confidence -= 0.2 + + # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process + # but chardet does return 'utf-8-sig' and it is a valid codec name. + if r is not None and encoding == "utf_8" and r.bom: + encoding += "_sig" + + if should_rename_legacy is False and encoding in CHARDET_CORRESPONDENCE: + encoding = CHARDET_CORRESPONDENCE[encoding] + + return { + "encoding": encoding, + "language": language, + "confidence": confidence, + } diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py new file mode 100644 index 0000000000000000000000000000000000000000..12ce024bd34c7eee369ddf438f5534e855a59839 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/md.py @@ -0,0 +1,635 @@ +from __future__ import annotations + +from functools import lru_cache +from logging import getLogger + +from .constant import ( + COMMON_SAFE_ASCII_CHARACTERS, + TRACE, + UNICODE_SECONDARY_RANGE_KEYWORD, +) +from .utils import ( + is_accentuated, + is_arabic, + is_arabic_isolated_form, + is_case_variable, + is_cjk, + is_emoticon, + is_hangul, + is_hiragana, + is_katakana, + is_latin, + is_punctuation, + is_separator, + is_symbol, + is_thai, + is_unprintable, + remove_accent, + unicode_range, + is_cjk_uncommon, +) + + +class MessDetectorPlugin: + """ + Base abstract class used for mess detection plugins. + All detectors MUST extend and implement given methods. + """ + + def eligible(self, character: str) -> bool: + """ + Determine if given character should be fed in. + """ + raise NotImplementedError # pragma: nocover + + def feed(self, character: str) -> None: + """ + The main routine to be executed upon character. + Insert the logic in witch the text would be considered chaotic. + """ + raise NotImplementedError # pragma: nocover + + def reset(self) -> None: # pragma: no cover + """ + Permit to reset the plugin to the initial state. + """ + raise NotImplementedError + + @property + def ratio(self) -> float: + """ + Compute the chaos ratio based on what your feed() has seen. + Must NOT be lower than 0.; No restriction gt 0. + """ + raise NotImplementedError # pragma: nocover + + +class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._punctuation_count: int = 0 + self._symbol_count: int = 0 + self._character_count: int = 0 + + self._last_printable_char: str | None = None + self._frenzy_symbol_in_word: bool = False + + def eligible(self, character: str) -> bool: + return character.isprintable() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if ( + character != self._last_printable_char + and character not in COMMON_SAFE_ASCII_CHARACTERS + ): + if is_punctuation(character): + self._punctuation_count += 1 + elif ( + character.isdigit() is False + and is_symbol(character) + and is_emoticon(character) is False + ): + self._symbol_count += 2 + + self._last_printable_char = character + + def reset(self) -> None: # Abstract + self._punctuation_count = 0 + self._character_count = 0 + self._symbol_count = 0 + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + ratio_of_punctuation: float = ( + self._punctuation_count + self._symbol_count + ) / self._character_count + + return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0 + + +class TooManyAccentuatedPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._character_count: int = 0 + self._accentuated_count: int = 0 + + def eligible(self, character: str) -> bool: + return character.isalpha() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_accentuated(character): + self._accentuated_count += 1 + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._accentuated_count = 0 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + ratio_of_accentuation: float = self._accentuated_count / self._character_count + return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0 + + +class UnprintablePlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._unprintable_count: int = 0 + self._character_count: int = 0 + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + if is_unprintable(character): + self._unprintable_count += 1 + self._character_count += 1 + + def reset(self) -> None: # Abstract + self._unprintable_count = 0 + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return (self._unprintable_count * 8) / self._character_count + + +class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._successive_count: int = 0 + self._character_count: int = 0 + + self._last_latin_character: str | None = None + + def eligible(self, character: str) -> bool: + return character.isalpha() and is_latin(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + if ( + self._last_latin_character is not None + and is_accentuated(character) + and is_accentuated(self._last_latin_character) + ): + if character.isupper() and self._last_latin_character.isupper(): + self._successive_count += 1 + # Worse if its the same char duplicated with different accent. + if remove_accent(character) == remove_accent(self._last_latin_character): + self._successive_count += 1 + self._last_latin_character = character + + def reset(self) -> None: # Abstract + self._successive_count = 0 + self._character_count = 0 + self._last_latin_character = None + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return (self._successive_count * 2) / self._character_count + + +class SuspiciousRange(MessDetectorPlugin): + def __init__(self) -> None: + self._suspicious_successive_range_count: int = 0 + self._character_count: int = 0 + self._last_printable_seen: str | None = None + + def eligible(self, character: str) -> bool: + return character.isprintable() + + def feed(self, character: str) -> None: + self._character_count += 1 + + if ( + character.isspace() + or is_punctuation(character) + or character in COMMON_SAFE_ASCII_CHARACTERS + ): + self._last_printable_seen = None + return + + if self._last_printable_seen is None: + self._last_printable_seen = character + return + + unicode_range_a: str | None = unicode_range(self._last_printable_seen) + unicode_range_b: str | None = unicode_range(character) + + if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): + self._suspicious_successive_range_count += 1 + + self._last_printable_seen = character + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._suspicious_successive_range_count = 0 + self._last_printable_seen = None + + @property + def ratio(self) -> float: + if self._character_count <= 13: + return 0.0 + + ratio_of_suspicious_range_usage: float = ( + self._suspicious_successive_range_count * 2 + ) / self._character_count + + return ratio_of_suspicious_range_usage + + +class SuperWeirdWordPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._word_count: int = 0 + self._bad_word_count: int = 0 + self._foreign_long_count: int = 0 + + self._is_current_word_bad: bool = False + self._foreign_long_watch: bool = False + + self._character_count: int = 0 + self._bad_character_count: int = 0 + + self._buffer: str = "" + self._buffer_accent_count: int = 0 + self._buffer_glyph_count: int = 0 + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + if character.isalpha(): + self._buffer += character + if is_accentuated(character): + self._buffer_accent_count += 1 + if ( + self._foreign_long_watch is False + and (is_latin(character) is False or is_accentuated(character)) + and is_cjk(character) is False + and is_hangul(character) is False + and is_katakana(character) is False + and is_hiragana(character) is False + and is_thai(character) is False + ): + self._foreign_long_watch = True + if ( + is_cjk(character) + or is_hangul(character) + or is_katakana(character) + or is_hiragana(character) + or is_thai(character) + ): + self._buffer_glyph_count += 1 + return + if not self._buffer: + return + if ( + character.isspace() or is_punctuation(character) or is_separator(character) + ) and self._buffer: + self._word_count += 1 + buffer_length: int = len(self._buffer) + + self._character_count += buffer_length + + if buffer_length >= 4: + if self._buffer_accent_count / buffer_length >= 0.5: + self._is_current_word_bad = True + # Word/Buffer ending with an upper case accentuated letter are so rare, + # that we will consider them all as suspicious. Same weight as foreign_long suspicious. + elif ( + is_accentuated(self._buffer[-1]) + and self._buffer[-1].isupper() + and all(_.isupper() for _ in self._buffer) is False + ): + self._foreign_long_count += 1 + self._is_current_word_bad = True + elif self._buffer_glyph_count == 1: + self._is_current_word_bad = True + self._foreign_long_count += 1 + if buffer_length >= 24 and self._foreign_long_watch: + camel_case_dst = [ + i + for c, i in zip(self._buffer, range(0, buffer_length)) + if c.isupper() + ] + probable_camel_cased: bool = False + + if camel_case_dst and (len(camel_case_dst) / buffer_length <= 0.3): + probable_camel_cased = True + + if not probable_camel_cased: + self._foreign_long_count += 1 + self._is_current_word_bad = True + + if self._is_current_word_bad: + self._bad_word_count += 1 + self._bad_character_count += len(self._buffer) + self._is_current_word_bad = False + + self._foreign_long_watch = False + self._buffer = "" + self._buffer_accent_count = 0 + self._buffer_glyph_count = 0 + elif ( + character not in {"<", ">", "-", "=", "~", "|", "_"} + and character.isdigit() is False + and is_symbol(character) + ): + self._is_current_word_bad = True + self._buffer += character + + def reset(self) -> None: # Abstract + self._buffer = "" + self._is_current_word_bad = False + self._foreign_long_watch = False + self._bad_word_count = 0 + self._word_count = 0 + self._character_count = 0 + self._bad_character_count = 0 + self._foreign_long_count = 0 + + @property + def ratio(self) -> float: + if self._word_count <= 10 and self._foreign_long_count == 0: + return 0.0 + + return self._bad_character_count / self._character_count + + +class CjkUncommonPlugin(MessDetectorPlugin): + """ + Detect messy CJK text that probably means nothing. + """ + + def __init__(self) -> None: + self._character_count: int = 0 + self._uncommon_count: int = 0 + + def eligible(self, character: str) -> bool: + return is_cjk(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_cjk_uncommon(character): + self._uncommon_count += 1 + return + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._uncommon_count = 0 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + uncommon_form_usage: float = self._uncommon_count / self._character_count + + # we can be pretty sure it's garbage when uncommon characters are widely + # used. otherwise it could just be traditional chinese for example. + return uncommon_form_usage / 10 if uncommon_form_usage > 0.5 else 0.0 + + +class ArchaicUpperLowerPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._buf: bool = False + + self._character_count_since_last_sep: int = 0 + + self._successive_upper_lower_count: int = 0 + self._successive_upper_lower_count_final: int = 0 + + self._character_count: int = 0 + + self._last_alpha_seen: str | None = None + self._current_ascii_only: bool = True + + def eligible(self, character: str) -> bool: + return True + + def feed(self, character: str) -> None: + is_concerned = character.isalpha() and is_case_variable(character) + chunk_sep = is_concerned is False + + if chunk_sep and self._character_count_since_last_sep > 0: + if ( + self._character_count_since_last_sep <= 64 + and character.isdigit() is False + and self._current_ascii_only is False + ): + self._successive_upper_lower_count_final += ( + self._successive_upper_lower_count + ) + + self._successive_upper_lower_count = 0 + self._character_count_since_last_sep = 0 + self._last_alpha_seen = None + self._buf = False + self._character_count += 1 + self._current_ascii_only = True + + return + + if self._current_ascii_only is True and character.isascii() is False: + self._current_ascii_only = False + + if self._last_alpha_seen is not None: + if (character.isupper() and self._last_alpha_seen.islower()) or ( + character.islower() and self._last_alpha_seen.isupper() + ): + if self._buf is True: + self._successive_upper_lower_count += 2 + self._buf = False + else: + self._buf = True + else: + self._buf = False + + self._character_count += 1 + self._character_count_since_last_sep += 1 + self._last_alpha_seen = character + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._character_count_since_last_sep = 0 + self._successive_upper_lower_count = 0 + self._successive_upper_lower_count_final = 0 + self._last_alpha_seen = None + self._buf = False + self._current_ascii_only = True + + @property + def ratio(self) -> float: + if self._character_count == 0: + return 0.0 + + return self._successive_upper_lower_count_final / self._character_count + + +class ArabicIsolatedFormPlugin(MessDetectorPlugin): + def __init__(self) -> None: + self._character_count: int = 0 + self._isolated_form_count: int = 0 + + def reset(self) -> None: # Abstract + self._character_count = 0 + self._isolated_form_count = 0 + + def eligible(self, character: str) -> bool: + return is_arabic(character) + + def feed(self, character: str) -> None: + self._character_count += 1 + + if is_arabic_isolated_form(character): + self._isolated_form_count += 1 + + @property + def ratio(self) -> float: + if self._character_count < 8: + return 0.0 + + isolated_form_usage: float = self._isolated_form_count / self._character_count + + return isolated_form_usage + + +@lru_cache(maxsize=1024) +def is_suspiciously_successive_range( + unicode_range_a: str | None, unicode_range_b: str | None +) -> bool: + """ + Determine if two Unicode range seen next to each other can be considered as suspicious. + """ + if unicode_range_a is None or unicode_range_b is None: + return True + + if unicode_range_a == unicode_range_b: + return False + + if "Latin" in unicode_range_a and "Latin" in unicode_range_b: + return False + + if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b: + return False + + # Latin characters can be accompanied with a combining diacritical mark + # eg. Vietnamese. + if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and ( + "Combining" in unicode_range_a or "Combining" in unicode_range_b + ): + return False + + keywords_range_a, keywords_range_b = ( + unicode_range_a.split(" "), + unicode_range_b.split(" "), + ) + + for el in keywords_range_a: + if el in UNICODE_SECONDARY_RANGE_KEYWORD: + continue + if el in keywords_range_b: + return False + + # Japanese Exception + range_a_jp_chars, range_b_jp_chars = ( + unicode_range_a + in ( + "Hiragana", + "Katakana", + ), + unicode_range_b in ("Hiragana", "Katakana"), + ) + if (range_a_jp_chars or range_b_jp_chars) and ( + "CJK" in unicode_range_a or "CJK" in unicode_range_b + ): + return False + if range_a_jp_chars and range_b_jp_chars: + return False + + if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b: + if "CJK" in unicode_range_a or "CJK" in unicode_range_b: + return False + if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": + return False + + # Chinese/Japanese use dedicated range for punctuation and/or separators. + if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or ( + unicode_range_a in ["Katakana", "Hiragana"] + and unicode_range_b in ["Katakana", "Hiragana"] + ): + if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b: + return False + if "Forms" in unicode_range_a or "Forms" in unicode_range_b: + return False + if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": + return False + + return True + + +@lru_cache(maxsize=2048) +def mess_ratio( + decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False +) -> float: + """ + Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. + """ + + detectors: list[MessDetectorPlugin] = [ + md_class() for md_class in MessDetectorPlugin.__subclasses__() + ] + + length: int = len(decoded_sequence) + 1 + + mean_mess_ratio: float = 0.0 + + if length < 512: + intermediary_mean_mess_ratio_calc: int = 32 + elif length <= 1024: + intermediary_mean_mess_ratio_calc = 64 + else: + intermediary_mean_mess_ratio_calc = 128 + + for character, index in zip(decoded_sequence + "\n", range(length)): + for detector in detectors: + if detector.eligible(character): + detector.feed(character) + + if ( + index > 0 and index % intermediary_mean_mess_ratio_calc == 0 + ) or index == length - 1: + mean_mess_ratio = sum(dt.ratio for dt in detectors) + + if mean_mess_ratio >= maximum_threshold: + break + + if debug: + logger = getLogger("charset_normalizer") + + logger.log( + TRACE, + "Mess-detector extended-analysis start. " + f"intermediary_mean_mess_ratio_calc={intermediary_mean_mess_ratio_calc} mean_mess_ratio={mean_mess_ratio} " + f"maximum_threshold={maximum_threshold}", + ) + + if len(decoded_sequence) > 16: + logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}") + logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}") + + for dt in detectors: + logger.log(TRACE, f"{dt.__class__}: {dt.ratio}") + + return round(mean_mess_ratio, 3) diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py new file mode 100644 index 0000000000000000000000000000000000000000..1042758f873d2a54f7078c5411b17ffc11dca4ee --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/models.py @@ -0,0 +1,360 @@ +from __future__ import annotations + +from encodings.aliases import aliases +from hashlib import sha256 +from json import dumps +from re import sub +from typing import Any, Iterator, List, Tuple + +from .constant import RE_POSSIBLE_ENCODING_INDICATION, TOO_BIG_SEQUENCE +from .utils import iana_name, is_multi_byte_encoding, unicode_range + + +class CharsetMatch: + def __init__( + self, + payload: bytes, + guessed_encoding: str, + mean_mess_ratio: float, + has_sig_or_bom: bool, + languages: CoherenceMatches, + decoded_payload: str | None = None, + preemptive_declaration: str | None = None, + ): + self._payload: bytes = payload + + self._encoding: str = guessed_encoding + self._mean_mess_ratio: float = mean_mess_ratio + self._languages: CoherenceMatches = languages + self._has_sig_or_bom: bool = has_sig_or_bom + self._unicode_ranges: list[str] | None = None + + self._leaves: list[CharsetMatch] = [] + self._mean_coherence_ratio: float = 0.0 + + self._output_payload: bytes | None = None + self._output_encoding: str | None = None + + self._string: str | None = decoded_payload + + self._preemptive_declaration: str | None = preemptive_declaration + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CharsetMatch): + if isinstance(other, str): + return iana_name(other) == self.encoding + return False + return self.encoding == other.encoding and self.fingerprint == other.fingerprint + + def __lt__(self, other: object) -> bool: + """ + Implemented to make sorted available upon CharsetMatches items. + """ + if not isinstance(other, CharsetMatch): + raise ValueError + + chaos_difference: float = abs(self.chaos - other.chaos) + coherence_difference: float = abs(self.coherence - other.coherence) + + # Below 1% difference --> Use Coherence + if chaos_difference < 0.01 and coherence_difference > 0.02: + return self.coherence > other.coherence + elif chaos_difference < 0.01 and coherence_difference <= 0.02: + # When having a difficult decision, use the result that decoded as many multi-byte as possible. + # preserve RAM usage! + if len(self._payload) >= TOO_BIG_SEQUENCE: + return self.chaos < other.chaos + return self.multi_byte_usage > other.multi_byte_usage + + return self.chaos < other.chaos + + @property + def multi_byte_usage(self) -> float: + return 1.0 - (len(str(self)) / len(self.raw)) + + def __str__(self) -> str: + # Lazy Str Loading + if self._string is None: + self._string = str(self._payload, self._encoding, "strict") + return self._string + + def __repr__(self) -> str: + return f"" + + def add_submatch(self, other: CharsetMatch) -> None: + if not isinstance(other, CharsetMatch) or other == self: + raise ValueError( + "Unable to add instance <{}> as a submatch of a CharsetMatch".format( + other.__class__ + ) + ) + + other._string = None # Unload RAM usage; dirty trick. + self._leaves.append(other) + + @property + def encoding(self) -> str: + return self._encoding + + @property + def encoding_aliases(self) -> list[str]: + """ + Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855. + """ + also_known_as: list[str] = [] + for u, p in aliases.items(): + if self.encoding == u: + also_known_as.append(p) + elif self.encoding == p: + also_known_as.append(u) + return also_known_as + + @property + def bom(self) -> bool: + return self._has_sig_or_bom + + @property + def byte_order_mark(self) -> bool: + return self._has_sig_or_bom + + @property + def languages(self) -> list[str]: + """ + Return the complete list of possible languages found in decoded sequence. + Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. + """ + return [e[0] for e in self._languages] + + @property + def language(self) -> str: + """ + Most probable language found in decoded sequence. If none were detected or inferred, the property will return + "Unknown". + """ + if not self._languages: + # Trying to infer the language based on the given encoding + # Its either English or we should not pronounce ourselves in certain cases. + if "ascii" in self.could_be_from_charset: + return "English" + + # doing it there to avoid circular import + from charset_normalizer.cd import encoding_languages, mb_encoding_languages + + languages = ( + mb_encoding_languages(self.encoding) + if is_multi_byte_encoding(self.encoding) + else encoding_languages(self.encoding) + ) + + if len(languages) == 0 or "Latin Based" in languages: + return "Unknown" + + return languages[0] + + return self._languages[0][0] + + @property + def chaos(self) -> float: + return self._mean_mess_ratio + + @property + def coherence(self) -> float: + if not self._languages: + return 0.0 + return self._languages[0][1] + + @property + def percent_chaos(self) -> float: + return round(self.chaos * 100, ndigits=3) + + @property + def percent_coherence(self) -> float: + return round(self.coherence * 100, ndigits=3) + + @property + def raw(self) -> bytes: + """ + Original untouched bytes. + """ + return self._payload + + @property + def submatch(self) -> list[CharsetMatch]: + return self._leaves + + @property + def has_submatch(self) -> bool: + return len(self._leaves) > 0 + + @property + def alphabets(self) -> list[str]: + if self._unicode_ranges is not None: + return self._unicode_ranges + # list detected ranges + detected_ranges: list[str | None] = [unicode_range(char) for char in str(self)] + # filter and sort + self._unicode_ranges = sorted(list({r for r in detected_ranges if r})) + return self._unicode_ranges + + @property + def could_be_from_charset(self) -> list[str]: + """ + The complete list of encoding that output the exact SAME str result and therefore could be the originating + encoding. + This list does include the encoding available in property 'encoding'. + """ + return [self._encoding] + [m.encoding for m in self._leaves] + + def output(self, encoding: str = "utf_8") -> bytes: + """ + Method to get re-encoded bytes payload using given target encoding. Default to UTF-8. + Any errors will be simply ignored by the encoder NOT replaced. + """ + if self._output_encoding is None or self._output_encoding != encoding: + self._output_encoding = encoding + decoded_string = str(self) + if ( + self._preemptive_declaration is not None + and self._preemptive_declaration.lower() + not in ["utf-8", "utf8", "utf_8"] + ): + patched_header = sub( + RE_POSSIBLE_ENCODING_INDICATION, + lambda m: m.string[m.span()[0] : m.span()[1]].replace( + m.groups()[0], + iana_name(self._output_encoding).replace("_", "-"), # type: ignore[arg-type] + ), + decoded_string[:8192], + count=1, + ) + + decoded_string = patched_header + decoded_string[8192:] + + self._output_payload = decoded_string.encode(encoding, "replace") + + return self._output_payload # type: ignore + + @property + def fingerprint(self) -> str: + """ + Retrieve the unique SHA256 computed using the transformed (re-encoded) payload. Not the original one. + """ + return sha256(self.output()).hexdigest() + + +class CharsetMatches: + """ + Container with every CharsetMatch items ordered by default from most probable to the less one. + Act like a list(iterable) but does not implements all related methods. + """ + + def __init__(self, results: list[CharsetMatch] | None = None): + self._results: list[CharsetMatch] = sorted(results) if results else [] + + def __iter__(self) -> Iterator[CharsetMatch]: + yield from self._results + + def __getitem__(self, item: int | str) -> CharsetMatch: + """ + Retrieve a single item either by its position or encoding name (alias may be used here). + Raise KeyError upon invalid index or encoding not present in results. + """ + if isinstance(item, int): + return self._results[item] + if isinstance(item, str): + item = iana_name(item, False) + for result in self._results: + if item in result.could_be_from_charset: + return result + raise KeyError + + def __len__(self) -> int: + return len(self._results) + + def __bool__(self) -> bool: + return len(self._results) > 0 + + def append(self, item: CharsetMatch) -> None: + """ + Insert a single match. Will be inserted accordingly to preserve sort. + Can be inserted as a submatch. + """ + if not isinstance(item, CharsetMatch): + raise ValueError( + "Cannot append instance '{}' to CharsetMatches".format( + str(item.__class__) + ) + ) + # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage) + if len(item.raw) < TOO_BIG_SEQUENCE: + for match in self._results: + if match.fingerprint == item.fingerprint and match.chaos == item.chaos: + match.add_submatch(item) + return + self._results.append(item) + self._results = sorted(self._results) + + def best(self) -> CharsetMatch | None: + """ + Simply return the first match. Strict equivalent to matches[0]. + """ + if not self._results: + return None + return self._results[0] + + def first(self) -> CharsetMatch | None: + """ + Redundant method, call the method best(). Kept for BC reasons. + """ + return self.best() + + +CoherenceMatch = Tuple[str, float] +CoherenceMatches = List[CoherenceMatch] + + +class CliDetectionResult: + def __init__( + self, + path: str, + encoding: str | None, + encoding_aliases: list[str], + alternative_encodings: list[str], + language: str, + alphabets: list[str], + has_sig_or_bom: bool, + chaos: float, + coherence: float, + unicode_path: str | None, + is_preferred: bool, + ): + self.path: str = path + self.unicode_path: str | None = unicode_path + self.encoding: str | None = encoding + self.encoding_aliases: list[str] = encoding_aliases + self.alternative_encodings: list[str] = alternative_encodings + self.language: str = language + self.alphabets: list[str] = alphabets + self.has_sig_or_bom: bool = has_sig_or_bom + self.chaos: float = chaos + self.coherence: float = coherence + self.is_preferred: bool = is_preferred + + @property + def __dict__(self) -> dict[str, Any]: # type: ignore + return { + "path": self.path, + "encoding": self.encoding, + "encoding_aliases": self.encoding_aliases, + "alternative_encodings": self.alternative_encodings, + "language": self.language, + "alphabets": self.alphabets, + "has_sig_or_bom": self.has_sig_or_bom, + "chaos": self.chaos, + "coherence": self.coherence, + "unicode_path": self.unicode_path, + "is_preferred": self.is_preferred, + } + + def to_json(self) -> str: + return dumps(self.__dict__, ensure_ascii=True, indent=4) diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/py.typed b/miniconda3/lib/python3.13/site-packages/charset_normalizer/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf0384ccf94216f79881674f54182a93e17def0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/utils.py @@ -0,0 +1,414 @@ +from __future__ import annotations + +import importlib +import logging +import unicodedata +from codecs import IncrementalDecoder +from encodings.aliases import aliases +from functools import lru_cache +from re import findall +from typing import Generator + +from _multibytecodec import ( # type: ignore[import-not-found,import] + MultibyteIncrementalDecoder, +) + +from .constant import ( + ENCODING_MARKS, + IANA_SUPPORTED_SIMILAR, + RE_POSSIBLE_ENCODING_INDICATION, + UNICODE_RANGES_COMBINED, + UNICODE_SECONDARY_RANGE_KEYWORD, + UTF8_MAXIMAL_ALLOCATION, + COMMON_CJK_CHARACTERS, +) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_accentuated(character: str) -> bool: + try: + description: str = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + return ( + "WITH GRAVE" in description + or "WITH ACUTE" in description + or "WITH CEDILLA" in description + or "WITH DIAERESIS" in description + or "WITH CIRCUMFLEX" in description + or "WITH TILDE" in description + or "WITH MACRON" in description + or "WITH RING ABOVE" in description + ) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def remove_accent(character: str) -> str: + decomposed: str = unicodedata.decomposition(character) + if not decomposed: + return character + + codes: list[str] = decomposed.split(" ") + + return chr(int(codes[0], 16)) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def unicode_range(character: str) -> str | None: + """ + Retrieve the Unicode range official name from a single character. + """ + character_ord: int = ord(character) + + for range_name, ord_range in UNICODE_RANGES_COMBINED.items(): + if character_ord in ord_range: + return range_name + + return None + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_latin(character: str) -> bool: + try: + description: str = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + return "LATIN" in description + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_punctuation(character: str) -> bool: + character_category: str = unicodedata.category(character) + + if "P" in character_category: + return True + + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Punctuation" in character_range + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_symbol(character: str) -> bool: + character_category: str = unicodedata.category(character) + + if "S" in character_category or "N" in character_category: + return True + + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Forms" in character_range and character_category != "Lo" + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_emoticon(character: str) -> bool: + character_range: str | None = unicode_range(character) + + if character_range is None: + return False + + return "Emoticons" in character_range or "Pictographs" in character_range + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_separator(character: str) -> bool: + if character.isspace() or character in {"|", "+", "<", ">"}: + return True + + character_category: str = unicodedata.category(character) + + return "Z" in character_category or character_category in {"Po", "Pd", "Pc"} + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_case_variable(character: str) -> bool: + return character.islower() != character.isupper() + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_cjk(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "CJK" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_hiragana(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "HIRAGANA" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_katakana(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "KATAKANA" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_hangul(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "HANGUL" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_thai(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "THAI" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_arabic(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "ARABIC" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_arabic_isolated_form(character: str) -> bool: + try: + character_name = unicodedata.name(character) + except ValueError: # Defensive: unicode database outdated? + return False + + return "ARABIC" in character_name and "ISOLATED FORM" in character_name + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_cjk_uncommon(character: str) -> bool: + return character not in COMMON_CJK_CHARACTERS + + +@lru_cache(maxsize=len(UNICODE_RANGES_COMBINED)) +def is_unicode_range_secondary(range_name: str) -> bool: + return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD) + + +@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) +def is_unprintable(character: str) -> bool: + return ( + character.isspace() is False # includes \n \t \r \v + and character.isprintable() is False + and character != "\x1a" # Why? Its the ASCII substitute character. + and character != "\ufeff" # bug discovered in Python, + # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space. + ) + + +def any_specified_encoding(sequence: bytes, search_zone: int = 8192) -> str | None: + """ + Extract using ASCII-only decoder any specified encoding in the first n-bytes. + """ + if not isinstance(sequence, bytes): + raise TypeError + + seq_len: int = len(sequence) + + results: list[str] = findall( + RE_POSSIBLE_ENCODING_INDICATION, + sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"), + ) + + if len(results) == 0: + return None + + for specified_encoding in results: + specified_encoding = specified_encoding.lower().replace("-", "_") + + encoding_alias: str + encoding_iana: str + + for encoding_alias, encoding_iana in aliases.items(): + if encoding_alias == specified_encoding: + return encoding_iana + if encoding_iana == specified_encoding: + return encoding_iana + + return None + + +@lru_cache(maxsize=128) +def is_multi_byte_encoding(name: str) -> bool: + """ + Verify is a specific encoding is a multi byte one based on it IANA name + """ + return name in { + "utf_8", + "utf_8_sig", + "utf_16", + "utf_16_be", + "utf_16_le", + "utf_32", + "utf_32_le", + "utf_32_be", + "utf_7", + } or issubclass( + importlib.import_module(f"encodings.{name}").IncrementalDecoder, + MultibyteIncrementalDecoder, + ) + + +def identify_sig_or_bom(sequence: bytes) -> tuple[str | None, bytes]: + """ + Identify and extract SIG/BOM in given sequence. + """ + + for iana_encoding in ENCODING_MARKS: + marks: bytes | list[bytes] = ENCODING_MARKS[iana_encoding] + + if isinstance(marks, bytes): + marks = [marks] + + for mark in marks: + if sequence.startswith(mark): + return iana_encoding, mark + + return None, b"" + + +def should_strip_sig_or_bom(iana_encoding: str) -> bool: + return iana_encoding not in {"utf_16", "utf_32"} + + +def iana_name(cp_name: str, strict: bool = True) -> str: + """Returns the Python normalized encoding name (Not the IANA official name).""" + cp_name = cp_name.lower().replace("-", "_") + + encoding_alias: str + encoding_iana: str + + for encoding_alias, encoding_iana in aliases.items(): + if cp_name in [encoding_alias, encoding_iana]: + return encoding_iana + + if strict: + raise ValueError(f"Unable to retrieve IANA for '{cp_name}'") + + return cp_name + + +def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: + if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): + return 0.0 + + decoder_a = importlib.import_module(f"encodings.{iana_name_a}").IncrementalDecoder + decoder_b = importlib.import_module(f"encodings.{iana_name_b}").IncrementalDecoder + + id_a: IncrementalDecoder = decoder_a(errors="ignore") + id_b: IncrementalDecoder = decoder_b(errors="ignore") + + character_match_count: int = 0 + + for i in range(255): + to_be_decoded: bytes = bytes([i]) + if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): + character_match_count += 1 + + return character_match_count / 254 + + +def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: + """ + Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using + the function cp_similarity. + """ + return ( + iana_name_a in IANA_SUPPORTED_SIMILAR + and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] + ) + + +def set_logging_handler( + name: str = "charset_normalizer", + level: int = logging.INFO, + format_string: str = "%(asctime)s | %(levelname)s | %(message)s", +) -> None: + logger = logging.getLogger(name) + logger.setLevel(level) + + handler = logging.StreamHandler() + handler.setFormatter(logging.Formatter(format_string)) + logger.addHandler(handler) + + +def cut_sequence_chunks( + sequences: bytes, + encoding_iana: str, + offsets: range, + chunk_size: int, + bom_or_sig_available: bool, + strip_sig_or_bom: bool, + sig_payload: bytes, + is_multi_byte_decoder: bool, + decoded_payload: str | None = None, +) -> Generator[str, None, None]: + if decoded_payload and is_multi_byte_decoder is False: + for i in offsets: + chunk = decoded_payload[i : i + chunk_size] + if not chunk: + break + yield chunk + else: + for i in offsets: + chunk_end = i + chunk_size + if chunk_end > len(sequences) + 8: + continue + + cut_sequence = sequences[i : i + chunk_size] + + if bom_or_sig_available and strip_sig_or_bom is False: + cut_sequence = sig_payload + cut_sequence + + chunk = cut_sequence.decode( + encoding_iana, + errors="ignore" if is_multi_byte_decoder else "strict", + ) + + # multi-byte bad cutting detector and adjustment + # not the cleanest way to perform that fix but clever enough for now. + if is_multi_byte_decoder and i > 0: + chunk_partial_size_chk: int = min(chunk_size, 16) + + if ( + decoded_payload + and chunk[:chunk_partial_size_chk] not in decoded_payload + ): + for j in range(i, i - 4, -1): + cut_sequence = sequences[j:chunk_end] + + if bom_or_sig_available and strip_sig_or_bom is False: + cut_sequence = sig_payload + cut_sequence + + chunk = cut_sequence.decode(encoding_iana, errors="ignore") + + if chunk[:chunk_partial_size_chk] in decoded_payload: + break + + yield chunk diff --git a/miniconda3/lib/python3.13/site-packages/charset_normalizer/version.py b/miniconda3/lib/python3.13/site-packages/charset_normalizer/version.py new file mode 100644 index 0000000000000000000000000000000000000000..c843e5331131fe69b5bba96d3f0c1160dcaa943b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/charset_normalizer/version.py @@ -0,0 +1,8 @@ +""" +Expose version +""" + +from __future__ import annotations + +__version__ = "3.4.4" +VERSION = __version__.split(".") diff --git a/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..e6c05af4a78cabdf5689f3f6f7fd57304d8a0eb1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/METADATA @@ -0,0 +1,82 @@ +Metadata-Version: 2.4 +Name: click +Version: 8.2.1 +Summary: Composable command line interface toolkit +Maintainer-email: Pallets +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: colorama; platform_system == 'Windows' +Project-URL: Changes, https://click.palletsprojects.com/page/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://click.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/click/ + +# $ click_ + +Click is a Python package for creating beautiful command line interfaces +in a composable way with as little code as necessary. It's the "Command +Line Interface Creation Kit". It's highly configurable but comes with +sensible defaults out of the box. + +It aims to make the process of writing command line tools quick and fun +while also preventing any frustration caused by the inability to +implement an intended CLI API. + +Click in three points: + +- Arbitrary nesting of commands +- Automatic help page generation +- Supports lazy loading of subcommands at runtime + + +## A Simple Example + +```python +import click + +@click.command() +@click.option("--count", default=1, help="Number of greetings.") +@click.option("--name", prompt="Your name", help="The person to greet.") +def hello(count, name): + """Simple program that greets NAME for a total of COUNT times.""" + for _ in range(count): + click.echo(f"Hello, {name}!") + +if __name__ == '__main__': + hello() +``` + +``` +$ python hello.py --count=3 +Your name: Click +Hello, Click! +Hello, Click! +Hello, Click! +``` + + +## Donate + +The Pallets organization develops and supports Click and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..aa1899264e21c21eddb04967ef249c4b41a48f95 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/RECORD @@ -0,0 +1,40 @@ +click-8.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +click-8.2.1.dist-info/METADATA,sha256=dI1MbhHTLoKD2tNCCGnx9rK2gok23HDNylFeLKdLSik,2471 +click-8.2.1.dist-info/RECORD,, +click-8.2.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click-8.2.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +click-8.2.1.dist-info/direct_url.json,sha256=H8jZyz21jDDoaYECf18QQi8UqnE6A1SJVtMbWCMrPfo,95 +click-8.2.1.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475 +click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473 +click/__pycache__/__init__.cpython-313.pyc,, +click/__pycache__/_compat.cpython-313.pyc,, +click/__pycache__/_termui_impl.cpython-313.pyc,, +click/__pycache__/_textwrap.cpython-313.pyc,, +click/__pycache__/_winconsole.cpython-313.pyc,, +click/__pycache__/core.cpython-313.pyc,, +click/__pycache__/decorators.cpython-313.pyc,, +click/__pycache__/exceptions.cpython-313.pyc,, +click/__pycache__/formatting.cpython-313.pyc,, +click/__pycache__/globals.cpython-313.pyc,, +click/__pycache__/parser.cpython-313.pyc,, +click/__pycache__/shell_completion.cpython-313.pyc,, +click/__pycache__/termui.cpython-313.pyc,, +click/__pycache__/testing.cpython-313.pyc,, +click/__pycache__/types.cpython-313.pyc,, +click/__pycache__/utils.cpython-313.pyc,, +click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693 +click/_termui_impl.py,sha256=ASXhLi9IQIc0Js9KQSS-3-SLZcPet3VqysBf9WgbbpI,26712 +click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400 +click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465 +click/core.py,sha256=gUhpNS9cFBGdEXXdisGVG-eRvGf49RTyFagxulqwdFw,117343 +click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461 +click/exceptions.py,sha256=1rdtXgHJ1b3OjGkN-UpXB9t_HCBihJvh_DtpmLmwn9s,9891 +click/formatting.py,sha256=Bhqx4QXdKQ9W4WKknIwj5KPKFmtduGOuGq1yw_THLZ8,9726 +click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923 +click/parser.py,sha256=nU1Ah2p11q29ul1vNdU9swPo_PUuKrxU6YXToi71q1c,18979 +click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +click/shell_completion.py,sha256=CQSGdjgun4ORbOZrXP0CVhEtPx4knsufOkRsDiK64cM,19857 +click/termui.py,sha256=vAYrKC2a7f_NfEIhAThEVYfa__ib5XQbTSCGtJlABRA,30847 +click/testing.py,sha256=2eLdAaCJCGToP5Tw-XN8JjrDb3wbJIfARxg3d0crW5M,18702 +click/types.py,sha256=KBTRxN28cR1VZ5mb9iJX98MQSw_p9SGzljqfEI8z5Tw,38389 +click/utils.py,sha256=b1Mm-usEDBHtEwcPltPIn3zSK4nw2KTp5GC7_oSTlLo,20245 diff --git a/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..bf3ebd0f8b03d230643ea84462c831c7c72cd3ec --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176433224228540/conda-bld/click_1764332256338/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click-8.2.1.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +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 NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/lib/python3.13/site-packages/click/__init__.py b/miniconda3/lib/python3.13/site-packages/click/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa547c57af68954b3bcd6012873881030e53d91 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/__init__.py @@ -0,0 +1,123 @@ +""" +Click is a simple Python module inspired by the stdlib optparse to make +writing command line scripts fun. Unlike other modules, it's based +around a simple API that does not come with too much magic and is +composable. +""" + +from __future__ import annotations + +from .core import Argument as Argument +from .core import Command as Command +from .core import CommandCollection as CommandCollection +from .core import Context as Context +from .core import Group as Group +from .core import Option as Option +from .core import Parameter as Parameter +from .decorators import argument as argument +from .decorators import command as command +from .decorators import confirmation_option as confirmation_option +from .decorators import group as group +from .decorators import help_option as help_option +from .decorators import make_pass_decorator as make_pass_decorator +from .decorators import option as option +from .decorators import pass_context as pass_context +from .decorators import pass_obj as pass_obj +from .decorators import password_option as password_option +from .decorators import version_option as version_option +from .exceptions import Abort as Abort +from .exceptions import BadArgumentUsage as BadArgumentUsage +from .exceptions import BadOptionUsage as BadOptionUsage +from .exceptions import BadParameter as BadParameter +from .exceptions import ClickException as ClickException +from .exceptions import FileError as FileError +from .exceptions import MissingParameter as MissingParameter +from .exceptions import NoSuchOption as NoSuchOption +from .exceptions import UsageError as UsageError +from .formatting import HelpFormatter as HelpFormatter +from .formatting import wrap_text as wrap_text +from .globals import get_current_context as get_current_context +from .termui import clear as clear +from .termui import confirm as confirm +from .termui import echo_via_pager as echo_via_pager +from .termui import edit as edit +from .termui import getchar as getchar +from .termui import launch as launch +from .termui import pause as pause +from .termui import progressbar as progressbar +from .termui import prompt as prompt +from .termui import secho as secho +from .termui import style as style +from .termui import unstyle as unstyle +from .types import BOOL as BOOL +from .types import Choice as Choice +from .types import DateTime as DateTime +from .types import File as File +from .types import FLOAT as FLOAT +from .types import FloatRange as FloatRange +from .types import INT as INT +from .types import IntRange as IntRange +from .types import ParamType as ParamType +from .types import Path as Path +from .types import STRING as STRING +from .types import Tuple as Tuple +from .types import UNPROCESSED as UNPROCESSED +from .types import UUID as UUID +from .utils import echo as echo +from .utils import format_filename as format_filename +from .utils import get_app_dir as get_app_dir +from .utils import get_binary_stream as get_binary_stream +from .utils import get_text_stream as get_text_stream +from .utils import open_file as open_file + + +def __getattr__(name: str) -> object: + import warnings + + if name == "BaseCommand": + from .core import _BaseCommand + + warnings.warn( + "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Command' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _BaseCommand + + if name == "MultiCommand": + from .core import _MultiCommand + + warnings.warn( + "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Group' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _MultiCommand + + if name == "OptionParser": + from .parser import _OptionParser + + warnings.warn( + "'OptionParser' is deprecated and will be removed in Click 9.0. The" + " old parser is available in 'optparse'.", + DeprecationWarning, + stacklevel=2, + ) + return _OptionParser + + if name == "__version__": + import importlib.metadata + import warnings + + warnings.warn( + "The '__version__' attribute is deprecated and will be removed in" + " Click 9.1. Use feature detection or" + " 'importlib.metadata.version(\"click\")' instead.", + DeprecationWarning, + stacklevel=2, + ) + return importlib.metadata.version("click") + + raise AttributeError(name) diff --git a/miniconda3/lib/python3.13/site-packages/click/_compat.py b/miniconda3/lib/python3.13/site-packages/click/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..f2726b93afe2ed69ba20d8e709c9cbd22b9d2339 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/_compat.py @@ -0,0 +1,622 @@ +from __future__ import annotations + +import codecs +import collections.abc as cabc +import io +import os +import re +import sys +import typing as t +from types import TracebackType +from weakref import WeakKeyDictionary + +CYGWIN = sys.platform.startswith("cygwin") +WIN = sys.platform.startswith("win") +auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None +_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]") + + +def _make_text_stream( + stream: t.BinaryIO, + encoding: str | None, + errors: str | None, + force_readable: bool = False, + force_writable: bool = False, +) -> t.TextIO: + if encoding is None: + encoding = get_best_encoding(stream) + if errors is None: + errors = "replace" + return _NonClosingTextIOWrapper( + stream, + encoding, + errors, + line_buffering=True, + force_readable=force_readable, + force_writable=force_writable, + ) + + +def is_ascii_encoding(encoding: str) -> bool: + """Checks if a given encoding is ascii.""" + try: + return codecs.lookup(encoding).name == "ascii" + except LookupError: + return False + + +def get_best_encoding(stream: t.IO[t.Any]) -> str: + """Returns the default stream encoding if not found.""" + rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() + if is_ascii_encoding(rv): + return "utf-8" + return rv + + +class _NonClosingTextIOWrapper(io.TextIOWrapper): + def __init__( + self, + stream: t.BinaryIO, + encoding: str | None, + errors: str | None, + force_readable: bool = False, + force_writable: bool = False, + **extra: t.Any, + ) -> None: + self._stream = stream = t.cast( + t.BinaryIO, _FixupStream(stream, force_readable, force_writable) + ) + super().__init__(stream, encoding, errors, **extra) + + def __del__(self) -> None: + try: + self.detach() + except Exception: + pass + + def isatty(self) -> bool: + # https://bitbucket.org/pypy/pypy/issue/1803 + return self._stream.isatty() + + +class _FixupStream: + """The new io interface needs more from streams than streams + traditionally implement. As such, this fix-up code is necessary in + some circumstances. + + The forcing of readable and writable flags are there because some tools + put badly patched objects on sys (one such offender are certain version + of jupyter notebook). + """ + + def __init__( + self, + stream: t.BinaryIO, + force_readable: bool = False, + force_writable: bool = False, + ): + self._stream = stream + self._force_readable = force_readable + self._force_writable = force_writable + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._stream, name) + + def read1(self, size: int) -> bytes: + f = getattr(self._stream, "read1", None) + + if f is not None: + return t.cast(bytes, f(size)) + + return self._stream.read(size) + + def readable(self) -> bool: + if self._force_readable: + return True + x = getattr(self._stream, "readable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.read(0) + except Exception: + return False + return True + + def writable(self) -> bool: + if self._force_writable: + return True + x = getattr(self._stream, "writable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.write(b"") + except Exception: + try: + self._stream.write(b"") + except Exception: + return False + return True + + def seekable(self) -> bool: + x = getattr(self._stream, "seekable", None) + if x is not None: + return t.cast(bool, x()) + try: + self._stream.seek(self._stream.tell()) + except Exception: + return False + return True + + +def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool: + try: + return isinstance(stream.read(0), bytes) + except Exception: + return default + # This happens in some cases where the stream was already + # closed. In this case, we assume the default. + + +def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool: + try: + stream.write(b"") + except Exception: + try: + stream.write("") + return False + except Exception: + pass + return default + return True + + +def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None: + # We need to figure out if the given stream is already binary. + # This can happen because the official docs recommend detaching + # the streams to get binary streams. Some code might do this, so + # we need to deal with this case explicitly. + if _is_binary_reader(stream, False): + return t.cast(t.BinaryIO, stream) + + buf = getattr(stream, "buffer", None) + + # Same situation here; this time we assume that the buffer is + # actually binary in case it's closed. + if buf is not None and _is_binary_reader(buf, True): + return t.cast(t.BinaryIO, buf) + + return None + + +def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None: + # We need to figure out if the given stream is already binary. + # This can happen because the official docs recommend detaching + # the streams to get binary streams. Some code might do this, so + # we need to deal with this case explicitly. + if _is_binary_writer(stream, False): + return t.cast(t.BinaryIO, stream) + + buf = getattr(stream, "buffer", None) + + # Same situation here; this time we assume that the buffer is + # actually binary in case it's closed. + if buf is not None and _is_binary_writer(buf, True): + return t.cast(t.BinaryIO, buf) + + return None + + +def _stream_is_misconfigured(stream: t.TextIO) -> bool: + """A stream is misconfigured if its encoding is ASCII.""" + # If the stream does not have an encoding set, we assume it's set + # to ASCII. This appears to happen in certain unittest + # environments. It's not quite clear what the correct behavior is + # but this at least will force Click to recover somehow. + return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii") + + +def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool: + """A stream attribute is compatible if it is equal to the + desired value or the desired value is unset and the attribute + has a value. + """ + stream_value = getattr(stream, attr, None) + return stream_value == value or (value is None and stream_value is not None) + + +def _is_compatible_text_stream( + stream: t.TextIO, encoding: str | None, errors: str | None +) -> bool: + """Check if a stream's encoding and errors attributes are + compatible with the desired values. + """ + return _is_compat_stream_attr( + stream, "encoding", encoding + ) and _is_compat_stream_attr(stream, "errors", errors) + + +def _force_correct_text_stream( + text_stream: t.IO[t.Any], + encoding: str | None, + errors: str | None, + is_binary: t.Callable[[t.IO[t.Any], bool], bool], + find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None], + force_readable: bool = False, + force_writable: bool = False, +) -> t.TextIO: + if is_binary(text_stream, False): + binary_reader = t.cast(t.BinaryIO, text_stream) + else: + text_stream = t.cast(t.TextIO, text_stream) + # If the stream looks compatible, and won't default to a + # misconfigured ascii encoding, return it as-is. + if _is_compatible_text_stream(text_stream, encoding, errors) and not ( + encoding is None and _stream_is_misconfigured(text_stream) + ): + return text_stream + + # Otherwise, get the underlying binary reader. + possible_binary_reader = find_binary(text_stream) + + # If that's not possible, silently use the original reader + # and get mojibake instead of exceptions. + if possible_binary_reader is None: + return text_stream + + binary_reader = possible_binary_reader + + # Default errors to replace instead of strict in order to get + # something that works. + if errors is None: + errors = "replace" + + # Wrap the binary stream in a text stream with the correct + # encoding parameters. + return _make_text_stream( + binary_reader, + encoding, + errors, + force_readable=force_readable, + force_writable=force_writable, + ) + + +def _force_correct_text_reader( + text_reader: t.IO[t.Any], + encoding: str | None, + errors: str | None, + force_readable: bool = False, +) -> t.TextIO: + return _force_correct_text_stream( + text_reader, + encoding, + errors, + _is_binary_reader, + _find_binary_reader, + force_readable=force_readable, + ) + + +def _force_correct_text_writer( + text_writer: t.IO[t.Any], + encoding: str | None, + errors: str | None, + force_writable: bool = False, +) -> t.TextIO: + return _force_correct_text_stream( + text_writer, + encoding, + errors, + _is_binary_writer, + _find_binary_writer, + force_writable=force_writable, + ) + + +def get_binary_stdin() -> t.BinaryIO: + reader = _find_binary_reader(sys.stdin) + if reader is None: + raise RuntimeError("Was not able to determine binary stream for sys.stdin.") + return reader + + +def get_binary_stdout() -> t.BinaryIO: + writer = _find_binary_writer(sys.stdout) + if writer is None: + raise RuntimeError("Was not able to determine binary stream for sys.stdout.") + return writer + + +def get_binary_stderr() -> t.BinaryIO: + writer = _find_binary_writer(sys.stderr) + if writer is None: + raise RuntimeError("Was not able to determine binary stream for sys.stderr.") + return writer + + +def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stdin, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True) + + +def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stdout, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True) + + +def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO: + rv = _get_windows_console_stream(sys.stderr, encoding, errors) + if rv is not None: + return rv + return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True) + + +def _wrap_io_open( + file: str | os.PathLike[str] | int, + mode: str, + encoding: str | None, + errors: str | None, +) -> t.IO[t.Any]: + """Handles not passing ``encoding`` and ``errors`` in binary mode.""" + if "b" in mode: + return open(file, mode) + + return open(file, mode, encoding=encoding, errors=errors) + + +def open_stream( + filename: str | os.PathLike[str], + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + atomic: bool = False, +) -> tuple[t.IO[t.Any], bool]: + binary = "b" in mode + filename = os.fspath(filename) + + # Standard streams first. These are simple because they ignore the + # atomic flag. Use fsdecode to handle Path("-"). + if os.fsdecode(filename) == "-": + if any(m in mode for m in ["w", "a", "x"]): + if binary: + return get_binary_stdout(), False + return get_text_stdout(encoding=encoding, errors=errors), False + if binary: + return get_binary_stdin(), False + return get_text_stdin(encoding=encoding, errors=errors), False + + # Non-atomic writes directly go out through the regular open functions. + if not atomic: + return _wrap_io_open(filename, mode, encoding, errors), True + + # Some usability stuff for atomic writes + if "a" in mode: + raise ValueError( + "Appending to an existing file is not supported, because that" + " would involve an expensive `copy`-operation to a temporary" + " file. Open the file in normal `w`-mode and copy explicitly" + " if that's what you're after." + ) + if "x" in mode: + raise ValueError("Use the `overwrite`-parameter instead.") + if "w" not in mode: + raise ValueError("Atomic writes only make sense with `w`-mode.") + + # Atomic writes are more complicated. They work by opening a file + # as a proxy in the same folder and then using the fdopen + # functionality to wrap it in a Python file. Then we wrap it in an + # atomic file that moves the file over on close. + import errno + import random + + try: + perm: int | None = os.stat(filename).st_mode + except OSError: + perm = None + + flags = os.O_RDWR | os.O_CREAT | os.O_EXCL + + if binary: + flags |= getattr(os, "O_BINARY", 0) + + while True: + tmp_filename = os.path.join( + os.path.dirname(filename), + f".__atomic-write{random.randrange(1 << 32):08x}", + ) + try: + fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) + break + except OSError as e: + if e.errno == errno.EEXIST or ( + os.name == "nt" + and e.errno == errno.EACCES + and os.path.isdir(e.filename) + and os.access(e.filename, os.W_OK) + ): + continue + raise + + if perm is not None: + os.chmod(tmp_filename, perm) # in case perm includes bits in umask + + f = _wrap_io_open(fd, mode, encoding, errors) + af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) + return t.cast(t.IO[t.Any], af), True + + +class _AtomicFile: + def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: + self._f = f + self._tmp_filename = tmp_filename + self._real_filename = real_filename + self.closed = False + + @property + def name(self) -> str: + return self._real_filename + + def close(self, delete: bool = False) -> None: + if self.closed: + return + self._f.close() + os.replace(self._tmp_filename, self._real_filename) + self.closed = True + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._f, name) + + def __enter__(self) -> _AtomicFile: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close(delete=exc_type is not None) + + def __repr__(self) -> str: + return repr(self._f) + + +def strip_ansi(value: str) -> str: + return _ansi_re.sub("", value) + + +def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool: + while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): + stream = stream._stream + + return stream.__class__.__module__.startswith("ipykernel.") + + +def should_strip_ansi( + stream: t.IO[t.Any] | None = None, color: bool | None = None +) -> bool: + if color is None: + if stream is None: + stream = sys.stdin + return not isatty(stream) and not _is_jupyter_kernel_output(stream) + return not color + + +# On Windows, wrap the output streams with colorama to support ANSI +# color codes. +# NOTE: double check is needed so mypy does not analyze this on Linux +if sys.platform.startswith("win") and WIN: + from ._winconsole import _get_windows_console_stream + + def _get_argv_encoding() -> str: + import locale + + return locale.getpreferredencoding() + + _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() + + def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO: + """Support ANSI color and style codes on Windows by wrapping a + stream with colorama. + """ + try: + cached = _ansi_stream_wrappers.get(stream) + except Exception: + cached = None + + if cached is not None: + return cached + + import colorama + + strip = should_strip_ansi(stream, color) + ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) + rv = t.cast(t.TextIO, ansi_wrapper.stream) + _write = rv.write + + def _safe_write(s: str) -> int: + try: + return _write(s) + except BaseException: + ansi_wrapper.reset_all() + raise + + rv.write = _safe_write # type: ignore[method-assign] + + try: + _ansi_stream_wrappers[stream] = rv + except Exception: + pass + + return rv + +else: + + def _get_argv_encoding() -> str: + return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding() + + def _get_windows_console_stream( + f: t.TextIO, encoding: str | None, errors: str | None + ) -> t.TextIO | None: + return None + + +def term_len(x: str) -> int: + return len(strip_ansi(x)) + + +def isatty(stream: t.IO[t.Any]) -> bool: + try: + return stream.isatty() + except Exception: + return False + + +def _make_cached_stream_func( + src_func: t.Callable[[], t.TextIO | None], + wrapper_func: t.Callable[[], t.TextIO], +) -> t.Callable[[], t.TextIO | None]: + cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() + + def func() -> t.TextIO | None: + stream = src_func() + + if stream is None: + return None + + try: + rv = cache.get(stream) + except Exception: + rv = None + if rv is not None: + return rv + rv = wrapper_func() + try: + cache[stream] = rv + except Exception: + pass + return rv + + return func + + +_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin) +_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout) +_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr) + + +binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = { + "stdin": get_binary_stdin, + "stdout": get_binary_stdout, + "stderr": get_binary_stderr, +} + +text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = { + "stdin": get_text_stdin, + "stdout": get_text_stdout, + "stderr": get_text_stderr, +} diff --git a/miniconda3/lib/python3.13/site-packages/click/_termui_impl.py b/miniconda3/lib/python3.13/site-packages/click/_termui_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..51fd9bf358f0ee8dedceb88efa8c6a60dc40d4a8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/_termui_impl.py @@ -0,0 +1,839 @@ +""" +This module contains implementations for the termui module. To keep the +import time of Click down, some infrequently used functionality is +placed in this module and only imported as needed. +""" + +from __future__ import annotations + +import collections.abc as cabc +import contextlib +import math +import os +import shlex +import sys +import time +import typing as t +from gettext import gettext as _ +from io import StringIO +from pathlib import Path +from shutil import which +from types import TracebackType + +from ._compat import _default_text_stdout +from ._compat import CYGWIN +from ._compat import get_best_encoding +from ._compat import isatty +from ._compat import open_stream +from ._compat import strip_ansi +from ._compat import term_len +from ._compat import WIN +from .exceptions import ClickException +from .utils import echo + +V = t.TypeVar("V") + +if os.name == "nt": + BEFORE_BAR = "\r" + AFTER_BAR = "\n" +else: + BEFORE_BAR = "\r\033[?25l" + AFTER_BAR = "\033[?25h\n" + + +class ProgressBar(t.Generic[V]): + def __init__( + self, + iterable: cabc.Iterable[V] | None, + length: int | None = None, + fill_char: str = "#", + empty_char: str = " ", + bar_template: str = "%(bar)s", + info_sep: str = " ", + 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, + label: str | None = None, + file: t.TextIO | None = None, + color: bool | None = None, + update_min_steps: int = 1, + width: int = 30, + ) -> None: + self.fill_char = fill_char + self.empty_char = empty_char + self.bar_template = bar_template + self.info_sep = info_sep + self.hidden = hidden + self.show_eta = show_eta + self.show_percent = show_percent + self.show_pos = show_pos + self.item_show_func = item_show_func + self.label: str = label or "" + + if file is None: + file = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if file is None: + file = StringIO() + + self.file = file + self.color = color + self.update_min_steps = update_min_steps + self._completed_intervals = 0 + self.width: int = width + self.autowidth: bool = width == 0 + + if length is None: + from operator import length_hint + + length = length_hint(iterable, -1) + + if length == -1: + length = None + if iterable is None: + if length is None: + raise TypeError("iterable or length is required") + iterable = t.cast("cabc.Iterable[V]", range(length)) + self.iter: cabc.Iterable[V] = iter(iterable) + self.length = length + self.pos: int = 0 + self.avg: list[float] = [] + self.last_eta: float + self.start: float + self.start = self.last_eta = time.time() + self.eta_known: bool = False + self.finished: bool = False + self.max_width: int | None = None + self.entered: bool = False + self.current_item: V | None = None + self._is_atty = isatty(self.file) + self._last_line: str | None = None + + def __enter__(self) -> ProgressBar[V]: + self.entered = True + self.render_progress() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.render_finish() + + def __iter__(self) -> cabc.Iterator[V]: + if not self.entered: + raise RuntimeError("You need to use progress bars in a with block.") + self.render_progress() + return self.generator() + + def __next__(self) -> V: + # Iteration is defined in terms of a generator function, + # returned by iter(self); use that to define next(). This works + # because `self.iter` is an iterable consumed by that generator, + # so it is re-entry safe. Calling `next(self.generator())` + # twice works and does "what you want". + return next(iter(self)) + + def render_finish(self) -> None: + if self.hidden or not self._is_atty: + return + self.file.write(AFTER_BAR) + self.file.flush() + + @property + def pct(self) -> float: + if self.finished: + return 1.0 + return min(self.pos / (float(self.length or 1) or 1), 1.0) + + @property + def time_per_iteration(self) -> float: + if not self.avg: + return 0.0 + return sum(self.avg) / float(len(self.avg)) + + @property + def eta(self) -> float: + if self.length is not None and not self.finished: + return self.time_per_iteration * (self.length - self.pos) + return 0.0 + + def format_eta(self) -> str: + if self.eta_known: + t = int(self.eta) + seconds = t % 60 + t //= 60 + minutes = t % 60 + t //= 60 + hours = t % 24 + t //= 24 + if t > 0: + return f"{t}d {hours:02}:{minutes:02}:{seconds:02}" + else: + return f"{hours:02}:{minutes:02}:{seconds:02}" + return "" + + def format_pos(self) -> str: + pos = str(self.pos) + if self.length is not None: + pos += f"/{self.length}" + return pos + + def format_pct(self) -> str: + return f"{int(self.pct * 100): 4}%"[1:] + + def format_bar(self) -> str: + if self.length is not None: + bar_length = int(self.pct * self.width) + bar = self.fill_char * bar_length + bar += self.empty_char * (self.width - bar_length) + elif self.finished: + bar = self.fill_char * self.width + else: + chars = list(self.empty_char * (self.width or 1)) + if self.time_per_iteration != 0: + chars[ + int( + (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5) + * self.width + ) + ] = self.fill_char + bar = "".join(chars) + return bar + + def format_progress_line(self) -> str: + show_percent = self.show_percent + + info_bits = [] + if self.length is not None and show_percent is None: + show_percent = not self.show_pos + + if self.show_pos: + info_bits.append(self.format_pos()) + if show_percent: + info_bits.append(self.format_pct()) + if self.show_eta and self.eta_known and not self.finished: + info_bits.append(self.format_eta()) + if self.item_show_func is not None: + item_info = self.item_show_func(self.current_item) + if item_info is not None: + info_bits.append(item_info) + + return ( + self.bar_template + % { + "label": self.label, + "bar": self.format_bar(), + "info": self.info_sep.join(info_bits), + } + ).rstrip() + + def render_progress(self) -> None: + import shutil + + if self.hidden: + return + + if not self._is_atty: + # Only output the label once if the output is not a TTY. + if self._last_line != self.label: + self._last_line = self.label + echo(self.label, file=self.file, color=self.color) + return + + buf = [] + # Update width in case the terminal has been resized + if self.autowidth: + old_width = self.width + self.width = 0 + clutter_length = term_len(self.format_progress_line()) + new_width = max(0, shutil.get_terminal_size().columns - clutter_length) + if new_width < old_width and self.max_width is not None: + buf.append(BEFORE_BAR) + buf.append(" " * self.max_width) + self.max_width = new_width + self.width = new_width + + clear_width = self.width + if self.max_width is not None: + clear_width = self.max_width + + buf.append(BEFORE_BAR) + line = self.format_progress_line() + line_len = term_len(line) + if self.max_width is None or self.max_width < line_len: + self.max_width = line_len + + buf.append(line) + buf.append(" " * (clear_width - line_len)) + line = "".join(buf) + # Render the line only if it changed. + + if line != self._last_line: + self._last_line = line + echo(line, file=self.file, color=self.color, nl=False) + self.file.flush() + + def make_step(self, n_steps: int) -> None: + self.pos += n_steps + if self.length is not None and self.pos >= self.length: + self.finished = True + + if (time.time() - self.last_eta) < 1.0: + return + + self.last_eta = time.time() + + # self.avg is a rolling list of length <= 7 of steps where steps are + # defined as time elapsed divided by the total progress through + # self.length. + if self.pos: + step = (time.time() - self.start) / self.pos + else: + step = time.time() - self.start + + self.avg = self.avg[-6:] + [step] + + self.eta_known = self.length is not None + + def update(self, n_steps: int, current_item: V | None = None) -> None: + """Update the progress bar by advancing a specified number of + steps, and optionally set the ``current_item`` for this new + position. + + :param n_steps: Number of steps to advance. + :param current_item: Optional item to set as ``current_item`` + for the updated position. + + .. versionchanged:: 8.0 + Added the ``current_item`` optional parameter. + + .. versionchanged:: 8.0 + Only render when the number of steps meets the + ``update_min_steps`` threshold. + """ + if current_item is not None: + self.current_item = current_item + + self._completed_intervals += n_steps + + if self._completed_intervals >= self.update_min_steps: + self.make_step(self._completed_intervals) + self.render_progress() + self._completed_intervals = 0 + + def finish(self) -> None: + self.eta_known = False + self.current_item = None + self.finished = True + + def generator(self) -> cabc.Iterator[V]: + """Return a generator which yields the items added to the bar + during construction, and updates the progress bar *after* the + yielded block returns. + """ + # WARNING: the iterator interface for `ProgressBar` relies on + # this and only works because this is a simple generator which + # doesn't create or manage additional state. If this function + # changes, the impact should be evaluated both against + # `iter(bar)` and `next(bar)`. `next()` in particular may call + # `self.generator()` repeatedly, and this must remain safe in + # order for that interface to work. + if not self.entered: + raise RuntimeError("You need to use progress bars in a with block.") + + if not self._is_atty: + yield from self.iter + else: + for rv in self.iter: + self.current_item = rv + + # This allows show_item_func to be updated before the + # item is processed. Only trigger at the beginning of + # the update interval. + if self._completed_intervals == 0: + self.render_progress() + + yield rv + self.update(1) + + self.finish() + self.render_progress() + + +def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None: + """Decide what method to use for paging through text.""" + stdout = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if stdout is None: + stdout = StringIO() + + if not isatty(sys.stdin) or not isatty(stdout): + return _nullpager(stdout, generator, color) + + # Split and normalize the pager command into parts. + pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False) + if pager_cmd_parts: + if WIN: + if _tempfilepager(generator, pager_cmd_parts, color): + return + elif _pipepager(generator, pager_cmd_parts, color): + return + + if os.environ.get("TERM") in ("dumb", "emacs"): + return _nullpager(stdout, generator, color) + if (WIN or sys.platform.startswith("os2")) and _tempfilepager( + generator, ["more"], color + ): + return + if _pipepager(generator, ["less"], color): + return + + import tempfile + + fd, filename = tempfile.mkstemp() + os.close(fd) + try: + if _pipepager(generator, ["more"], color): + return + return _nullpager(stdout, generator, color) + finally: + os.unlink(filename) + + +def _pipepager( + generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None +) -> bool: + """Page through text by feeding it to another program. Invoking a + pager through this might support colors. + + Returns `True` if the command was found, `False` otherwise and thus another + pager should be attempted. + """ + # Split the command into the invoked CLI and its parameters. + if not cmd_parts: + return False + cmd = cmd_parts[0] + cmd_params = cmd_parts[1:] + + cmd_filepath = which(cmd) + if not cmd_filepath: + return False + # Resolves symlinks and produces a normalized absolute path string. + cmd_path = Path(cmd_filepath).resolve() + cmd_name = cmd_path.name + + import subprocess + + # Make a local copy of the environment to not affect the global one. + env = dict(os.environ) + + # If we're piping to less and the user hasn't decided on colors, we enable + # them by default we find the -R flag in the command line arguments. + if color is None and cmd_name == "less": + less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}" + if not less_flags: + env["LESS"] = "-R" + color = True + elif "r" in less_flags or "R" in less_flags: + color = True + + c = subprocess.Popen( + [str(cmd_path)] + cmd_params, + shell=True, + stdin=subprocess.PIPE, + env=env, + errors="replace", + text=True, + ) + assert c.stdin is not None + try: + for text in generator: + if not color: + text = strip_ansi(text) + + c.stdin.write(text) + except BrokenPipeError: + # In case the pager exited unexpectedly, ignore the broken pipe error. + pass + except Exception as e: + # In case there is an exception we want to close the pager immediately + # and let the caller handle it. + # Otherwise the pager will keep running, and the user may not notice + # the error message, or worse yet it may leave the terminal in a broken state. + c.terminate() + raise e + finally: + # We must close stdin and wait for the pager to exit before we continue + try: + c.stdin.close() + # Close implies flush, so it might throw a BrokenPipeError if the pager + # process exited already. + except BrokenPipeError: + pass + + # Less doesn't respect ^C, but catches it for its own UI purposes (aborting + # search or other commands inside less). + # + # That means when the user hits ^C, the parent process (click) terminates, + # but less is still alive, paging the output and messing up the terminal. + # + # If the user wants to make the pager exit on ^C, they should set + # `LESS='-K'`. It's not our decision to make. + while True: + try: + c.wait() + except KeyboardInterrupt: + pass + else: + break + + return True + + +def _tempfilepager( + generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None +) -> bool: + """Page through text by invoking a program on a temporary file. + + Returns `True` if the command was found, `False` otherwise and thus another + pager should be attempted. + """ + # Split the command into the invoked CLI and its parameters. + if not cmd_parts: + return False + cmd = cmd_parts[0] + + cmd_filepath = which(cmd) + if not cmd_filepath: + return False + # Resolves symlinks and produces a normalized absolute path string. + cmd_path = Path(cmd_filepath).resolve() + + import subprocess + import tempfile + + fd, filename = tempfile.mkstemp() + # TODO: This never terminates if the passed generator never terminates. + text = "".join(generator) + if not color: + text = strip_ansi(text) + encoding = get_best_encoding(sys.stdout) + with open_stream(filename, "wb")[0] as f: + f.write(text.encode(encoding)) + try: + subprocess.call([str(cmd_path), filename]) + except OSError: + # Command not found + pass + finally: + os.close(fd) + os.unlink(filename) + + return True + + +def _nullpager( + stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None +) -> None: + """Simply print unformatted text. This is the ultimate fallback.""" + for text in generator: + if not color: + text = strip_ansi(text) + stream.write(text) + + +class Editor: + def __init__( + self, + editor: str | None = None, + env: cabc.Mapping[str, str] | None = None, + require_save: bool = True, + extension: str = ".txt", + ) -> None: + self.editor = editor + self.env = env + self.require_save = require_save + self.extension = extension + + def get_editor(self) -> str: + if self.editor is not None: + return self.editor + for key in "VISUAL", "EDITOR": + rv = os.environ.get(key) + if rv: + return rv + if WIN: + return "notepad" + for editor in "sensible-editor", "vim", "nano": + if which(editor) is not None: + return editor + return "vi" + + def edit_files(self, filenames: cabc.Iterable[str]) -> None: + import subprocess + + editor = self.get_editor() + environ: dict[str, str] | None = None + + if self.env: + environ = os.environ.copy() + environ.update(self.env) + + exc_filename = " ".join(f'"{filename}"' for filename in filenames) + + try: + c = subprocess.Popen( + args=f"{editor} {exc_filename}", env=environ, shell=True + ) + exit_code = c.wait() + if exit_code != 0: + raise ClickException( + _("{editor}: Editing failed").format(editor=editor) + ) + except OSError as e: + raise ClickException( + _("{editor}: Editing failed: {e}").format(editor=editor, e=e) + ) from e + + @t.overload + def edit(self, text: bytes | bytearray) -> bytes | None: ... + + # We cannot know whether or not the type expected is str or bytes when None + # is passed, so str is returned as that was what was done before. + @t.overload + def edit(self, text: str | None) -> str | None: ... + + def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None: + import tempfile + + if text is None: + data = b"" + elif isinstance(text, (bytes, bytearray)): + data = text + else: + if text and not text.endswith("\n"): + text += "\n" + + if WIN: + data = text.replace("\n", "\r\n").encode("utf-8-sig") + else: + data = text.encode("utf-8") + + fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension) + f: t.BinaryIO + + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + + # If the filesystem resolution is 1 second, like Mac OS + # 10.12 Extended, or 2 seconds, like FAT32, and the editor + # closes very fast, require_save can fail. Set the modified + # time to be 2 seconds in the past to work around this. + os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2)) + # Depending on the resolution, the exact value might not be + # recorded, so get the new recorded value. + timestamp = os.path.getmtime(name) + + self.edit_files((name,)) + + if self.require_save and os.path.getmtime(name) == timestamp: + return None + + with open(name, "rb") as f: + rv = f.read() + + if isinstance(text, (bytes, bytearray)): + return rv + + return rv.decode("utf-8-sig").replace("\r\n", "\n") + finally: + os.unlink(name) + + +def open_url(url: str, wait: bool = False, locate: bool = False) -> int: + import subprocess + + def _unquote_file(url: str) -> str: + from urllib.parse import unquote + + if url.startswith("file://"): + url = unquote(url[7:]) + + return url + + if sys.platform == "darwin": + args = ["open"] + if wait: + args.append("-W") + if locate: + args.append("-R") + args.append(_unquote_file(url)) + null = open("/dev/null", "w") + try: + return subprocess.Popen(args, stderr=null).wait() + finally: + null.close() + elif WIN: + if locate: + url = _unquote_file(url) + args = ["explorer", f"/select,{url}"] + else: + args = ["start"] + if wait: + args.append("/WAIT") + args.append("") + args.append(url) + try: + return subprocess.call(args) + except OSError: + # Command not found + return 127 + elif CYGWIN: + if locate: + url = _unquote_file(url) + args = ["cygstart", os.path.dirname(url)] + else: + args = ["cygstart"] + if wait: + args.append("-w") + args.append(url) + try: + return subprocess.call(args) + except OSError: + # Command not found + return 127 + + try: + if locate: + url = os.path.dirname(_unquote_file(url)) or "." + else: + url = _unquote_file(url) + c = subprocess.Popen(["xdg-open", url]) + if wait: + return c.wait() + return 0 + except OSError: + if url.startswith(("http://", "https://")) and not locate and not wait: + import webbrowser + + webbrowser.open(url) + return 0 + return 1 + + +def _translate_ch_to_exc(ch: str) -> None: + if ch == "\x03": + raise KeyboardInterrupt() + + if ch == "\x04" and not WIN: # Unix-like, Ctrl+D + raise EOFError() + + if ch == "\x1a" and WIN: # Windows, Ctrl+Z + raise EOFError() + + return None + + +if sys.platform == "win32": + import msvcrt + + @contextlib.contextmanager + def raw_terminal() -> cabc.Iterator[int]: + yield -1 + + def getchar(echo: bool) -> str: + # The function `getch` will return a bytes object corresponding to + # the pressed character. Since Windows 10 build 1803, it will also + # return \x00 when called a second time after pressing a regular key. + # + # `getwch` does not share this probably-bugged behavior. Moreover, it + # returns a Unicode object by default, which is what we want. + # + # Either of these functions will return \x00 or \xe0 to indicate + # a special key, and you need to call the same function again to get + # the "rest" of the code. The fun part is that \u00e0 is + # "latin small letter a with grave", so if you type that on a French + # keyboard, you _also_ get a \xe0. + # E.g., consider the Up arrow. This returns \xe0 and then \x48. The + # resulting Unicode string reads as "a with grave" + "capital H". + # This is indistinguishable from when the user actually types + # "a with grave" and then "capital H". + # + # When \xe0 is returned, we assume it's part of a special-key sequence + # and call `getwch` again, but that means that when the user types + # the \u00e0 character, `getchar` doesn't return until a second + # character is typed. + # The alternative is returning immediately, but that would mess up + # cross-platform handling of arrow keys and others that start with + # \xe0. Another option is using `getch`, but then we can't reliably + # read non-ASCII characters, because return values of `getch` are + # limited to the current 8-bit codepage. + # + # Anyway, Click doesn't claim to do this Right(tm), and using `getwch` + # is doing the right thing in more situations than with `getch`. + + if echo: + func = t.cast(t.Callable[[], str], msvcrt.getwche) + else: + func = t.cast(t.Callable[[], str], msvcrt.getwch) + + rv = func() + + if rv in ("\x00", "\xe0"): + # \x00 and \xe0 are control characters that indicate special key, + # see above. + rv += func() + + _translate_ch_to_exc(rv) + return rv + +else: + import termios + import tty + + @contextlib.contextmanager + def raw_terminal() -> cabc.Iterator[int]: + f: t.TextIO | None + fd: int + + if not isatty(sys.stdin): + f = open("/dev/tty") + fd = f.fileno() + else: + fd = sys.stdin.fileno() + f = None + + try: + old_settings = termios.tcgetattr(fd) + + try: + tty.setraw(fd) + yield fd + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + sys.stdout.flush() + + if f is not None: + f.close() + except termios.error: + pass + + def getchar(echo: bool) -> str: + with raw_terminal() as fd: + ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace") + + if echo and isatty(sys.stdout): + sys.stdout.write(ch) + + _translate_ch_to_exc(ch) + return ch diff --git a/miniconda3/lib/python3.13/site-packages/click/_textwrap.py b/miniconda3/lib/python3.13/site-packages/click/_textwrap.py new file mode 100644 index 0000000000000000000000000000000000000000..97fbee3dc6ce372600e702d38d9139bcf6a40bec --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/_textwrap.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import collections.abc as cabc +import textwrap +from 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) diff --git a/miniconda3/lib/python3.13/site-packages/click/_winconsole.py b/miniconda3/lib/python3.13/site-packages/click/_winconsole.py new file mode 100644 index 0000000000000000000000000000000000000000..e56c7c6ae7ee7e577db6ace659cd58c0c652074c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/_winconsole.py @@ -0,0 +1,296 @@ +# This module is based on the excellent work by Adam Bartoš who +# provided a lot of what went into the implementation here in +# the discussion to issue1602 in the Python bug tracker. +# +# There are some general differences in regards to how this works +# compared to the original patches as we do not need to patch +# the entire interpreter but just work in our little world of +# echo and prompt. +from __future__ import annotations + +import collections.abc as cabc +import io +import sys +import time +import typing as t +from ctypes import Array +from ctypes import byref +from ctypes import c_char +from ctypes import c_char_p +from ctypes import c_int +from ctypes import c_ssize_t +from ctypes import c_ulong +from ctypes import c_void_p +from ctypes import POINTER +from ctypes import py_object +from ctypes import Structure +from ctypes.wintypes import DWORD +from ctypes.wintypes import HANDLE +from ctypes.wintypes import LPCWSTR +from ctypes.wintypes import LPWSTR + +from ._compat import _NonClosingTextIOWrapper + +assert sys.platform == "win32" +import msvcrt # noqa: E402 +from ctypes import windll # noqa: E402 +from ctypes import WINFUNCTYPE # noqa: E402 + +c_ssize_p = POINTER(c_ssize_t) + +kernel32 = windll.kernel32 +GetStdHandle = kernel32.GetStdHandle +ReadConsoleW = kernel32.ReadConsoleW +WriteConsoleW = kernel32.WriteConsoleW +GetConsoleMode = kernel32.GetConsoleMode +GetLastError = kernel32.GetLastError +GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32)) +CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( + ("CommandLineToArgvW", windll.shell32) +) +LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32)) + +STDIN_HANDLE = GetStdHandle(-10) +STDOUT_HANDLE = GetStdHandle(-11) +STDERR_HANDLE = GetStdHandle(-12) + +PyBUF_SIMPLE = 0 +PyBUF_WRITABLE = 1 + +ERROR_SUCCESS = 0 +ERROR_NOT_ENOUGH_MEMORY = 8 +ERROR_OPERATION_ABORTED = 995 + +STDIN_FILENO = 0 +STDOUT_FILENO = 1 +STDERR_FILENO = 2 + +EOF = b"\x1a" +MAX_BYTES_WRITTEN = 32767 + +if t.TYPE_CHECKING: + try: + # Using `typing_extensions.Buffer` instead of `collections.abc` + # on Windows for some reason does not have `Sized` implemented. + from collections.abc import Buffer # type: ignore + except ImportError: + from typing_extensions import Buffer + +try: + from ctypes import pythonapi +except ImportError: + # On PyPy we cannot get buffers so our ability to operate here is + # severely limited. + get_buffer = None +else: + + class Py_buffer(Structure): + _fields_ = [ # noqa: RUF012 + ("buf", c_void_p), + ("obj", py_object), + ("len", c_ssize_t), + ("itemsize", c_ssize_t), + ("readonly", c_int), + ("ndim", c_int), + ("format", c_char_p), + ("shape", c_ssize_p), + ("strides", c_ssize_p), + ("suboffsets", c_ssize_p), + ("internal", c_void_p), + ] + + PyObject_GetBuffer = pythonapi.PyObject_GetBuffer + PyBuffer_Release = pythonapi.PyBuffer_Release + + def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]: + buf = Py_buffer() + flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE + PyObject_GetBuffer(py_object(obj), byref(buf), flags) + + try: + buffer_type = c_char * buf.len + out: Array[c_char] = buffer_type.from_address(buf.buf) + return out + finally: + PyBuffer_Release(byref(buf)) + + +class _WindowsConsoleRawIOBase(io.RawIOBase): + def __init__(self, handle: int | None) -> None: + self.handle = handle + + def isatty(self) -> t.Literal[True]: + super().isatty() + return True + + +class _WindowsConsoleReader(_WindowsConsoleRawIOBase): + def readable(self) -> t.Literal[True]: + return True + + def readinto(self, b: Buffer) -> int: + bytes_to_be_read = len(b) + if not bytes_to_be_read: + return 0 + elif bytes_to_be_read % 2: + raise ValueError( + "cannot read odd number of bytes from UTF-16-LE encoded console" + ) + + buffer = get_buffer(b, writable=True) + code_units_to_be_read = bytes_to_be_read // 2 + code_units_read = c_ulong() + + rv = ReadConsoleW( + HANDLE(self.handle), + buffer, + code_units_to_be_read, + byref(code_units_read), + None, + ) + if GetLastError() == ERROR_OPERATION_ABORTED: + # wait for KeyboardInterrupt + time.sleep(0.1) + if not rv: + raise OSError(f"Windows error: {GetLastError()}") + + if buffer[0] == EOF: + return 0 + return 2 * code_units_read.value + + +class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): + def writable(self) -> t.Literal[True]: + return True + + @staticmethod + def _get_error_message(errno: int) -> str: + if errno == ERROR_SUCCESS: + return "ERROR_SUCCESS" + elif errno == ERROR_NOT_ENOUGH_MEMORY: + return "ERROR_NOT_ENOUGH_MEMORY" + return f"Windows error {errno}" + + def write(self, b: Buffer) -> int: + bytes_to_be_written = len(b) + buf = get_buffer(b) + code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2 + code_units_written = c_ulong() + + WriteConsoleW( + HANDLE(self.handle), + buf, + code_units_to_be_written, + byref(code_units_written), + None, + ) + bytes_written = 2 * code_units_written.value + + if bytes_written == 0 and bytes_to_be_written > 0: + raise OSError(self._get_error_message(GetLastError())) + return bytes_written + + +class ConsoleStream: + def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None: + self._text_stream = text_stream + self.buffer = byte_stream + + @property + def name(self) -> str: + return self.buffer.name + + def write(self, x: t.AnyStr) -> int: + if isinstance(x, str): + return self._text_stream.write(x) + try: + self.flush() + except Exception: + pass + return self.buffer.write(x) + + def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None: + for line in lines: + self.write(line) + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._text_stream, name) + + def isatty(self) -> bool: + return self.buffer.isatty() + + def __repr__(self) -> str: + return f"" + + +def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO: + text_stream = _NonClosingTextIOWrapper( + io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)), + "utf-16-le", + "strict", + line_buffering=True, + ) + return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) + + +def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO: + text_stream = _NonClosingTextIOWrapper( + io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)), + "utf-16-le", + "strict", + line_buffering=True, + ) + return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) + + +def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO: + text_stream = _NonClosingTextIOWrapper( + io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)), + "utf-16-le", + "strict", + line_buffering=True, + ) + return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream)) + + +_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = { + 0: _get_text_stdin, + 1: _get_text_stdout, + 2: _get_text_stderr, +} + + +def _is_console(f: t.TextIO) -> bool: + if not hasattr(f, "fileno"): + return False + + try: + fileno = f.fileno() + except (OSError, io.UnsupportedOperation): + return False + + handle = msvcrt.get_osfhandle(fileno) + return bool(GetConsoleMode(handle, byref(DWORD()))) + + +def _get_windows_console_stream( + f: t.TextIO, encoding: str | None, errors: str | None +) -> t.TextIO | None: + if ( + get_buffer is None + or encoding not in {"utf-16-le", None} + or errors not in {"strict", None} + or not _is_console(f) + ): + return None + + func = _stream_factories.get(f.fileno()) + if func is None: + return None + + b = getattr(f, "buffer", None) + + if b is None: + return None + + return func(b) diff --git a/miniconda3/lib/python3.13/site-packages/click/core.py b/miniconda3/lib/python3.13/site-packages/click/core.py new file mode 100644 index 0000000000000000000000000000000000000000..f57ada62b195fa533387b5d06b366b17edb7d2f4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/core.py @@ -0,0 +1,3135 @@ +from __future__ import annotations + +import collections.abc as cabc +import enum +import errno +import inspect +import os +import sys +import typing as t +from collections import abc +from collections import Counter +from contextlib import AbstractContextManager +from contextlib import contextmanager +from contextlib import ExitStack +from functools import update_wrapper +from gettext import gettext as _ +from gettext import ngettext +from itertools import repeat +from types import TracebackType + +from . import types +from .exceptions import Abort +from .exceptions import BadParameter +from .exceptions import ClickException +from .exceptions import Exit +from .exceptions import MissingParameter +from .exceptions import NoArgsIsHelpError +from .exceptions import UsageError +from .formatting import HelpFormatter +from .formatting import join_options +from .globals import pop_context +from .globals import push_context +from .parser import _flag_needs_value +from .parser import _OptionParser +from .parser import _split_opt +from .termui import confirm +from .termui import prompt +from .termui import style +from .utils import _detect_program_name +from .utils import _expand_args +from .utils import echo +from .utils import make_default_short_help +from .utils import make_str +from .utils import PacifyFlushWrapper + +if t.TYPE_CHECKING: + from .shell_completion import CompletionItem + +F = t.TypeVar("F", bound="t.Callable[..., t.Any]") +V = t.TypeVar("V") + + +def _complete_visible_commands( + ctx: Context, incomplete: str +) -> cabc.Iterator[tuple[str, Command]]: + """List all the subcommands of a group that start with the + incomplete value and aren't hidden. + + :param ctx: Invocation context for the group. + :param incomplete: Value being completed. May be empty. + """ + multi = t.cast(Group, ctx.command) + + for name in multi.list_commands(ctx): + if name.startswith(incomplete): + command = multi.get_command(ctx, name) + + if command is not None and not command.hidden: + yield name, command + + +def _check_nested_chain( + base_command: Group, cmd_name: str, cmd: Command, register: bool = False +) -> None: + if not base_command.chain or not isinstance(cmd, Group): + return + + if register: + message = ( + f"It is not possible to add the group {cmd_name!r} to another" + f" group {base_command.name!r} that is in chain mode." + ) + else: + message = ( + f"Found the group {cmd_name!r} as subcommand to another group " + f" {base_command.name!r} that is in chain mode. This is not supported." + ) + + raise RuntimeError(message) + + +def batch(iterable: cabc.Iterable[V], batch_size: int) -> list[tuple[V, ...]]: + return list(zip(*repeat(iter(iterable), batch_size), strict=False)) + + +@contextmanager +def augment_usage_errors( + ctx: Context, param: Parameter | None = None +) -> cabc.Iterator[None]: + """Context manager that attaches extra information to exceptions.""" + try: + yield + except BadParameter as e: + if e.ctx is None: + e.ctx = ctx + if param is not None and e.param is None: + e.param = param + raise + except UsageError as e: + if e.ctx is None: + e.ctx = ctx + raise + + +def iter_params_for_processing( + invocation_order: cabc.Sequence[Parameter], + declaration_order: cabc.Sequence[Parameter], +) -> list[Parameter]: + """Returns all declared parameters in the order they should be processed. + + The declared parameters are re-shuffled depending on the order in which + they were invoked, as well as the eagerness of each parameters. + + The invocation order takes precedence over the declaration order. I.e. the + order in which the user provided them to the CLI is respected. + + This behavior and its effect on callback evaluation is detailed at: + https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order + """ + + def sort_key(item: Parameter) -> tuple[bool, float]: + try: + idx: float = invocation_order.index(item) + except ValueError: + idx = float("inf") + + return not item.is_eager, idx + + return sorted(declaration_order, key=sort_key) + + +class ParameterSource(enum.Enum): + """This is an :class:`~enum.Enum` that indicates the source of a + parameter's value. + + Use :meth:`click.Context.get_parameter_source` to get the + source for a parameter by name. + + .. versionchanged:: 8.0 + Use :class:`~enum.Enum` and drop the ``validate`` method. + + .. versionchanged:: 8.0 + Added the ``PROMPT`` value. + """ + + COMMANDLINE = enum.auto() + """The value was provided by the command line args.""" + ENVIRONMENT = enum.auto() + """The value was provided with an environment variable.""" + DEFAULT = enum.auto() + """Used the default specified by the parameter.""" + DEFAULT_MAP = enum.auto() + """Used a default provided by :attr:`Context.default_map`.""" + PROMPT = enum.auto() + """Used a prompt to confirm a default or provide a value.""" + + +class Context: + """The context is a special internal object that holds state relevant + for the script execution at every single level. It's normally invisible + to commands unless they opt-in to getting access to it. + + The context is useful as it can pass internal objects around and can + control special execution features such as reading data from + environment variables. + + A context can be used as context manager in which case it will call + :meth:`close` on teardown. + + :param command: the command class for this context. + :param parent: the parent context. + :param info_name: the info name for this invocation. Generally this + is the most descriptive name for the script or + command. For the toplevel script it is usually + the name of the script, for commands below it it's + the name of the script. + :param obj: an arbitrary object of user data. + :param auto_envvar_prefix: the prefix to use for automatic environment + variables. If this is `None` then reading + from environment variables is disabled. This + does not affect manually set environment + variables which are always read. + :param default_map: a dictionary (like object) with default values + for parameters. + :param terminal_width: the width of the terminal. The default is + inherit from parent context. If no context + defines the terminal width then auto + detection will be applied. + :param max_content_width: the maximum width for content rendered by + Click (this currently only affects help + pages). This defaults to 80 characters if + not overridden. In other words: even if the + terminal is larger than that, Click will not + format things wider than 80 characters by + default. In addition to that, formatters might + add some safety mapping on the right. + :param resilient_parsing: if this flag is enabled then Click will + parse without any interactivity or callback + invocation. Default values will also be + ignored. This is useful for implementing + things such as completion support. + :param allow_extra_args: if this is set to `True` then extra arguments + at the end will not raise an error and will be + kept on the context. The default is to inherit + from the command. + :param allow_interspersed_args: if this is set to `False` then options + and arguments cannot be mixed. The + default is to inherit from the command. + :param ignore_unknown_options: instructs click to ignore options it does + not know and keeps them for later + processing. + :param help_option_names: optionally a list of strings that define how + the default help parameter is named. The + default is ``['--help']``. + :param token_normalize_func: an optional function that is used to + normalize tokens (options, choices, + etc.). This for instance can be used to + implement case insensitive behavior. + :param color: controls if the terminal supports ANSI colors or not. The + default is autodetection. This is only needed if ANSI + codes are used in texts that Click prints which is by + default not the case. This for instance would affect + help output. + :param show_default: Show the default value for commands. If this + value is not set, it defaults to the value from the parent + context. ``Command.show_default`` overrides this default for the + specific command. + + .. versionchanged:: 8.2 + The ``protected_args`` attribute is deprecated and will be removed in + Click 9.0. ``args`` will contain remaining unparsed tokens. + + .. versionchanged:: 8.1 + The ``show_default`` parameter is overridden by + ``Command.show_default``, instead of the other way around. + + .. versionchanged:: 8.0 + The ``show_default`` parameter defaults to the value from the + parent context. + + .. versionchanged:: 7.1 + Added the ``show_default`` parameter. + + .. versionchanged:: 4.0 + Added the ``color``, ``ignore_unknown_options``, and + ``max_content_width`` parameters. + + .. versionchanged:: 3.0 + Added the ``allow_extra_args`` and ``allow_interspersed_args`` + parameters. + + .. versionchanged:: 2.0 + Added the ``resilient_parsing``, ``help_option_names``, and + ``token_normalize_func`` parameters. + """ + + #: The formatter class to create with :meth:`make_formatter`. + #: + #: .. versionadded:: 8.0 + formatter_class: type[HelpFormatter] = HelpFormatter + + def __init__( + self, + command: Command, + parent: Context | None = None, + info_name: str | None = None, + obj: t.Any | None = None, + auto_envvar_prefix: str | None = None, + default_map: cabc.MutableMapping[str, t.Any] | None = None, + terminal_width: int | None = None, + max_content_width: int | None = None, + resilient_parsing: bool = False, + allow_extra_args: bool | None = None, + allow_interspersed_args: bool | None = None, + ignore_unknown_options: bool | None = None, + help_option_names: list[str] | None = None, + token_normalize_func: t.Callable[[str], str] | None = None, + color: bool | None = None, + show_default: bool | None = None, + ) -> None: + #: the parent context or `None` if none exists. + self.parent = parent + #: the :class:`Command` for this context. + self.command = command + #: the descriptive information name + self.info_name = info_name + #: Map of parameter names to their parsed values. Parameters + #: with ``expose_value=False`` are not stored. + self.params: dict[str, t.Any] = {} + #: the leftover arguments. + self.args: list[str] = [] + #: protected arguments. These are arguments that are prepended + #: to `args` when certain parsing scenarios are encountered but + #: must be never propagated to another arguments. This is used + #: to implement nested parsing. + self._protected_args: list[str] = [] + #: the collected prefixes of the command's options. + self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set() + + if obj is None and parent is not None: + obj = parent.obj + + #: the user object stored. + self.obj: t.Any = obj + self._meta: dict[str, t.Any] = getattr(parent, "meta", {}) + + #: A dictionary (-like object) with defaults for parameters. + if ( + default_map is None + and info_name is not None + and parent is not None + and parent.default_map is not None + ): + default_map = parent.default_map.get(info_name) + + self.default_map: cabc.MutableMapping[str, t.Any] | None = default_map + + #: This flag indicates if a subcommand is going to be executed. A + #: group callback can use this information to figure out if it's + #: being executed directly or because the execution flow passes + #: onwards to a subcommand. By default it's None, but it can be + #: the name of the subcommand to execute. + #: + #: If chaining is enabled this will be set to ``'*'`` in case + #: any commands are executed. It is however not possible to + #: figure out which ones. If you require this knowledge you + #: should use a :func:`result_callback`. + self.invoked_subcommand: str | None = None + + if terminal_width is None and parent is not None: + terminal_width = parent.terminal_width + + #: The width of the terminal (None is autodetection). + self.terminal_width: int | None = terminal_width + + if max_content_width is None and parent is not None: + max_content_width = parent.max_content_width + + #: The maximum width of formatted content (None implies a sensible + #: default which is 80 for most things). + self.max_content_width: int | None = max_content_width + + if allow_extra_args is None: + allow_extra_args = command.allow_extra_args + + #: Indicates if the context allows extra args or if it should + #: fail on parsing. + #: + #: .. versionadded:: 3.0 + self.allow_extra_args = allow_extra_args + + if allow_interspersed_args is None: + allow_interspersed_args = command.allow_interspersed_args + + #: Indicates if the context allows mixing of arguments and + #: options or not. + #: + #: .. versionadded:: 3.0 + self.allow_interspersed_args: bool = allow_interspersed_args + + if ignore_unknown_options is None: + ignore_unknown_options = command.ignore_unknown_options + + #: Instructs click to ignore options that a command does not + #: understand and will store it on the context for later + #: processing. This is primarily useful for situations where you + #: want to call into external programs. Generally this pattern is + #: strongly discouraged because it's not possibly to losslessly + #: forward all arguments. + #: + #: .. versionadded:: 4.0 + self.ignore_unknown_options: bool = ignore_unknown_options + + if help_option_names is None: + if parent is not None: + help_option_names = parent.help_option_names + else: + help_option_names = ["--help"] + + #: The names for the help options. + self.help_option_names: list[str] = help_option_names + + if token_normalize_func is None and parent is not None: + token_normalize_func = parent.token_normalize_func + + #: An optional normalization function for tokens. This is + #: options, choices, commands etc. + self.token_normalize_func: t.Callable[[str], str] | None = token_normalize_func + + #: Indicates if resilient parsing is enabled. In that case Click + #: will do its best to not cause any failures and default values + #: will be ignored. Useful for completion. + self.resilient_parsing: bool = resilient_parsing + + # If there is no envvar prefix yet, but the parent has one and + # the command on this level has a name, we can expand the envvar + # prefix automatically. + if auto_envvar_prefix is None: + if ( + parent is not None + and parent.auto_envvar_prefix is not None + and self.info_name is not None + ): + auto_envvar_prefix = ( + f"{parent.auto_envvar_prefix}_{self.info_name.upper()}" + ) + else: + auto_envvar_prefix = auto_envvar_prefix.upper() + + if auto_envvar_prefix is not None: + auto_envvar_prefix = auto_envvar_prefix.replace("-", "_") + + self.auto_envvar_prefix: str | None = auto_envvar_prefix + + if color is None and parent is not None: + color = parent.color + + #: Controls if styling output is wanted or not. + self.color: bool | None = color + + if show_default is None and parent is not None: + show_default = parent.show_default + + #: Show option default values when formatting help text. + self.show_default: bool | None = show_default + + self._close_callbacks: list[t.Callable[[], t.Any]] = [] + self._depth = 0 + self._parameter_source: dict[str, ParameterSource] = {} + self._exit_stack = ExitStack() + + @property + def protected_args(self) -> list[str]: + import warnings + + warnings.warn( + "'protected_args' is deprecated and will be removed in Click 9.0." + " 'args' will contain remaining unparsed tokens.", + DeprecationWarning, + stacklevel=2, + ) + return self._protected_args + + def to_info_dict(self) -> dict[str, t.Any]: + """Gather information that could be useful for a tool generating + user-facing documentation. This traverses the entire CLI + structure. + + .. code-block:: python + + with Context(cli) as ctx: + info = ctx.to_info_dict() + + .. versionadded:: 8.0 + """ + return { + "command": self.command.to_info_dict(self), + "info_name": self.info_name, + "allow_extra_args": self.allow_extra_args, + "allow_interspersed_args": self.allow_interspersed_args, + "ignore_unknown_options": self.ignore_unknown_options, + "auto_envvar_prefix": self.auto_envvar_prefix, + } + + def __enter__(self) -> Context: + self._depth += 1 + push_context(self) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self._depth -= 1 + if self._depth == 0: + self.close() + pop_context() + + @contextmanager + def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]: + """This helper method can be used with the context object to promote + it to the current thread local (see :func:`get_current_context`). + The default behavior of this is to invoke the cleanup functions which + can be disabled by setting `cleanup` to `False`. The cleanup + functions are typically used for things such as closing file handles. + + If the cleanup is intended the context object can also be directly + used as a context manager. + + Example usage:: + + with ctx.scope(): + assert get_current_context() is ctx + + This is equivalent:: + + with ctx: + assert get_current_context() is ctx + + .. versionadded:: 5.0 + + :param cleanup: controls if the cleanup functions should be run or + not. The default is to run these functions. In + some situations the context only wants to be + temporarily pushed in which case this can be disabled. + Nested pushes automatically defer the cleanup. + """ + if not cleanup: + self._depth += 1 + try: + with self as rv: + yield rv + finally: + if not cleanup: + self._depth -= 1 + + @property + def meta(self) -> dict[str, t.Any]: + """This is a dictionary which is shared with all the contexts + that are nested. It exists so that click utilities can store some + state here if they need to. It is however the responsibility of + that code to manage this dictionary well. + + The keys are supposed to be unique dotted strings. For instance + module paths are a good choice for it. What is stored in there is + irrelevant for the operation of click. However what is important is + that code that places data here adheres to the general semantics of + the system. + + Example usage:: + + LANG_KEY = f'{__name__}.lang' + + def set_language(value): + ctx = get_current_context() + ctx.meta[LANG_KEY] = value + + def get_language(): + return get_current_context().meta.get(LANG_KEY, 'en_US') + + .. versionadded:: 5.0 + """ + return self._meta + + def make_formatter(self) -> HelpFormatter: + """Creates the :class:`~click.HelpFormatter` for the help and + usage output. + + To quickly customize the formatter class used without overriding + this method, set the :attr:`formatter_class` attribute. + + .. versionchanged:: 8.0 + Added the :attr:`formatter_class` attribute. + """ + return self.formatter_class( + width=self.terminal_width, max_width=self.max_content_width + ) + + def with_resource(self, context_manager: AbstractContextManager[V]) -> V: + """Register a resource as if it were used in a ``with`` + statement. The resource will be cleaned up when the context is + popped. + + Uses :meth:`contextlib.ExitStack.enter_context`. It calls the + resource's ``__enter__()`` method and returns the result. When + the context is popped, it closes the stack, which calls the + resource's ``__exit__()`` method. + + To register a cleanup function for something that isn't a + context manager, use :meth:`call_on_close`. Or use something + from :mod:`contextlib` to turn it into a context manager first. + + .. code-block:: python + + @click.group() + @click.option("--name") + @click.pass_context + def cli(ctx): + ctx.obj = ctx.with_resource(connect_db(name)) + + :param context_manager: The context manager to enter. + :return: Whatever ``context_manager.__enter__()`` returns. + + .. versionadded:: 8.0 + """ + return self._exit_stack.enter_context(context_manager) + + def call_on_close(self, f: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]: + """Register a function to be called when the context tears down. + + This can be used to close resources opened during the script + execution. Resources that support Python's context manager + protocol which would be used in a ``with`` statement should be + registered with :meth:`with_resource` instead. + + :param f: The function to execute on teardown. + """ + return self._exit_stack.callback(f) + + def close(self) -> None: + """Invoke all close callbacks registered with + :meth:`call_on_close`, and exit all context managers entered + with :meth:`with_resource`. + """ + self._exit_stack.close() + # In case the context is reused, create a new exit stack. + self._exit_stack = ExitStack() + + @property + def command_path(self) -> str: + """The computed command path. This is used for the ``usage`` + information on the help page. It's automatically created by + combining the info names of the chain of contexts to the root. + """ + rv = "" + if self.info_name is not None: + rv = self.info_name + if self.parent is not None: + parent_command_path = [self.parent.command_path] + + if isinstance(self.parent.command, Command): + for param in self.parent.command.get_params(self): + parent_command_path.extend(param.get_usage_pieces(self)) + + rv = f"{' '.join(parent_command_path)} {rv}" + return rv.lstrip() + + def find_root(self) -> Context: + """Finds the outermost context.""" + node = self + while node.parent is not None: + node = node.parent + return node + + def find_object(self, object_type: type[V]) -> V | None: + """Finds the closest object of a given type.""" + node: Context | None = self + + while node is not None: + if isinstance(node.obj, object_type): + return node.obj + + node = node.parent + + return None + + def ensure_object(self, object_type: type[V]) -> V: + """Like :meth:`find_object` but sets the innermost object to a + new instance of `object_type` if it does not exist. + """ + rv = self.find_object(object_type) + if rv is None: + self.obj = rv = object_type() + return rv + + @t.overload + def lookup_default( + self, name: str, call: t.Literal[True] = True + ) -> t.Any | None: ... + + @t.overload + def lookup_default( + self, name: str, call: t.Literal[False] = ... + ) -> t.Any | t.Callable[[], t.Any] | None: ... + + def lookup_default(self, name: str, call: bool = True) -> t.Any | None: + """Get the default for a parameter from :attr:`default_map`. + + :param name: Name of the parameter. + :param call: If the default is a callable, call it. Disable to + return the callable instead. + + .. versionchanged:: 8.0 + Added the ``call`` parameter. + """ + if self.default_map is not None: + value = self.default_map.get(name) + + if call and callable(value): + return value() + + return value + + return None + + def fail(self, message: str) -> t.NoReturn: + """Aborts the execution of the program with a specific error + message. + + :param message: the error message to fail with. + """ + raise UsageError(message, self) + + def abort(self) -> t.NoReturn: + """Aborts the script.""" + raise Abort() + + def exit(self, code: int = 0) -> t.NoReturn: + """Exits the application with a given exit code. + + .. versionchanged:: 8.2 + Callbacks and context managers registered with :meth:`call_on_close` + and :meth:`with_resource` are closed before exiting. + """ + self.close() + raise Exit(code) + + def get_usage(self) -> str: + """Helper method to get formatted usage string for the current + context and command. + """ + return self.command.get_usage(self) + + def get_help(self) -> str: + """Helper method to get formatted help page for the current + context and command. + """ + return self.command.get_help(self) + + def _make_sub_context(self, command: Command) -> Context: + """Create a new context of the same type as this context, but + for a new command. + + :meta private: + """ + return type(self)(command, info_name=command.name, parent=self) + + @t.overload + def invoke( + self, callback: t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any + ) -> V: ... + + @t.overload + def invoke(self, callback: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: ... + + def invoke( + self, callback: Command | t.Callable[..., V], /, *args: t.Any, **kwargs: t.Any + ) -> t.Any | V: + """Invokes a command callback in exactly the way it expects. There + are two ways to invoke this method: + + 1. the first argument can be a callback and all other arguments and + keyword arguments are forwarded directly to the function. + 2. the first argument is a click command object. In that case all + arguments are forwarded as well but proper click parameters + (options and click arguments) must be keyword arguments and Click + will fill in defaults. + + .. versionchanged:: 8.0 + All ``kwargs`` are tracked in :attr:`params` so they will be + passed if :meth:`forward` is called at multiple levels. + + .. versionchanged:: 3.2 + A new context is created, and missing arguments use default values. + """ + if isinstance(callback, Command): + other_cmd = callback + + if other_cmd.callback is None: + raise TypeError( + "The given command does not have a callback that can be invoked." + ) + else: + callback = t.cast("t.Callable[..., V]", other_cmd.callback) + + ctx = self._make_sub_context(other_cmd) + + for param in other_cmd.params: + if param.name not in kwargs and param.expose_value: + kwargs[param.name] = param.type_cast_value( # type: ignore + ctx, param.get_default(ctx) + ) + + # Track all kwargs as params, so that forward() will pass + # them on in subsequent calls. + ctx.params.update(kwargs) + else: + ctx = self + + with augment_usage_errors(self): + with ctx: + return callback(*args, **kwargs) + + def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any: + """Similar to :meth:`invoke` but fills in default keyword + arguments from the current context if the other command expects + it. This cannot invoke callbacks directly, only other commands. + + .. versionchanged:: 8.0 + All ``kwargs`` are tracked in :attr:`params` so they will be + passed if ``forward`` is called at multiple levels. + """ + # Can only forward to other commands, not direct callbacks. + if not isinstance(cmd, Command): + raise TypeError("Callback is not a command.") + + for param in self.params: + if param not in kwargs: + kwargs[param] = self.params[param] + + return self.invoke(cmd, *args, **kwargs) + + def set_parameter_source(self, name: str, source: ParameterSource) -> None: + """Set the source of a parameter. This indicates the location + from which the value of the parameter was obtained. + + :param name: The name of the parameter. + :param source: A member of :class:`~click.core.ParameterSource`. + """ + self._parameter_source[name] = source + + def get_parameter_source(self, name: str) -> ParameterSource | None: + """Get the source of a parameter. This indicates the location + from which the value of the parameter was obtained. + + This can be useful for determining when a user specified a value + on the command line that is the same as the default value. It + will be :attr:`~click.core.ParameterSource.DEFAULT` only if the + value was actually taken from the default. + + :param name: The name of the parameter. + :rtype: ParameterSource + + .. versionchanged:: 8.0 + Returns ``None`` if the parameter was not provided from any + source. + """ + return self._parameter_source.get(name) + + +class Command: + """Commands are the basic building block of command line interfaces in + Click. A basic command handles command line parsing and might dispatch + more parsing to commands nested below it. + + :param name: the name of the command to use unless a group overrides it. + :param context_settings: an optional dictionary with defaults that are + passed to the context object. + :param callback: the callback to invoke. This is optional. + :param params: the parameters to register with this command. This can + be either :class:`Option` or :class:`Argument` objects. + :param help: the help string to use for this command. + :param epilog: like the help string but it's printed at the end of the + help page after everything else. + :param short_help: the short help to use for this command. This is + shown on the command listing of the parent command. + :param add_help_option: by default each command registers a ``--help`` + option. This can be disabled by this parameter. + :param no_args_is_help: this controls what happens if no arguments are + provided. This option is disabled by default. + If enabled this will add ``--help`` as argument + if no arguments are passed + :param hidden: hide this command from help outputs. + :param deprecated: If ``True`` or non-empty string, issues a message + indicating that the command is deprecated and highlights + its deprecation in --help. The message can be customized + by using a string as the value. + + .. versionchanged:: 8.2 + This is the base class for all commands, not ``BaseCommand``. + ``deprecated`` can be set to a string as well to customize the + deprecation message. + + .. versionchanged:: 8.1 + ``help``, ``epilog``, and ``short_help`` are stored unprocessed, + all formatting is done when outputting help text, not at init, + and is done even if not using the ``@command`` decorator. + + .. versionchanged:: 8.0 + Added a ``repr`` showing the command name. + + .. versionchanged:: 7.1 + Added the ``no_args_is_help`` parameter. + + .. versionchanged:: 2.0 + Added the ``context_settings`` parameter. + """ + + #: The context class to create with :meth:`make_context`. + #: + #: .. versionadded:: 8.0 + context_class: type[Context] = Context + + #: the default for the :attr:`Context.allow_extra_args` flag. + allow_extra_args = False + + #: the default for the :attr:`Context.allow_interspersed_args` flag. + allow_interspersed_args = True + + #: the default for the :attr:`Context.ignore_unknown_options` flag. + ignore_unknown_options = False + + def __init__( + self, + name: str | None, + context_settings: cabc.MutableMapping[str, t.Any] | None = None, + callback: t.Callable[..., t.Any] | None = None, + params: list[Parameter] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str | None = "[OPTIONS]", + add_help_option: bool = True, + no_args_is_help: bool = False, + hidden: bool = False, + deprecated: bool | str = False, + ) -> None: + #: the name the command thinks it has. Upon registering a command + #: on a :class:`Group` the group will default the command name + #: with this information. You should instead use the + #: :class:`Context`\'s :attr:`~Context.info_name` attribute. + self.name = name + + if context_settings is None: + context_settings = {} + + #: an optional dictionary with defaults passed to the context. + self.context_settings: cabc.MutableMapping[str, t.Any] = context_settings + + #: the callback to execute when the command fires. This might be + #: `None` in which case nothing happens. + self.callback = callback + #: the list of parameters for this command in the order they + #: should show up in the help page and execute. Eager parameters + #: will automatically be handled before non eager ones. + self.params: list[Parameter] = params or [] + self.help = help + self.epilog = epilog + self.options_metavar = options_metavar + self.short_help = short_help + self.add_help_option = add_help_option + self._help_option = None + self.no_args_is_help = no_args_is_help + self.hidden = hidden + self.deprecated = deprecated + + def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: + return { + "name": self.name, + "params": [param.to_info_dict() for param in self.get_params(ctx)], + "help": self.help, + "epilog": self.epilog, + "short_help": self.short_help, + "hidden": self.hidden, + "deprecated": self.deprecated, + } + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} {self.name}>" + + def get_usage(self, ctx: Context) -> str: + """Formats the usage line into a string and returns it. + + Calls :meth:`format_usage` internally. + """ + formatter = ctx.make_formatter() + self.format_usage(ctx, formatter) + return formatter.getvalue().rstrip("\n") + + def get_params(self, ctx: Context) -> list[Parameter]: + params = self.params + help_option = self.get_help_option(ctx) + + if help_option is not None: + params = [*params, help_option] + + if __debug__: + import warnings + + opts = [opt for param in params for opt in param.opts] + opts_counter = Counter(opts) + duplicate_opts = (opt for opt, count in opts_counter.items() if count > 1) + + for duplicate_opt in duplicate_opts: + warnings.warn( + ( + f"The parameter {duplicate_opt} is used more than once. " + "Remove its duplicate as parameters should be unique." + ), + stacklevel=3, + ) + + return params + + def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the usage line into the formatter. + + This is a low-level method called by :meth:`get_usage`. + """ + pieces = self.collect_usage_pieces(ctx) + formatter.write_usage(ctx.command_path, " ".join(pieces)) + + def collect_usage_pieces(self, ctx: Context) -> list[str]: + """Returns all the pieces that go into the usage line and returns + it as a list of strings. + """ + rv = [self.options_metavar] if self.options_metavar else [] + + for param in self.get_params(ctx): + rv.extend(param.get_usage_pieces(ctx)) + + return rv + + def get_help_option_names(self, ctx: Context) -> list[str]: + """Returns the names for the help option.""" + all_names = set(ctx.help_option_names) + for param in self.params: + all_names.difference_update(param.opts) + all_names.difference_update(param.secondary_opts) + return list(all_names) + + def get_help_option(self, ctx: Context) -> Option | None: + """Returns the help option object. + + Skipped if :attr:`add_help_option` is ``False``. + + .. versionchanged:: 8.1.8 + The help option is now cached to avoid creating it multiple times. + """ + help_option_names = self.get_help_option_names(ctx) + + if not help_option_names or not self.add_help_option: + return None + + # Cache the help option object in private _help_option attribute to + # avoid creating it multiple times. Not doing this will break the + # callback odering by iter_params_for_processing(), which relies on + # object comparison. + if self._help_option is None: + # Avoid circular import. + from .decorators import help_option + + # Apply help_option decorator and pop resulting option + help_option(*help_option_names)(self) + self._help_option = self.params.pop() # type: ignore[assignment] + + return self._help_option + + def make_parser(self, ctx: Context) -> _OptionParser: + """Creates the underlying option parser for this command.""" + parser = _OptionParser(ctx) + for param in self.get_params(ctx): + param.add_to_parser(parser, ctx) + return parser + + def get_help(self, ctx: Context) -> str: + """Formats the help into a string and returns it. + + Calls :meth:`format_help` internally. + """ + formatter = ctx.make_formatter() + self.format_help(ctx, formatter) + return formatter.getvalue().rstrip("\n") + + def get_short_help_str(self, limit: int = 45) -> str: + """Gets short help for the command or makes it by shortening the + long help string. + """ + if self.short_help: + text = inspect.cleandoc(self.short_help) + elif self.help: + text = make_default_short_help(self.help, limit) + else: + text = "" + + if self.deprecated: + deprecated_message = ( + f"(DEPRECATED: {self.deprecated})" + if isinstance(self.deprecated, str) + else "(DEPRECATED)" + ) + text = _("{text} {deprecated_message}").format( + text=text, deprecated_message=deprecated_message + ) + + return text.strip() + + def format_help(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the help into the formatter if it exists. + + This is a low-level method called by :meth:`get_help`. + + This calls the following methods: + + - :meth:`format_usage` + - :meth:`format_help_text` + - :meth:`format_options` + - :meth:`format_epilog` + """ + self.format_usage(ctx, formatter) + self.format_help_text(ctx, formatter) + self.format_options(ctx, formatter) + self.format_epilog(ctx, formatter) + + def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the help text to the formatter if it exists.""" + if self.help is not None: + # truncate the help text to the first form feed + text = inspect.cleandoc(self.help).partition("\f")[0] + else: + text = "" + + if self.deprecated: + deprecated_message = ( + f"(DEPRECATED: {self.deprecated})" + if isinstance(self.deprecated, str) + else "(DEPRECATED)" + ) + text = _("{text} {deprecated_message}").format( + text=text, deprecated_message=deprecated_message + ) + + if text: + formatter.write_paragraph() + + with formatter.indentation(): + formatter.write_text(text) + + def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes all the options into the formatter if they exist.""" + opts = [] + for param in self.get_params(ctx): + rv = param.get_help_record(ctx) + if rv is not None: + opts.append(rv) + + if opts: + with formatter.section(_("Options")): + formatter.write_dl(opts) + + def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None: + """Writes the epilog into the formatter if it exists.""" + if self.epilog: + epilog = inspect.cleandoc(self.epilog) + formatter.write_paragraph() + + with formatter.indentation(): + formatter.write_text(epilog) + + def make_context( + self, + info_name: str | None, + args: list[str], + parent: Context | None = None, + **extra: t.Any, + ) -> Context: + """This function when given an info name and arguments will kick + off the parsing and create a new :class:`Context`. It does not + invoke the actual command callback though. + + To quickly customize the context class used without overriding + this method, set the :attr:`context_class` attribute. + + :param info_name: the info name for this invocation. Generally this + is the most descriptive name for the script or + command. For the toplevel script it's usually + the name of the script, for commands below it's + the name of the command. + :param args: the arguments to parse as list of strings. + :param parent: the parent context if available. + :param extra: extra keyword arguments forwarded to the context + constructor. + + .. versionchanged:: 8.0 + Added the :attr:`context_class` attribute. + """ + for key, value in self.context_settings.items(): + if key not in extra: + extra[key] = value + + ctx = self.context_class(self, info_name=info_name, parent=parent, **extra) + + with ctx.scope(cleanup=False): + self.parse_args(ctx, args) + return ctx + + def parse_args(self, ctx: Context, args: list[str]) -> list[str]: + if not args and self.no_args_is_help and not ctx.resilient_parsing: + raise NoArgsIsHelpError(ctx) + + parser = self.make_parser(ctx) + opts, args, param_order = parser.parse_args(args=args) + + for param in iter_params_for_processing(param_order, self.get_params(ctx)): + value, args = param.handle_parse_result(ctx, opts, args) + + if args and not ctx.allow_extra_args and not ctx.resilient_parsing: + ctx.fail( + ngettext( + "Got unexpected extra argument ({args})", + "Got unexpected extra arguments ({args})", + len(args), + ).format(args=" ".join(map(str, args))) + ) + + ctx.args = args + ctx._opt_prefixes.update(parser._opt_prefixes) + return args + + def invoke(self, ctx: Context) -> t.Any: + """Given a context, this invokes the attached callback (if it exists) + in the right way. + """ + if self.deprecated: + extra_message = ( + f" {self.deprecated}" if isinstance(self.deprecated, str) else "" + ) + message = _( + "DeprecationWarning: The command {name!r} is deprecated.{extra_message}" + ).format(name=self.name, extra_message=extra_message) + echo(style(message, fg="red"), err=True) + + if self.callback is not None: + return ctx.invoke(self.callback, **ctx.params) + + def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: + """Return a list of completions for the incomplete value. Looks + at the names of options and chained multi-commands. + + Any command could be part of a chained multi-command, so sibling + commands are valid at any point during command completion. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + results: list[CompletionItem] = [] + + if incomplete and not incomplete[0].isalnum(): + for param in self.get_params(ctx): + if ( + not isinstance(param, Option) + or param.hidden + or ( + not param.multiple + and ctx.get_parameter_source(param.name) # type: ignore + is ParameterSource.COMMANDLINE + ) + ): + continue + + results.extend( + CompletionItem(name, help=param.help) + for name in [*param.opts, *param.secondary_opts] + if name.startswith(incomplete) + ) + + while ctx.parent is not None: + ctx = ctx.parent + + if isinstance(ctx.command, Group) and ctx.command.chain: + results.extend( + CompletionItem(name, help=command.get_short_help_str()) + for name, command in _complete_visible_commands(ctx, incomplete) + if name not in ctx._protected_args + ) + + return results + + @t.overload + def main( + self, + args: cabc.Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: t.Literal[True] = True, + **extra: t.Any, + ) -> t.NoReturn: ... + + @t.overload + def main( + self, + args: cabc.Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = ..., + **extra: t.Any, + ) -> t.Any: ... + + def main( + self, + args: cabc.Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + **extra: t.Any, + ) -> t.Any: + """This is the way to invoke a script with all the bells and + whistles as a command line application. This will always terminate + the application after a call. If this is not wanted, ``SystemExit`` + needs to be caught. + + This method is also available by directly calling the instance of + a :class:`Command`. + + :param args: the arguments that should be used for parsing. If not + provided, ``sys.argv[1:]`` is used. + :param prog_name: the program name that should be used. By default + the program name is constructed by taking the file + name from ``sys.argv[0]``. + :param complete_var: the environment variable that controls the + bash completion support. The default is + ``"__COMPLETE"`` with prog_name in + uppercase. + :param standalone_mode: the default behavior is to invoke the script + in standalone mode. Click will then + handle exceptions and convert them into + error messages and the function will never + return but shut down the interpreter. If + this is set to `False` they will be + propagated to the caller and the return + value of this function is the return value + of :meth:`invoke`. + :param windows_expand_args: Expand glob patterns, user dir, and + env vars in command line args on Windows. + :param extra: extra keyword arguments are forwarded to the context + constructor. See :class:`Context` for more information. + + .. versionchanged:: 8.0.1 + Added the ``windows_expand_args`` parameter to allow + disabling command line arg expansion on Windows. + + .. versionchanged:: 8.0 + When taking arguments from ``sys.argv`` on Windows, glob + patterns, user dir, and env vars are expanded. + + .. versionchanged:: 3.0 + Added the ``standalone_mode`` parameter. + """ + if args is None: + args = sys.argv[1:] + + if os.name == "nt" and windows_expand_args: + args = _expand_args(args) + else: + args = list(args) + + if prog_name is None: + prog_name = _detect_program_name() + + # Process shell completion requests and exit early. + self._main_shell_completion(extra, prog_name, complete_var) + + try: + try: + with self.make_context(prog_name, args, **extra) as ctx: + rv = self.invoke(ctx) + if not standalone_mode: + return rv + # it's not safe to `ctx.exit(rv)` here! + # note that `rv` may actually contain data like "1" which + # has obvious effects + # more subtle case: `rv=[None, None]` can come out of + # chained commands which all returned `None` -- so it's not + # even always obvious that `rv` indicates success/failure + # by its truthiness/falsiness + ctx.exit() + except (EOFError, KeyboardInterrupt) as e: + echo(file=sys.stderr) + raise Abort() from e + except ClickException as e: + if not standalone_mode: + raise + e.show() + sys.exit(e.exit_code) + except OSError as e: + if e.errno == errno.EPIPE: + sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout)) + sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr)) + sys.exit(1) + else: + raise + except Exit as e: + if standalone_mode: + sys.exit(e.exit_code) + else: + # in non-standalone mode, return the exit code + # note that this is only reached if `self.invoke` above raises + # an Exit explicitly -- thus bypassing the check there which + # would return its result + # the results of non-standalone execution may therefore be + # somewhat ambiguous: if there are codepaths which lead to + # `ctx.exit(1)` and to `return 1`, the caller won't be able to + # tell the difference between the two + return e.exit_code + except Abort: + if not standalone_mode: + raise + echo(_("Aborted!"), file=sys.stderr) + sys.exit(1) + + def _main_shell_completion( + self, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + complete_var: str | None = None, + ) -> None: + """Check if the shell is asking for tab completion, process + that, then exit early. Called from :meth:`main` before the + program is invoked. + + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. Defaults to + ``_{PROG_NAME}_COMPLETE``. + + .. versionchanged:: 8.2.0 + Dots (``.``) in ``prog_name`` are replaced with underscores (``_``). + """ + if complete_var is None: + complete_name = prog_name.replace("-", "_").replace(".", "_") + complete_var = f"_{complete_name}_COMPLETE".upper() + + instruction = os.environ.get(complete_var) + + if not instruction: + return + + from .shell_completion import shell_complete + + rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) + sys.exit(rv) + + def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any: + """Alias for :meth:`main`.""" + return self.main(*args, **kwargs) + + +class _FakeSubclassCheck(type): + def __subclasscheck__(cls, subclass: type) -> bool: + return issubclass(subclass, cls.__bases__[0]) + + def __instancecheck__(cls, instance: t.Any) -> bool: + return isinstance(instance, cls.__bases__[0]) + + +class _BaseCommand(Command, metaclass=_FakeSubclassCheck): + """ + .. deprecated:: 8.2 + Will be removed in Click 9.0. Use ``Command`` instead. + """ + + +class Group(Command): + """A group is a command that nests other commands (or more groups). + + :param name: The name of the group command. + :param commands: Map names to :class:`Command` objects. Can be a list, which + will use :attr:`Command.name` as the keys. + :param invoke_without_command: Invoke the group's callback even if a + subcommand is not given. + :param no_args_is_help: If no arguments are given, show the group's help and + exit. Defaults to the opposite of ``invoke_without_command``. + :param subcommand_metavar: How to represent the subcommand argument in help. + The default will represent whether ``chain`` is set or not. + :param chain: Allow passing more than one subcommand argument. After parsing + a command's arguments, if any arguments remain another command will be + matched, and so on. + :param result_callback: A function to call after the group's and + subcommand's callbacks. The value returned by the subcommand is passed. + If ``chain`` is enabled, the value will be a list of values returned by + all the commands. If ``invoke_without_command`` is enabled, the value + will be the value returned by the group's callback, or an empty list if + ``chain`` is enabled. + :param kwargs: Other arguments passed to :class:`Command`. + + .. versionchanged:: 8.0 + The ``commands`` argument can be a list of command objects. + + .. versionchanged:: 8.2 + Merged with and replaces the ``MultiCommand`` base class. + """ + + allow_extra_args = True + allow_interspersed_args = False + + #: If set, this is used by the group's :meth:`command` decorator + #: as the default :class:`Command` class. This is useful to make all + #: subcommands use a custom command class. + #: + #: .. versionadded:: 8.0 + command_class: type[Command] | None = None + + #: If set, this is used by the group's :meth:`group` decorator + #: as the default :class:`Group` class. This is useful to make all + #: subgroups use a custom group class. + #: + #: If set to the special value :class:`type` (literally + #: ``group_class = type``), this group's class will be used as the + #: default class. This makes a custom group class continue to make + #: custom groups. + #: + #: .. versionadded:: 8.0 + group_class: type[Group] | type[type] | None = None + # Literal[type] isn't valid, so use Type[type] + + def __init__( + self, + name: str | None = None, + commands: cabc.MutableMapping[str, Command] + | cabc.Sequence[Command] + | None = None, + invoke_without_command: bool = False, + no_args_is_help: bool | None = None, + subcommand_metavar: str | None = None, + chain: bool = False, + result_callback: t.Callable[..., t.Any] | None = None, + **kwargs: t.Any, + ) -> None: + super().__init__(name, **kwargs) + + if commands is None: + commands = {} + elif isinstance(commands, abc.Sequence): + commands = {c.name: c for c in commands if c.name is not None} + + #: The registered subcommands by their exported names. + self.commands: cabc.MutableMapping[str, Command] = commands + + if no_args_is_help is None: + no_args_is_help = not invoke_without_command + + self.no_args_is_help = no_args_is_help + self.invoke_without_command = invoke_without_command + + if subcommand_metavar is None: + if chain: + subcommand_metavar = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..." + else: + subcommand_metavar = "COMMAND [ARGS]..." + + self.subcommand_metavar = subcommand_metavar + self.chain = chain + # The result callback that is stored. This can be set or + # overridden with the :func:`result_callback` decorator. + self._result_callback = result_callback + + if self.chain: + for param in self.params: + if isinstance(param, Argument) and not param.required: + raise RuntimeError( + "A group in chain mode cannot have optional arguments." + ) + + def to_info_dict(self, ctx: Context) -> dict[str, t.Any]: + info_dict = super().to_info_dict(ctx) + commands = {} + + for name in self.list_commands(ctx): + command = self.get_command(ctx, name) + + if command is None: + continue + + sub_ctx = ctx._make_sub_context(command) + + with sub_ctx.scope(cleanup=False): + commands[name] = command.to_info_dict(sub_ctx) + + info_dict.update(commands=commands, chain=self.chain) + return info_dict + + def add_command(self, cmd: Command, name: str | None = None) -> None: + """Registers another :class:`Command` with this group. If the name + is not provided, the name of the command is used. + """ + name = name or cmd.name + if name is None: + raise TypeError("Command has no name.") + _check_nested_chain(self, name, cmd, register=True) + self.commands[name] = cmd + + @t.overload + def command(self, __func: t.Callable[..., t.Any]) -> Command: ... + + @t.overload + def command( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ... + + def command( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Command] | Command: + """A shortcut decorator for declaring and attaching a command to + the group. This takes the same arguments as :func:`command` and + immediately registers the created command with this group by + calling :meth:`add_command`. + + To customize the command class used, set the + :attr:`command_class` attribute. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + + .. versionchanged:: 8.0 + Added the :attr:`command_class` attribute. + """ + from .decorators import command + + func: t.Callable[..., t.Any] | None = None + + if args and callable(args[0]): + assert len(args) == 1 and not kwargs, ( + "Use 'command(**kwargs)(callable)' to provide arguments." + ) + (func,) = args + args = () + + if self.command_class and kwargs.get("cls") is None: + kwargs["cls"] = self.command_class + + def decorator(f: t.Callable[..., t.Any]) -> Command: + cmd: Command = command(*args, **kwargs)(f) + self.add_command(cmd) + return cmd + + if func is not None: + return decorator(func) + + return decorator + + @t.overload + def group(self, __func: t.Callable[..., t.Any]) -> Group: ... + + @t.overload + def group( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Group]: ... + + def group( + self, *args: t.Any, **kwargs: t.Any + ) -> t.Callable[[t.Callable[..., t.Any]], Group] | Group: + """A shortcut decorator for declaring and attaching a group to + the group. This takes the same arguments as :func:`group` and + immediately registers the created group with this group by + calling :meth:`add_command`. + + To customize the group class used, set the :attr:`group_class` + attribute. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + + .. versionchanged:: 8.0 + Added the :attr:`group_class` attribute. + """ + from .decorators import group + + func: t.Callable[..., t.Any] | None = None + + if args and callable(args[0]): + assert len(args) == 1 and not kwargs, ( + "Use 'group(**kwargs)(callable)' to provide arguments." + ) + (func,) = args + args = () + + if self.group_class is not None and kwargs.get("cls") is None: + if self.group_class is type: + kwargs["cls"] = type(self) + else: + kwargs["cls"] = self.group_class + + def decorator(f: t.Callable[..., t.Any]) -> Group: + cmd: Group = group(*args, **kwargs)(f) + self.add_command(cmd) + return cmd + + if func is not None: + return decorator(func) + + return decorator + + def result_callback(self, replace: bool = False) -> t.Callable[[F], F]: + """Adds a result callback to the command. By default if a + result callback is already registered this will chain them but + this can be disabled with the `replace` parameter. The result + callback is invoked with the return value of the subcommand + (or the list of return values from all subcommands if chaining + is enabled) as well as the parameters as they would be passed + to the main callback. + + Example:: + + @click.group() + @click.option('-i', '--input', default=23) + def cli(input): + return 42 + + @cli.result_callback() + def process_result(result, input): + return result + input + + :param replace: if set to `True` an already existing result + callback will be removed. + + .. versionchanged:: 8.0 + Renamed from ``resultcallback``. + + .. versionadded:: 3.0 + """ + + def decorator(f: F) -> F: + old_callback = self._result_callback + + if old_callback is None or replace: + self._result_callback = f + return f + + def function(value: t.Any, /, *args: t.Any, **kwargs: t.Any) -> t.Any: + inner = old_callback(value, *args, **kwargs) + return f(inner, *args, **kwargs) + + self._result_callback = rv = update_wrapper(t.cast(F, function), f) + return rv # type: ignore[return-value] + + return decorator + + def get_command(self, ctx: Context, cmd_name: str) -> Command | None: + """Given a context and a command name, this returns a :class:`Command` + object if it exists or returns ``None``. + """ + return self.commands.get(cmd_name) + + def list_commands(self, ctx: Context) -> list[str]: + """Returns a list of subcommand names in the order they should appear.""" + return sorted(self.commands) + + def collect_usage_pieces(self, ctx: Context) -> list[str]: + rv = super().collect_usage_pieces(ctx) + rv.append(self.subcommand_metavar) + return rv + + def format_options(self, ctx: Context, formatter: HelpFormatter) -> None: + super().format_options(ctx, formatter) + self.format_commands(ctx, formatter) + + def format_commands(self, ctx: Context, formatter: HelpFormatter) -> None: + """Extra format methods for multi methods that adds all the commands + after the options. + """ + commands = [] + for subcommand in self.list_commands(ctx): + cmd = self.get_command(ctx, subcommand) + # What is this, the tool lied about a command. Ignore it + if cmd is None: + continue + if cmd.hidden: + continue + + commands.append((subcommand, cmd)) + + # allow for 3 times the default spacing + if len(commands): + limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) + + rows = [] + for subcommand, cmd in commands: + help = cmd.get_short_help_str(limit) + rows.append((subcommand, help)) + + if rows: + with formatter.section(_("Commands")): + formatter.write_dl(rows) + + def parse_args(self, ctx: Context, args: list[str]) -> list[str]: + if not args and self.no_args_is_help and not ctx.resilient_parsing: + raise NoArgsIsHelpError(ctx) + + rest = super().parse_args(ctx, args) + + if self.chain: + ctx._protected_args = rest + ctx.args = [] + elif rest: + ctx._protected_args, ctx.args = rest[:1], rest[1:] + + return ctx.args + + def invoke(self, ctx: Context) -> t.Any: + def _process_result(value: t.Any) -> t.Any: + if self._result_callback is not None: + value = ctx.invoke(self._result_callback, value, **ctx.params) + return value + + if not ctx._protected_args: + if self.invoke_without_command: + # No subcommand was invoked, so the result callback is + # invoked with the group return value for regular + # groups, or an empty list for chained groups. + with ctx: + rv = super().invoke(ctx) + return _process_result([] if self.chain else rv) + ctx.fail(_("Missing command.")) + + # Fetch args back out + args = [*ctx._protected_args, *ctx.args] + ctx.args = [] + ctx._protected_args = [] + + # If we're not in chain mode, we only allow the invocation of a + # single command but we also inform the current context about the + # name of the command to invoke. + if not self.chain: + # Make sure the context is entered so we do not clean up + # resources until the result processor has worked. + with ctx: + cmd_name, cmd, args = self.resolve_command(ctx, args) + assert cmd is not None + ctx.invoked_subcommand = cmd_name + super().invoke(ctx) + sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) + with sub_ctx: + return _process_result(sub_ctx.command.invoke(sub_ctx)) + + # In chain mode we create the contexts step by step, but after the + # base command has been invoked. Because at that point we do not + # know the subcommands yet, the invoked subcommand attribute is + # set to ``*`` to inform the command that subcommands are executed + # but nothing else. + with ctx: + ctx.invoked_subcommand = "*" if args else None + super().invoke(ctx) + + # Otherwise we make every single context and invoke them in a + # chain. In that case the return value to the result processor + # is the list of all invoked subcommand's results. + contexts = [] + while args: + cmd_name, cmd, args = self.resolve_command(ctx, args) + assert cmd is not None + sub_ctx = cmd.make_context( + cmd_name, + args, + parent=ctx, + allow_extra_args=True, + allow_interspersed_args=False, + ) + contexts.append(sub_ctx) + args, sub_ctx.args = sub_ctx.args, [] + + rv = [] + for sub_ctx in contexts: + with sub_ctx: + rv.append(sub_ctx.command.invoke(sub_ctx)) + return _process_result(rv) + + def resolve_command( + self, ctx: Context, args: list[str] + ) -> tuple[str | None, Command | None, list[str]]: + cmd_name = make_str(args[0]) + original_cmd_name = cmd_name + + # Get the command + cmd = self.get_command(ctx, cmd_name) + + # If we can't find the command but there is a normalization + # function available, we try with that one. + if cmd is None and ctx.token_normalize_func is not None: + cmd_name = ctx.token_normalize_func(cmd_name) + cmd = self.get_command(ctx, cmd_name) + + # If we don't find the command we want to show an error message + # to the user that it was not provided. However, there is + # something else we should do: if the first argument looks like + # an option we want to kick off parsing again for arguments to + # resolve things like --help which now should go to the main + # place. + if cmd is None and not ctx.resilient_parsing: + if _split_opt(cmd_name)[0]: + self.parse_args(ctx, args) + ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name)) + return cmd_name if cmd else None, cmd, args[1:] + + def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: + """Return a list of completions for the incomplete value. Looks + at the names of options, subcommands, and chained + multi-commands. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + results = [ + CompletionItem(name, help=command.get_short_help_str()) + for name, command in _complete_visible_commands(ctx, incomplete) + ] + results.extend(super().shell_complete(ctx, incomplete)) + return results + + +class _MultiCommand(Group, metaclass=_FakeSubclassCheck): + """ + .. deprecated:: 8.2 + Will be removed in Click 9.0. Use ``Group`` instead. + """ + + +class CommandCollection(Group): + """A :class:`Group` that looks up subcommands on other groups. If a command + is not found on this group, each registered source is checked in order. + Parameters on a source are not added to this group, and a source's callback + is not invoked when invoking its commands. In other words, this "flattens" + commands in many groups into this one group. + + :param name: The name of the group command. + :param sources: A list of :class:`Group` objects to look up commands from. + :param kwargs: Other arguments passed to :class:`Group`. + + .. versionchanged:: 8.2 + This is a subclass of ``Group``. Commands are looked up first on this + group, then each of its sources. + """ + + def __init__( + self, + name: str | None = None, + sources: list[Group] | None = None, + **kwargs: t.Any, + ) -> None: + super().__init__(name, **kwargs) + #: The list of registered groups. + self.sources: list[Group] = sources or [] + + def add_source(self, group: Group) -> None: + """Add a group as a source of commands.""" + self.sources.append(group) + + def get_command(self, ctx: Context, cmd_name: str) -> Command | None: + rv = super().get_command(ctx, cmd_name) + + if rv is not None: + return rv + + for source in self.sources: + rv = source.get_command(ctx, cmd_name) + + if rv is not None: + if self.chain: + _check_nested_chain(self, cmd_name, rv) + + return rv + + return None + + def list_commands(self, ctx: Context) -> list[str]: + rv: set[str] = set(super().list_commands(ctx)) + + for source in self.sources: + rv.update(source.list_commands(ctx)) + + return sorted(rv) + + +def _check_iter(value: t.Any) -> cabc.Iterator[t.Any]: + """Check if the value is iterable but not a string. Raises a type + error, or return an iterator over the value. + """ + if isinstance(value, str): + raise TypeError + + return iter(value) + + +class Parameter: + r"""A parameter to a command comes in two versions: they are either + :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently + not supported by design as some of the internals for parsing are + intentionally not finalized. + + Some settings are supported by both options and arguments. + + :param param_decls: the parameter declarations for this option or + argument. This is a list of flags or argument + names. + :param type: the type that should be used. Either a :class:`ParamType` + or a Python type. The latter is converted into the former + automatically if supported. + :param required: controls if this is optional or not. + :param default: the default value if omitted. This can also be a callable, + in which case it's invoked when the default is needed + without any arguments. + :param callback: A function to further process or validate the value + after type conversion. It is called as ``f(ctx, param, value)`` + and must return the value. It is called for all sources, + including prompts. + :param nargs: the number of arguments to match. If not ``1`` the return + value is a tuple instead of single value. The default for + nargs is ``1`` (except if the type is a tuple, then it's + the arity of the tuple). If ``nargs=-1``, all remaining + parameters are collected. + :param metavar: how the value is represented in the help page. + :param expose_value: if this is `True` then the value is passed onwards + to the command callback and stored on the context, + otherwise it's skipped. + :param is_eager: eager values are processed before non eager ones. This + should not be set for arguments or it will inverse the + order of processing. + :param envvar: a string or list of strings that are environment variables + that should be checked. + :param shell_complete: A function that returns custom shell + completions. Used instead of the param's type completion if + given. Takes ``ctx, param, incomplete`` and must return a list + of :class:`~click.shell_completion.CompletionItem` or a list of + strings. + :param deprecated: If ``True`` or non-empty string, issues a message + indicating that the argument is deprecated and highlights + its deprecation in --help. The message can be customized + by using a string as the value. A deprecated parameter + cannot be required, a ValueError will be raised otherwise. + + .. versionchanged:: 8.2.0 + Introduction of ``deprecated``. + + .. versionchanged:: 8.2 + Adding duplicate parameter names to a :class:`~click.core.Command` will + result in a ``UserWarning`` being shown. + + .. versionchanged:: 8.2 + Adding duplicate parameter names to a :class:`~click.core.Command` will + result in a ``UserWarning`` being shown. + + .. versionchanged:: 8.0 + ``process_value`` validates required parameters and bounded + ``nargs``, and invokes the parameter callback before returning + the value. This allows the callback to validate prompts. + ``full_process_value`` is removed. + + .. versionchanged:: 8.0 + ``autocompletion`` is renamed to ``shell_complete`` and has new + semantics described above. The old name is deprecated and will + be removed in 8.1, until then it will be wrapped to match the + new requirements. + + .. versionchanged:: 8.0 + For ``multiple=True, nargs>1``, the default must be a list of + tuples. + + .. versionchanged:: 8.0 + Setting a default is no longer required for ``nargs>1``, it will + default to ``None``. ``multiple=True`` or ``nargs=-1`` will + default to ``()``. + + .. versionchanged:: 7.1 + Empty environment variables are ignored rather than taking the + empty string value. This makes it possible for scripts to clear + variables if they can't unset them. + + .. versionchanged:: 2.0 + Changed signature for parameter callback to also be passed the + parameter. The old callback format will still work, but it will + raise a warning to give you a chance to migrate the code easier. + """ + + param_type_name = "parameter" + + def __init__( + self, + param_decls: cabc.Sequence[str] | None = None, + type: types.ParamType | t.Any | None = None, + required: bool = False, + default: t.Any | t.Callable[[], t.Any] | None = None, + callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None, + nargs: int | None = None, + multiple: bool = False, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | cabc.Sequence[str] | None = None, + shell_complete: t.Callable[ + [Context, Parameter, str], list[CompletionItem] | list[str] + ] + | None = None, + deprecated: bool | str = False, + ) -> None: + self.name: str | None + self.opts: list[str] + self.secondary_opts: list[str] + self.name, self.opts, self.secondary_opts = self._parse_decls( + param_decls or (), expose_value + ) + self.type: types.ParamType = types.convert_type(type, default) + + # Default nargs to what the type tells us if we have that + # information available. + if nargs is None: + if self.type.is_composite: + nargs = self.type.arity + else: + nargs = 1 + + self.required = required + self.callback = callback + self.nargs = nargs + self.multiple = multiple + self.expose_value = expose_value + self.default = default + self.is_eager = is_eager + self.metavar = metavar + self.envvar = envvar + self._custom_shell_complete = shell_complete + self.deprecated = deprecated + + if __debug__: + if self.type.is_composite and nargs != self.type.arity: + raise ValueError( + f"'nargs' must be {self.type.arity} (or None) for" + f" type {self.type!r}, but it was {nargs}." + ) + + # Skip no default or callable default. + check_default = default if not callable(default) else None + + if check_default is not None: + if multiple: + try: + # Only check the first value against nargs. + check_default = next(_check_iter(check_default), None) + except TypeError: + raise ValueError( + "'default' must be a list when 'multiple' is true." + ) from None + + # Can be None for multiple with empty default. + if nargs != 1 and check_default is not None: + try: + _check_iter(check_default) + except TypeError: + if multiple: + message = ( + "'default' must be a list of lists when 'multiple' is" + " true and 'nargs' != 1." + ) + else: + message = "'default' must be a list when 'nargs' != 1." + + raise ValueError(message) from None + + if nargs > 1 and len(check_default) != nargs: + subject = "item length" if multiple else "length" + raise ValueError( + f"'default' {subject} must match nargs={nargs}." + ) + + if required and deprecated: + raise ValueError( + f"The {self.param_type_name} '{self.human_readable_name}' " + "is deprecated and still required. A deprecated " + f"{self.param_type_name} cannot be required." + ) + + def to_info_dict(self) -> dict[str, t.Any]: + """Gather information that could be useful for a tool generating + user-facing documentation. + + Use :meth:`click.Context.to_info_dict` to traverse the entire + CLI structure. + + .. versionadded:: 8.0 + """ + return { + "name": self.name, + "param_type_name": self.param_type_name, + "opts": self.opts, + "secondary_opts": self.secondary_opts, + "type": self.type.to_info_dict(), + "required": self.required, + "nargs": self.nargs, + "multiple": self.multiple, + "default": self.default, + "envvar": self.envvar, + } + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} {self.name}>" + + def _parse_decls( + self, decls: cabc.Sequence[str], expose_value: bool + ) -> tuple[str | None, list[str], list[str]]: + raise NotImplementedError() + + @property + def human_readable_name(self) -> str: + """Returns the human readable name of this parameter. This is the + same as the name for options, but the metavar for arguments. + """ + return self.name # type: ignore + + def make_metavar(self, ctx: Context) -> str: + if self.metavar is not None: + return self.metavar + + metavar = self.type.get_metavar(param=self, ctx=ctx) + + if metavar is None: + metavar = self.type.name.upper() + + if self.nargs != 1: + metavar += "..." + + return metavar + + @t.overload + def get_default( + self, ctx: Context, call: t.Literal[True] = True + ) -> t.Any | None: ... + + @t.overload + def get_default( + self, ctx: Context, call: bool = ... + ) -> t.Any | t.Callable[[], t.Any] | None: ... + + def get_default( + self, ctx: Context, call: bool = True + ) -> t.Any | t.Callable[[], t.Any] | None: + """Get the default for the parameter. Tries + :meth:`Context.lookup_default` first, then the local default. + + :param ctx: Current context. + :param call: If the default is a callable, call it. Disable to + return the callable instead. + + .. versionchanged:: 8.0.2 + Type casting is no longer performed when getting a default. + + .. versionchanged:: 8.0.1 + Type casting can fail in resilient parsing mode. Invalid + defaults will not prevent showing help text. + + .. versionchanged:: 8.0 + Looks at ``ctx.default_map`` first. + + .. versionchanged:: 8.0 + Added the ``call`` parameter. + """ + value = ctx.lookup_default(self.name, call=False) # type: ignore + + if value is None: + value = self.default + + if call and callable(value): + value = value() + + return value + + def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: + raise NotImplementedError() + + def consume_value( + self, ctx: Context, opts: cabc.Mapping[str, t.Any] + ) -> tuple[t.Any, ParameterSource]: + value = opts.get(self.name) # type: ignore + source = ParameterSource.COMMANDLINE + + if value is None: + value = self.value_from_envvar(ctx) + source = ParameterSource.ENVIRONMENT + + if value is None: + value = ctx.lookup_default(self.name) # type: ignore + source = ParameterSource.DEFAULT_MAP + + if value is None: + value = self.get_default(ctx) + source = ParameterSource.DEFAULT + + return value, source + + def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any: + """Convert and validate a value against the option's + :attr:`type`, :attr:`multiple`, and :attr:`nargs`. + """ + if value is None: + return () if self.multiple or self.nargs == -1 else None + + def check_iter(value: t.Any) -> cabc.Iterator[t.Any]: + try: + return _check_iter(value) + except TypeError: + # This should only happen when passing in args manually, + # the parser should construct an iterable when parsing + # the command line. + raise BadParameter( + _("Value must be an iterable."), ctx=ctx, param=self + ) from None + + if self.nargs == 1 or self.type.is_composite: + + def convert(value: t.Any) -> t.Any: + return self.type(value, param=self, ctx=ctx) + + elif self.nargs == -1: + + def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] + return tuple(self.type(x, self, ctx) for x in check_iter(value)) + + else: # nargs > 1 + + def convert(value: t.Any) -> t.Any: # tuple[t.Any, ...] + value = tuple(check_iter(value)) + + if len(value) != self.nargs: + raise BadParameter( + ngettext( + "Takes {nargs} values but 1 was given.", + "Takes {nargs} values but {len} were given.", + len(value), + ).format(nargs=self.nargs, len=len(value)), + ctx=ctx, + param=self, + ) + + return tuple(self.type(x, self, ctx) for x in value) + + if self.multiple: + return tuple(convert(x) for x in check_iter(value)) + + return convert(value) + + def value_is_missing(self, value: t.Any) -> bool: + if value is None: + return True + + if (self.nargs != 1 or self.multiple) and value == (): + return True + + return False + + def process_value(self, ctx: Context, value: t.Any) -> t.Any: + value = self.type_cast_value(ctx, value) + + if self.required and self.value_is_missing(value): + raise MissingParameter(ctx=ctx, param=self) + + if self.callback is not None: + value = self.callback(ctx, self, value) + + return value + + def resolve_envvar_value(self, ctx: Context) -> str | None: + if self.envvar is None: + return None + + if isinstance(self.envvar, str): + rv = os.environ.get(self.envvar) + + if rv: + return rv + else: + for envvar in self.envvar: + rv = os.environ.get(envvar) + + if rv: + return rv + + return None + + def value_from_envvar(self, ctx: Context) -> t.Any | None: + rv: t.Any | None = self.resolve_envvar_value(ctx) + + if rv is not None and self.nargs != 1: + rv = self.type.split_envvar_value(rv) + + return rv + + def handle_parse_result( + self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str] + ) -> tuple[t.Any, list[str]]: + with augment_usage_errors(ctx, param=self): + value, source = self.consume_value(ctx, opts) + + if ( + self.deprecated + and value is not None + and source + not in ( + ParameterSource.DEFAULT, + ParameterSource.DEFAULT_MAP, + ) + ): + extra_message = ( + f" {self.deprecated}" if isinstance(self.deprecated, str) else "" + ) + message = _( + "DeprecationWarning: The {param_type} {name!r} is deprecated." + "{extra_message}" + ).format( + param_type=self.param_type_name, + name=self.human_readable_name, + extra_message=extra_message, + ) + echo(style(message, fg="red"), err=True) + + ctx.set_parameter_source(self.name, source) # type: ignore + + try: + value = self.process_value(ctx, value) + except Exception: + if not ctx.resilient_parsing: + raise + + value = None + + if self.expose_value: + ctx.params[self.name] = value # type: ignore + + return value, args + + def get_help_record(self, ctx: Context) -> tuple[str, str] | None: + pass + + def get_usage_pieces(self, ctx: Context) -> list[str]: + return [] + + def get_error_hint(self, ctx: Context) -> str: + """Get a stringified version of the param for use in error messages to + indicate which param caused the error. + """ + hint_list = self.opts or [self.human_readable_name] + return " / ".join(f"'{x}'" for x in hint_list) + + def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]: + """Return a list of completions for the incomplete value. If a + ``shell_complete`` function was given during init, it is used. + Otherwise, the :attr:`type` + :meth:`~click.types.ParamType.shell_complete` function is used. + + :param ctx: Invocation context for this command. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + if self._custom_shell_complete is not None: + results = self._custom_shell_complete(ctx, self, incomplete) + + if results and isinstance(results[0], str): + from click.shell_completion import CompletionItem + + results = [CompletionItem(c) for c in results] + + return t.cast("list[CompletionItem]", results) + + return self.type.shell_complete(ctx, self, incomplete) + + +class Option(Parameter): + """Options are usually optional values on the command line and + have some extra features that arguments don't have. + + All other parameters are passed onwards to the parameter constructor. + + :param show_default: Show the default value for this option in its + help text. Values are not shown by default, unless + :attr:`Context.show_default` is ``True``. If this value is a + string, it shows that string in parentheses instead of the + actual value. This is particularly useful for dynamic options. + For single option boolean flags, the default remains hidden if + its value is ``False``. + :param show_envvar: Controls if an environment variable should be + shown on the help page and error messages. + Normally, environment variables are not shown. + :param prompt: If set to ``True`` or a non empty string then the + user will be prompted for input. If set to ``True`` the prompt + will be the option name capitalized. A deprecated option cannot be + prompted. + :param confirmation_prompt: Prompt a second time to confirm the + value if it was prompted for. Can be set to a string instead of + ``True`` to customize the message. + :param prompt_required: If set to ``False``, the user will be + prompted for input only when the option was specified as a flag + without a value. + :param hide_input: If this is ``True`` then the input on the prompt + will be hidden from the user. This is useful for password input. + :param is_flag: forces this option to act as a flag. The default is + auto detection. + :param flag_value: which value should be used for this flag if it's + enabled. This is set to a boolean automatically if + the option string contains a slash to mark two options. + :param multiple: if this is set to `True` then the argument is accepted + multiple times and recorded. This is similar to ``nargs`` + in how it works but supports arbitrary number of + arguments. + :param count: this flag makes an option increment an integer. + :param allow_from_autoenv: if this is enabled then the value of this + parameter will be pulled from an environment + variable in case a prefix is defined on the + context. + :param help: the help string. + :param hidden: hide this option from help outputs. + :param attrs: Other command arguments described in :class:`Parameter`. + + .. versionchanged:: 8.2 + ``envvar`` used with ``flag_value`` will always use the ``flag_value``, + previously it would use the value of the environment variable. + + .. versionchanged:: 8.1 + Help text indentation is cleaned here instead of only in the + ``@option`` decorator. + + .. versionchanged:: 8.1 + The ``show_default`` parameter overrides + ``Context.show_default``. + + .. versionchanged:: 8.1 + The default of a single option boolean flag is not shown if the + default value is ``False``. + + .. versionchanged:: 8.0.1 + ``type`` is detected from ``flag_value`` if given. + """ + + param_type_name = "option" + + def __init__( + self, + param_decls: cabc.Sequence[str] | None = None, + show_default: bool | str | None = None, + prompt: bool | str = False, + confirmation_prompt: bool | str = False, + prompt_required: bool = True, + hide_input: bool = False, + is_flag: bool | None = None, + flag_value: t.Any | None = None, + multiple: bool = False, + count: bool = False, + allow_from_autoenv: bool = True, + type: types.ParamType | t.Any | None = None, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = False, + deprecated: bool | str = False, + **attrs: t.Any, + ) -> None: + if help: + help = inspect.cleandoc(help) + + default_is_missing = "default" not in attrs + super().__init__( + param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs + ) + + if prompt is True: + if self.name is None: + raise TypeError("'name' is required with 'prompt=True'.") + + prompt_text: str | None = self.name.replace("_", " ").capitalize() + elif prompt is False: + prompt_text = None + else: + prompt_text = prompt + + if deprecated: + deprecated_message = ( + f"(DEPRECATED: {deprecated})" + if isinstance(deprecated, str) + else "(DEPRECATED)" + ) + help = help + deprecated_message if help is not None else deprecated_message + + self.prompt = prompt_text + self.confirmation_prompt = confirmation_prompt + self.prompt_required = prompt_required + self.hide_input = hide_input + self.hidden = hidden + + # If prompt is enabled but not required, then the option can be + # used as a flag to indicate using prompt or flag_value. + self._flag_needs_value = self.prompt is not None and not self.prompt_required + + if is_flag is None: + if flag_value is not None: + # Implicitly a flag because flag_value was set. + is_flag = True + elif self._flag_needs_value: + # Not a flag, but when used as a flag it shows a prompt. + is_flag = False + else: + # Implicitly a flag because flag options were given. + is_flag = bool(self.secondary_opts) + elif is_flag is False and not self._flag_needs_value: + # Not a flag, and prompt is not enabled, can be used as a + # flag if flag_value is set. + self._flag_needs_value = flag_value is not None + + self.default: t.Any | t.Callable[[], t.Any] + + if is_flag and default_is_missing and not self.required: + if multiple: + self.default = () + else: + self.default = False + + if is_flag and flag_value is None: + flag_value = not self.default + + self.type: types.ParamType + if is_flag and type is None: + # Re-guess the type from the flag value instead of the + # default. + self.type = types.convert_type(None, flag_value) + + self.is_flag: bool = is_flag + self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType) + self.flag_value: t.Any = flag_value + + # Counting + self.count = count + if count: + if type is None: + self.type = types.IntRange(min=0) + if default_is_missing: + self.default = 0 + + self.allow_from_autoenv = allow_from_autoenv + self.help = help + self.show_default = show_default + self.show_choices = show_choices + self.show_envvar = show_envvar + + if __debug__: + if deprecated and prompt: + raise ValueError("`deprecated` options cannot use `prompt`.") + + if self.nargs == -1: + raise TypeError("nargs=-1 is not supported for options.") + + if self.prompt and self.is_flag and not self.is_bool_flag: + raise TypeError("'prompt' is not valid for non-boolean flag.") + + if not self.is_bool_flag and self.secondary_opts: + raise TypeError("Secondary flag is not valid for non-boolean flag.") + + if self.is_bool_flag and self.hide_input and self.prompt is not None: + raise TypeError( + "'prompt' with 'hide_input' is not valid for boolean flag." + ) + + if self.count: + if self.multiple: + raise TypeError("'count' is not valid with 'multiple'.") + + if self.is_flag: + raise TypeError("'count' is not valid with 'is_flag'.") + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict.update( + help=self.help, + prompt=self.prompt, + is_flag=self.is_flag, + flag_value=self.flag_value, + count=self.count, + hidden=self.hidden, + ) + return info_dict + + def get_error_hint(self, ctx: Context) -> str: + result = super().get_error_hint(ctx) + if self.show_envvar: + result += f" (env var: '{self.envvar}')" + return result + + def _parse_decls( + self, decls: cabc.Sequence[str], expose_value: bool + ) -> tuple[str | None, list[str], list[str]]: + opts = [] + secondary_opts = [] + name = None + possible_names = [] + + for decl in decls: + if decl.isidentifier(): + if name is not None: + raise TypeError(f"Name '{name}' defined twice") + name = decl + else: + split_char = ";" if decl[:1] == "/" else "/" + if split_char in decl: + first, second = decl.split(split_char, 1) + first = first.rstrip() + if first: + possible_names.append(_split_opt(first)) + opts.append(first) + second = second.lstrip() + if second: + secondary_opts.append(second.lstrip()) + if first == second: + raise ValueError( + f"Boolean option {decl!r} cannot use the" + " same flag for true/false." + ) + else: + possible_names.append(_split_opt(decl)) + opts.append(decl) + + if name is None and possible_names: + possible_names.sort(key=lambda x: -len(x[0])) # group long options first + name = possible_names[0][1].replace("-", "_").lower() + if not name.isidentifier(): + name = None + + if name is None: + if not expose_value: + return None, opts, secondary_opts + raise TypeError( + f"Could not determine name for option with declarations {decls!r}" + ) + + if not opts and not secondary_opts: + raise TypeError( + f"No options defined but a name was passed ({name})." + " Did you mean to declare an argument instead? Did" + f" you mean to pass '--{name}'?" + ) + + return name, opts, secondary_opts + + def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: + if self.multiple: + action = "append" + elif self.count: + action = "count" + else: + action = "store" + + if self.is_flag: + action = f"{action}_const" + + if self.is_bool_flag and self.secondary_opts: + parser.add_option( + obj=self, opts=self.opts, dest=self.name, action=action, const=True + ) + parser.add_option( + obj=self, + opts=self.secondary_opts, + dest=self.name, + action=action, + const=False, + ) + else: + parser.add_option( + obj=self, + opts=self.opts, + dest=self.name, + action=action, + const=self.flag_value, + ) + else: + parser.add_option( + obj=self, + opts=self.opts, + dest=self.name, + action=action, + nargs=self.nargs, + ) + + def get_help_record(self, ctx: Context) -> tuple[str, str] | None: + if self.hidden: + return None + + any_prefix_is_slash = False + + def _write_opts(opts: cabc.Sequence[str]) -> str: + nonlocal any_prefix_is_slash + + rv, any_slashes = join_options(opts) + + if any_slashes: + any_prefix_is_slash = True + + if not self.is_flag and not self.count: + rv += f" {self.make_metavar(ctx=ctx)}" + + return rv + + rv = [_write_opts(self.opts)] + + if self.secondary_opts: + rv.append(_write_opts(self.secondary_opts)) + + help = self.help or "" + + extra = self.get_help_extra(ctx) + extra_items = [] + if "envvars" in extra: + extra_items.append( + _("env var: {var}").format(var=", ".join(extra["envvars"])) + ) + if "default" in extra: + extra_items.append(_("default: {default}").format(default=extra["default"])) + if "range" in extra: + extra_items.append(extra["range"]) + if "required" in extra: + extra_items.append(_(extra["required"])) + + if extra_items: + extra_str = "; ".join(extra_items) + help = f"{help} [{extra_str}]" if help else f"[{extra_str}]" + + return ("; " if any_prefix_is_slash else " / ").join(rv), help + + def get_help_extra(self, ctx: Context) -> types.OptionHelpExtra: + extra: types.OptionHelpExtra = {} + + if self.show_envvar: + envvar = self.envvar + + if envvar is None: + if ( + self.allow_from_autoenv + and ctx.auto_envvar_prefix is not None + and self.name is not None + ): + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" + + if envvar is not None: + if isinstance(envvar, str): + extra["envvars"] = (envvar,) + else: + extra["envvars"] = tuple(str(d) for d in envvar) + + # Temporarily enable resilient parsing to avoid type casting + # failing for the default. Might be possible to extend this to + # help formatting in general. + resilient = ctx.resilient_parsing + ctx.resilient_parsing = True + + try: + default_value = self.get_default(ctx, call=False) + finally: + ctx.resilient_parsing = resilient + + show_default = False + show_default_is_str = False + + if self.show_default is not None: + if isinstance(self.show_default, str): + show_default_is_str = show_default = True + else: + show_default = self.show_default + elif ctx.show_default is not None: + show_default = ctx.show_default + + if show_default_is_str or (show_default and (default_value is not None)): + if show_default_is_str: + default_string = f"({self.show_default})" + elif isinstance(default_value, (list, tuple)): + default_string = ", ".join(str(d) for d in default_value) + elif inspect.isfunction(default_value): + default_string = _("(dynamic)") + elif self.is_bool_flag and self.secondary_opts: + # For boolean flags that have distinct True/False opts, + # use the opt without prefix instead of the value. + default_string = _split_opt( + (self.opts if default_value else self.secondary_opts)[0] + )[1] + elif self.is_bool_flag and not self.secondary_opts and not default_value: + default_string = "" + elif default_value == "": + default_string = '""' + else: + default_string = str(default_value) + + if default_string: + extra["default"] = default_string + + if ( + isinstance(self.type, types._NumberRangeBase) + # skip count with default range type + and not (self.count and self.type.min == 0 and self.type.max is None) + ): + range_str = self.type._describe_range() + + if range_str: + extra["range"] = range_str + + if self.required: + extra["required"] = "required" + + return extra + + @t.overload + def get_default( + self, ctx: Context, call: t.Literal[True] = True + ) -> t.Any | None: ... + + @t.overload + def get_default( + self, ctx: Context, call: bool = ... + ) -> t.Any | t.Callable[[], t.Any] | None: ... + + def get_default( + self, ctx: Context, call: bool = True + ) -> t.Any | t.Callable[[], t.Any] | None: + # If we're a non boolean flag our default is more complex because + # we need to look at all flags in the same group to figure out + # if we're the default one in which case we return the flag + # value as default. + if self.is_flag and not self.is_bool_flag: + for param in ctx.command.params: + if param.name == self.name and param.default: + return t.cast(Option, param).flag_value + + return None + + return super().get_default(ctx, call=call) + + def prompt_for_value(self, ctx: Context) -> t.Any: + """This is an alternative flow that can be activated in the full + value processing if a value does not exist. It will prompt the + user until a valid value exists and then returns the processed + value as result. + """ + assert self.prompt is not None + + # Calculate the default before prompting anything to be stable. + default = self.get_default(ctx) + + # If this is a prompt for a flag we need to handle this + # differently. + if self.is_bool_flag: + return confirm(self.prompt, default) + + # If show_default is set to True/False, provide this to `prompt` as well. For + # non-bool values of `show_default`, we use `prompt`'s default behavior + prompt_kwargs: t.Any = {} + if isinstance(self.show_default, bool): + prompt_kwargs["show_default"] = self.show_default + + return prompt( + self.prompt, + default=default, + type=self.type, + hide_input=self.hide_input, + show_choices=self.show_choices, + confirmation_prompt=self.confirmation_prompt, + value_proc=lambda x: self.process_value(ctx, x), + **prompt_kwargs, + ) + + def resolve_envvar_value(self, ctx: Context) -> str | None: + rv = super().resolve_envvar_value(ctx) + + if rv is not None: + if self.is_flag and self.flag_value: + return str(self.flag_value) + return rv + + if ( + self.allow_from_autoenv + and ctx.auto_envvar_prefix is not None + and self.name is not None + ): + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" + rv = os.environ.get(envvar) + + if rv: + return rv + + return None + + def value_from_envvar(self, ctx: Context) -> t.Any | None: + rv: t.Any | None = self.resolve_envvar_value(ctx) + + if rv is None: + return None + + value_depth = (self.nargs != 1) + bool(self.multiple) + + if value_depth > 0: + rv = self.type.split_envvar_value(rv) + + if self.multiple and self.nargs != 1: + rv = batch(rv, self.nargs) + + return rv + + def consume_value( + self, ctx: Context, opts: cabc.Mapping[str, Parameter] + ) -> tuple[t.Any, ParameterSource]: + value, source = super().consume_value(ctx, opts) + + # The parser will emit a sentinel value if the option can be + # given as a flag without a value. This is different from None + # to distinguish from the flag not being given at all. + if value is _flag_needs_value: + if self.prompt is not None and not ctx.resilient_parsing: + value = self.prompt_for_value(ctx) + source = ParameterSource.PROMPT + else: + value = self.flag_value + source = ParameterSource.COMMANDLINE + + elif ( + self.multiple + and value is not None + and any(v is _flag_needs_value for v in value) + ): + value = [self.flag_value if v is _flag_needs_value else v for v in value] + source = ParameterSource.COMMANDLINE + + # The value wasn't set, or used the param's default, prompt if + # prompting is enabled. + elif ( + source in {None, ParameterSource.DEFAULT} + and self.prompt is not None + and (self.required or self.prompt_required) + and not ctx.resilient_parsing + ): + value = self.prompt_for_value(ctx) + source = ParameterSource.PROMPT + + return value, source + + +class Argument(Parameter): + """Arguments are positional parameters to a command. They generally + provide fewer features than options but can have infinite ``nargs`` + and are required by default. + + All parameters are passed onwards to the constructor of :class:`Parameter`. + """ + + param_type_name = "argument" + + def __init__( + self, + param_decls: cabc.Sequence[str], + required: bool | None = None, + **attrs: t.Any, + ) -> None: + if required is None: + if attrs.get("default") is not None: + required = False + else: + required = attrs.get("nargs", 1) > 0 + + if "multiple" in attrs: + raise TypeError("__init__() got an unexpected keyword argument 'multiple'.") + + super().__init__(param_decls, required=required, **attrs) + + if __debug__: + if self.default is not None and self.nargs == -1: + raise TypeError("'default' is not supported for nargs=-1.") + + @property + def human_readable_name(self) -> str: + if self.metavar is not None: + return self.metavar + return self.name.upper() # type: ignore + + def make_metavar(self, ctx: Context) -> str: + if self.metavar is not None: + return self.metavar + var = self.type.get_metavar(param=self, ctx=ctx) + if not var: + var = self.name.upper() # type: ignore + if self.deprecated: + var += "!" + if not self.required: + var = f"[{var}]" + if self.nargs != 1: + var += "..." + return var + + def _parse_decls( + self, decls: cabc.Sequence[str], expose_value: bool + ) -> tuple[str | None, list[str], list[str]]: + if not decls: + if not expose_value: + return None, [], [] + raise TypeError("Argument is marked as exposed, but does not have a name.") + if len(decls) == 1: + name = arg = decls[0] + name = name.replace("-", "_").lower() + else: + raise TypeError( + "Arguments take exactly one parameter declaration, got" + f" {len(decls)}: {decls}." + ) + return name, [arg], [] + + def get_usage_pieces(self, ctx: Context) -> list[str]: + return [self.make_metavar(ctx)] + + def get_error_hint(self, ctx: Context) -> str: + return f"'{self.make_metavar(ctx)}'" + + def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None: + parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) + + +def __getattr__(name: str) -> object: + import warnings + + if name == "BaseCommand": + warnings.warn( + "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Command' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _BaseCommand + + if name == "MultiCommand": + warnings.warn( + "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" + " 'Group' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _MultiCommand + + raise AttributeError(name) diff --git a/miniconda3/lib/python3.13/site-packages/click/decorators.py b/miniconda3/lib/python3.13/site-packages/click/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..21f4c342245fa93a7946b17d7661e0d2fa6a0c29 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/decorators.py @@ -0,0 +1,551 @@ +from __future__ import annotations + +import inspect +import typing as t +from functools import update_wrapper +from gettext import gettext as _ + +from .core import Argument +from .core import Command +from .core import Context +from .core import Group +from .core import Option +from .core import Parameter +from .globals import get_current_context +from .utils import echo + +if t.TYPE_CHECKING: + import typing_extensions as te + + P = te.ParamSpec("P") + +R = t.TypeVar("R") +T = t.TypeVar("T") +_AnyCallable = t.Callable[..., t.Any] +FC = t.TypeVar("FC", bound="_AnyCallable | Command") + + +def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]: + """Marks a callback as wanting to receive the current context + object as first argument. + """ + + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + return f(get_current_context(), *args, **kwargs) + + return update_wrapper(new_func, f) + + +def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: + """Similar to :func:`pass_context`, but only pass the object on the + context onwards (:attr:`Context.obj`). This is useful if that object + represents the state of a nested system. + """ + + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + return f(get_current_context().obj, *args, **kwargs) + + return update_wrapper(new_func, f) + + +def make_pass_decorator( + object_type: type[T], ensure: bool = False +) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: + """Given an object type this creates a decorator that will work + similar to :func:`pass_obj` but instead of passing the object of the + current context, it will find the innermost context of type + :func:`object_type`. + + This generates a decorator that works roughly like this:: + + from functools import update_wrapper + + def decorator(f): + @pass_context + def new_func(ctx, *args, **kwargs): + obj = ctx.find_object(object_type) + return ctx.invoke(f, obj, *args, **kwargs) + return update_wrapper(new_func, f) + return decorator + + :param object_type: the type of the object to pass. + :param ensure: if set to `True`, a new object will be created and + remembered on the context if it's not there yet. + """ + + def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + ctx = get_current_context() + + obj: T | None + if ensure: + obj = ctx.ensure_object(object_type) + else: + obj = ctx.find_object(object_type) + + if obj is None: + raise RuntimeError( + "Managed to invoke callback without a context" + f" object of type {object_type.__name__!r}" + " existing." + ) + + return ctx.invoke(f, obj, *args, **kwargs) + + return update_wrapper(new_func, f) + + return decorator + + +def pass_meta_key( + key: str, *, doc_description: str | None = None +) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: + """Create a decorator that passes a key from + :attr:`click.Context.meta` as the first argument to the decorated + function. + + :param key: Key in ``Context.meta`` to pass. + :param doc_description: Description of the object being passed, + inserted into the decorator's docstring. Defaults to "the 'key' + key from Context.meta". + + .. versionadded:: 8.0 + """ + + def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: + def new_func(*args: P.args, **kwargs: P.kwargs) -> R: + ctx = get_current_context() + obj = ctx.meta[key] + return ctx.invoke(f, obj, *args, **kwargs) + + return update_wrapper(new_func, f) + + if doc_description is None: + doc_description = f"the {key!r} key from :attr:`click.Context.meta`" + + decorator.__doc__ = ( + f"Decorator that passes {doc_description} as the first argument" + " to the decorated function." + ) + return decorator + + +CmdType = t.TypeVar("CmdType", bound=Command) + + +# variant: no call, directly as decorator for a function. +@t.overload +def command(name: _AnyCallable) -> Command: ... + + +# variant: with positional name and with positional or keyword cls argument: +# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...) +@t.overload +def command( + name: str | None, + cls: type[CmdType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], CmdType]: ... + + +# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...) +@t.overload +def command( + name: None = None, + *, + cls: type[CmdType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], CmdType]: ... + + +# variant: with optional string name, no cls argument provided. +@t.overload +def command( + name: str | None = ..., cls: None = None, **attrs: t.Any +) -> t.Callable[[_AnyCallable], Command]: ... + + +def command( + name: str | _AnyCallable | None = None, + cls: type[CmdType] | None = None, + **attrs: t.Any, +) -> Command | t.Callable[[_AnyCallable], Command | CmdType]: + r"""Creates a new :class:`Command` and uses the decorated function as + callback. This will also automatically attach all decorated + :func:`option`\s and :func:`argument`\s as parameters to the command. + + The name of the command defaults to the name of the function, converted to + lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes + ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example, + ``init_data_command`` becomes ``init-data``. + + All keyword arguments are forwarded to the underlying command class. + For the ``params`` argument, any decorated params are appended to + the end of the list. + + Once decorated the function turns into a :class:`Command` instance + that can be invoked as a command line utility or be attached to a + command :class:`Group`. + + :param name: The name of the command. Defaults to modifying the function's + name as described above. + :param cls: The command class to create. Defaults to :class:`Command`. + + .. versionchanged:: 8.2 + The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are + removed when generating the name. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + + .. versionchanged:: 8.1 + The ``params`` argument can be used. Decorated params are + appended to the end of the list. + """ + + func: t.Callable[[_AnyCallable], t.Any] | None = None + + if callable(name): + func = name + name = None + assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class." + assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments." + + if cls is None: + cls = t.cast("type[CmdType]", Command) + + def decorator(f: _AnyCallable) -> CmdType: + if isinstance(f, Command): + raise TypeError("Attempted to convert a callback into a command twice.") + + attr_params = attrs.pop("params", None) + params = attr_params if attr_params is not None else [] + + try: + decorator_params = f.__click_params__ # type: ignore + except AttributeError: + pass + else: + del f.__click_params__ # type: ignore + params.extend(reversed(decorator_params)) + + if attrs.get("help") is None: + attrs["help"] = f.__doc__ + + if t.TYPE_CHECKING: + assert cls is not None + assert not callable(name) + + if name is not None: + cmd_name = name + else: + cmd_name = f.__name__.lower().replace("_", "-") + cmd_left, sep, suffix = cmd_name.rpartition("-") + + if sep and suffix in {"command", "cmd", "group", "grp"}: + cmd_name = cmd_left + + cmd = cls(name=cmd_name, callback=f, params=params, **attrs) + cmd.__doc__ = f.__doc__ + return cmd + + if func is not None: + return decorator(func) + + return decorator + + +GrpType = t.TypeVar("GrpType", bound=Group) + + +# variant: no call, directly as decorator for a function. +@t.overload +def group(name: _AnyCallable) -> Group: ... + + +# variant: with positional name and with positional or keyword cls argument: +# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...) +@t.overload +def group( + name: str | None, + cls: type[GrpType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], GrpType]: ... + + +# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...) +@t.overload +def group( + name: None = None, + *, + cls: type[GrpType], + **attrs: t.Any, +) -> t.Callable[[_AnyCallable], GrpType]: ... + + +# variant: with optional string name, no cls argument provided. +@t.overload +def group( + name: str | None = ..., cls: None = None, **attrs: t.Any +) -> t.Callable[[_AnyCallable], Group]: ... + + +def group( + name: str | _AnyCallable | None = None, + cls: type[GrpType] | None = None, + **attrs: t.Any, +) -> Group | t.Callable[[_AnyCallable], Group | GrpType]: + """Creates a new :class:`Group` with a function as callback. This + works otherwise the same as :func:`command` just that the `cls` + parameter is set to :class:`Group`. + + .. versionchanged:: 8.1 + This decorator can be applied without parentheses. + """ + if cls is None: + cls = t.cast("type[GrpType]", Group) + + if callable(name): + return command(cls=cls, **attrs)(name) + + return command(name, cls, **attrs) + + +def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None: + if isinstance(f, Command): + f.params.append(param) + else: + if not hasattr(f, "__click_params__"): + f.__click_params__ = [] # type: ignore + + f.__click_params__.append(param) # type: ignore + + +def argument( + *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any +) -> t.Callable[[FC], FC]: + """Attaches an argument to the command. All positional arguments are + passed as parameter declarations to :class:`Argument`; all keyword + arguments are forwarded unchanged (except ``cls``). + This is equivalent to creating an :class:`Argument` instance manually + and attaching it to the :attr:`Command.params` list. + + For the default argument class, refer to :class:`Argument` and + :class:`Parameter` for descriptions of parameters. + + :param cls: the argument class to instantiate. This defaults to + :class:`Argument`. + :param param_decls: Passed as positional arguments to the constructor of + ``cls``. + :param attrs: Passed as keyword arguments to the constructor of ``cls``. + """ + if cls is None: + cls = Argument + + def decorator(f: FC) -> FC: + _param_memo(f, cls(param_decls, **attrs)) + return f + + return decorator + + +def option( + *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any +) -> t.Callable[[FC], FC]: + """Attaches an option to the command. All positional arguments are + passed as parameter declarations to :class:`Option`; all keyword + arguments are forwarded unchanged (except ``cls``). + This is equivalent to creating an :class:`Option` instance manually + and attaching it to the :attr:`Command.params` list. + + For the default option class, refer to :class:`Option` and + :class:`Parameter` for descriptions of parameters. + + :param cls: the option class to instantiate. This defaults to + :class:`Option`. + :param param_decls: Passed as positional arguments to the constructor of + ``cls``. + :param attrs: Passed as keyword arguments to the constructor of ``cls``. + """ + if cls is None: + cls = Option + + def decorator(f: FC) -> FC: + _param_memo(f, cls(param_decls, **attrs)) + return f + + return decorator + + +def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: + """Add a ``--yes`` option which shows a prompt before continuing if + not passed. If the prompt is declined, the program will exit. + + :param param_decls: One or more option names. Defaults to the single + value ``"--yes"``. + :param kwargs: Extra arguments are passed to :func:`option`. + """ + + def callback(ctx: Context, param: Parameter, value: bool) -> None: + if not value: + ctx.abort() + + if not param_decls: + param_decls = ("--yes",) + + kwargs.setdefault("is_flag", True) + kwargs.setdefault("callback", callback) + kwargs.setdefault("expose_value", False) + kwargs.setdefault("prompt", "Do you want to continue?") + kwargs.setdefault("help", "Confirm the action without prompting.") + return option(*param_decls, **kwargs) + + +def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: + """Add a ``--password`` option which prompts for a password, hiding + input and asking to enter the value again for confirmation. + + :param param_decls: One or more option names. Defaults to the single + value ``"--password"``. + :param kwargs: Extra arguments are passed to :func:`option`. + """ + if not param_decls: + param_decls = ("--password",) + + kwargs.setdefault("prompt", True) + kwargs.setdefault("confirmation_prompt", True) + kwargs.setdefault("hide_input", True) + return option(*param_decls, **kwargs) + + +def version_option( + version: str | None = None, + *param_decls: str, + package_name: str | None = None, + prog_name: str | None = None, + message: str | None = None, + **kwargs: t.Any, +) -> t.Callable[[FC], FC]: + """Add a ``--version`` option which immediately prints the version + number and exits the program. + + If ``version`` is not provided, Click will try to detect it using + :func:`importlib.metadata.version` to get the version for the + ``package_name``. + + If ``package_name`` is not provided, Click will try to detect it by + inspecting the stack frames. This will be used to detect the + version, so it must match the name of the installed package. + + :param version: The version number to show. If not provided, Click + will try to detect it. + :param param_decls: One or more option names. Defaults to the single + value ``"--version"``. + :param package_name: The package name to detect the version from. If + not provided, Click will try to detect it. + :param prog_name: The name of the CLI to show in the message. If not + provided, it will be detected from the command. + :param message: The message to show. The values ``%(prog)s``, + ``%(package)s``, and ``%(version)s`` are available. Defaults to + ``"%(prog)s, version %(version)s"``. + :param kwargs: Extra arguments are passed to :func:`option`. + :raise RuntimeError: ``version`` could not be detected. + + .. versionchanged:: 8.0 + Add the ``package_name`` parameter, and the ``%(package)s`` + value for messages. + + .. versionchanged:: 8.0 + Use :mod:`importlib.metadata` instead of ``pkg_resources``. The + version is detected based on the package name, not the entry + point name. The Python package name must match the installed + package name, or be passed with ``package_name=``. + """ + if message is None: + message = _("%(prog)s, version %(version)s") + + if version is None and package_name is None: + frame = inspect.currentframe() + f_back = frame.f_back if frame is not None else None + f_globals = f_back.f_globals if f_back is not None else None + # break reference cycle + # https://docs.python.org/3/library/inspect.html#the-interpreter-stack + del frame + + if f_globals is not None: + package_name = f_globals.get("__name__") + + if package_name == "__main__": + package_name = f_globals.get("__package__") + + if package_name: + package_name = package_name.partition(".")[0] + + def callback(ctx: Context, param: Parameter, value: bool) -> None: + if not value or ctx.resilient_parsing: + return + + nonlocal prog_name + nonlocal version + + if prog_name is None: + prog_name = ctx.find_root().info_name + + if version is None and package_name is not None: + import importlib.metadata + + try: + version = importlib.metadata.version(package_name) + except importlib.metadata.PackageNotFoundError: + raise RuntimeError( + f"{package_name!r} is not installed. Try passing" + " 'package_name' instead." + ) from None + + if version is None: + raise RuntimeError( + f"Could not determine the version for {package_name!r} automatically." + ) + + echo( + message % {"prog": prog_name, "package": package_name, "version": version}, + color=ctx.color, + ) + ctx.exit() + + if not param_decls: + param_decls = ("--version",) + + kwargs.setdefault("is_flag", True) + kwargs.setdefault("expose_value", False) + kwargs.setdefault("is_eager", True) + kwargs.setdefault("help", _("Show the version and exit.")) + kwargs["callback"] = callback + return option(*param_decls, **kwargs) + + +def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: + """Pre-configured ``--help`` option which immediately prints the help page + and exits the program. + + :param param_decls: One or more option names. Defaults to the single + value ``"--help"``. + :param kwargs: Extra arguments are passed to :func:`option`. + """ + + def show_help(ctx: Context, param: Parameter, value: bool) -> None: + """Callback that print the help page on ```` and exits.""" + if value and not ctx.resilient_parsing: + echo(ctx.get_help(), color=ctx.color) + ctx.exit() + + if not param_decls: + param_decls = ("--help",) + + kwargs.setdefault("is_flag", True) + kwargs.setdefault("expose_value", False) + kwargs.setdefault("is_eager", True) + kwargs.setdefault("help", _("Show this message and exit.")) + kwargs.setdefault("callback", show_help) + + return option(*param_decls, **kwargs) diff --git a/miniconda3/lib/python3.13/site-packages/click/exceptions.py b/miniconda3/lib/python3.13/site-packages/click/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f141a832e1ab678709998c3bbafcdea6561b9661 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/exceptions.py @@ -0,0 +1,308 @@ +from __future__ import annotations + +import collections.abc as cabc +import typing as t +from gettext import gettext as _ +from gettext import ngettext + +from ._compat import get_text_stderr +from .globals import resolve_color_default +from .utils import echo +from .utils import format_filename + +if t.TYPE_CHECKING: + from .core import Command + from .core import Context + from .core import Parameter + + +def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None: + if param_hint is not None and not isinstance(param_hint, str): + return " / ".join(repr(x) for x in param_hint) + + return param_hint + + +class ClickException(Exception): + """An exception that Click can handle and show to the user.""" + + #: The exit code for this exception. + exit_code = 1 + + def __init__(self, message: str) -> None: + super().__init__(message) + # The context will be removed by the time we print the message, so cache + # the color settings here to be used later on (in `show`) + self.show_color: bool | None = resolve_color_default() + self.message = message + + def format_message(self) -> str: + return self.message + + def __str__(self) -> str: + return self.message + + def show(self, file: t.IO[t.Any] | None = None) -> None: + if file is None: + file = get_text_stderr() + + echo( + _("Error: {message}").format(message=self.format_message()), + file=file, + color=self.show_color, + ) + + +class UsageError(ClickException): + """An internal exception that signals a usage error. This typically + aborts any further handling. + + :param message: the error message to display. + :param ctx: optionally the context that caused this error. Click will + fill in the context automatically in some situations. + """ + + exit_code = 2 + + def __init__(self, message: str, ctx: Context | None = None) -> None: + super().__init__(message) + self.ctx = ctx + self.cmd: Command | None = self.ctx.command if self.ctx else None + + def show(self, file: t.IO[t.Any] | None = None) -> None: + if file is None: + file = get_text_stderr() + color = None + hint = "" + if ( + self.ctx is not None + and self.ctx.command.get_help_option(self.ctx) is not None + ): + hint = _("Try '{command} {option}' for help.").format( + command=self.ctx.command_path, option=self.ctx.help_option_names[0] + ) + hint = f"{hint}\n" + if self.ctx is not None: + color = self.ctx.color + echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) + echo( + _("Error: {message}").format(message=self.format_message()), + file=file, + color=color, + ) + + +class BadParameter(UsageError): + """An exception that formats out a standardized error message for a + bad parameter. This is useful when thrown from a callback or type as + Click will attach contextual information to it (for instance, which + parameter it is). + + .. versionadded:: 2.0 + + :param param: the parameter object that caused this error. This can + be left out, and Click will attach this info itself + if possible. + :param param_hint: a string that shows up as parameter name. This + can be used as alternative to `param` in cases + where custom validation should happen. If it is + a string it's used as such, if it's a list then + each item is quoted and separated. + """ + + def __init__( + self, + message: str, + ctx: Context | None = None, + param: Parameter | None = None, + param_hint: str | None = None, + ) -> None: + super().__init__(message, ctx) + self.param = param + self.param_hint = param_hint + + def format_message(self) -> str: + if self.param_hint is not None: + param_hint = self.param_hint + elif self.param is not None: + param_hint = self.param.get_error_hint(self.ctx) # type: ignore + else: + return _("Invalid value: {message}").format(message=self.message) + + return _("Invalid value for {param_hint}: {message}").format( + param_hint=_join_param_hints(param_hint), message=self.message + ) + + +class MissingParameter(BadParameter): + """Raised if click required an option or argument but it was not + provided when invoking the script. + + .. versionadded:: 4.0 + + :param param_type: a string that indicates the type of the parameter. + The default is to inherit the parameter type from + the given `param`. Valid values are ``'parameter'``, + ``'option'`` or ``'argument'``. + """ + + def __init__( + self, + message: str | None = None, + ctx: Context | None = None, + param: Parameter | None = None, + param_hint: str | None = None, + param_type: str | None = None, + ) -> None: + super().__init__(message or "", ctx, param, param_hint) + self.param_type = param_type + + def format_message(self) -> str: + if self.param_hint is not None: + param_hint: str | None = self.param_hint + elif self.param is not None: + param_hint = self.param.get_error_hint(self.ctx) # type: ignore + else: + param_hint = None + + param_hint = _join_param_hints(param_hint) + param_hint = f" {param_hint}" if param_hint else "" + + param_type = self.param_type + if param_type is None and self.param is not None: + param_type = self.param.param_type_name + + msg = self.message + if self.param is not None: + msg_extra = self.param.type.get_missing_message( + param=self.param, ctx=self.ctx + ) + if msg_extra: + if msg: + msg += f". {msg_extra}" + else: + msg = msg_extra + + msg = f" {msg}" if msg else "" + + # Translate param_type for known types. + if param_type == "argument": + missing = _("Missing argument") + elif param_type == "option": + missing = _("Missing option") + elif param_type == "parameter": + missing = _("Missing parameter") + else: + missing = _("Missing {param_type}").format(param_type=param_type) + + return f"{missing}{param_hint}.{msg}" + + def __str__(self) -> str: + if not self.message: + param_name = self.param.name if self.param else None + return _("Missing parameter: {param_name}").format(param_name=param_name) + else: + return self.message + + +class NoSuchOption(UsageError): + """Raised if click attempted to handle an option that does not + exist. + + .. versionadded:: 4.0 + """ + + def __init__( + self, + option_name: str, + message: str | None = None, + possibilities: cabc.Sequence[str] | None = None, + ctx: Context | None = None, + ) -> None: + if message is None: + message = _("No such option: {name}").format(name=option_name) + + super().__init__(message, ctx) + self.option_name = option_name + self.possibilities = possibilities + + def format_message(self) -> str: + if not self.possibilities: + return self.message + + possibility_str = ", ".join(sorted(self.possibilities)) + suggest = ngettext( + "Did you mean {possibility}?", + "(Possible options: {possibilities})", + len(self.possibilities), + ).format(possibility=possibility_str, possibilities=possibility_str) + return f"{self.message} {suggest}" + + +class BadOptionUsage(UsageError): + """Raised if an option is generally supplied but the use of the option + was incorrect. This is for instance raised if the number of arguments + for an option is not correct. + + .. versionadded:: 4.0 + + :param option_name: the name of the option being used incorrectly. + """ + + def __init__( + self, option_name: str, message: str, ctx: Context | None = None + ) -> None: + super().__init__(message, ctx) + self.option_name = option_name + + +class BadArgumentUsage(UsageError): + """Raised if an argument is generally supplied but the use of the argument + was incorrect. This is for instance raised if the number of values + for an argument is not correct. + + .. versionadded:: 6.0 + """ + + +class NoArgsIsHelpError(UsageError): + def __init__(self, ctx: Context) -> None: + self.ctx: Context + super().__init__(ctx.get_help(), ctx=ctx) + + def show(self, file: t.IO[t.Any] | None = None) -> None: + echo(self.format_message(), file=file, err=True, color=self.ctx.color) + + +class FileError(ClickException): + """Raised if a file cannot be opened.""" + + def __init__(self, filename: str, hint: str | None = None) -> None: + if hint is None: + hint = _("unknown error") + + super().__init__(hint) + self.ui_filename: str = format_filename(filename) + self.filename = filename + + def format_message(self) -> str: + return _("Could not open file {filename!r}: {message}").format( + filename=self.ui_filename, message=self.message + ) + + +class Abort(RuntimeError): + """An internal signalling exception that signals Click to abort.""" + + +class Exit(RuntimeError): + """An exception that indicates that the application should exit with some + status code. + + :param code: the status code to exit with. + """ + + __slots__ = ("exit_code",) + + def __init__(self, code: int = 0) -> None: + self.exit_code: int = code diff --git a/miniconda3/lib/python3.13/site-packages/click/formatting.py b/miniconda3/lib/python3.13/site-packages/click/formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..9891f8809feff24a529ce47a860589c129835322 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/formatting.py @@ -0,0 +1,301 @@ +from __future__ import annotations + +import collections.abc as cabc +from contextlib import contextmanager +from gettext import gettext as _ + +from ._compat import term_len +from .parser import _split_opt + +# Can force a width. This is used by the test system +FORCED_WIDTH: int | None = None + + +def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]: + widths: dict[int, int] = {} + + for row in rows: + for idx, col in enumerate(row): + widths[idx] = max(widths.get(idx, 0), term_len(col)) + + return tuple(y for x, y in sorted(widths.items())) + + +def iter_rows( + rows: cabc.Iterable[tuple[str, str]], col_count: int +) -> cabc.Iterator[tuple[str, ...]]: + for row in rows: + yield row + ("",) * (col_count - len(row)) + + +def wrap_text( + text: str, + width: int = 78, + initial_indent: str = "", + subsequent_indent: str = "", + preserve_paragraphs: bool = False, +) -> str: + """A helper function that intelligently wraps text. By default, it + assumes that it operates on a single paragraph of text but if the + `preserve_paragraphs` parameter is provided it will intelligently + handle paragraphs (defined by two empty lines). + + If paragraphs are handled, a paragraph can be prefixed with an empty + line containing the ``\\b`` character (``\\x08``) to indicate that + no rewrapping should happen in that block. + + :param text: the text that should be rewrapped. + :param width: the maximum width for the text. + :param initial_indent: the initial indent that should be placed on the + first line as a string. + :param subsequent_indent: the indent string that should be placed on + each consecutive line. + :param preserve_paragraphs: if this flag is set then the wrapping will + intelligently handle paragraphs. + """ + from ._textwrap import TextWrapper + + text = text.expandtabs() + wrapper = TextWrapper( + width, + initial_indent=initial_indent, + subsequent_indent=subsequent_indent, + replace_whitespace=False, + ) + if not preserve_paragraphs: + return wrapper.fill(text) + + p: list[tuple[int, bool, str]] = [] + buf: list[str] = [] + indent = None + + def _flush_par() -> None: + if not buf: + return + if buf[0].strip() == "\b": + p.append((indent or 0, True, "\n".join(buf[1:]))) + else: + p.append((indent or 0, False, " ".join(buf))) + del buf[:] + + for line in text.splitlines(): + if not line: + _flush_par() + indent = None + else: + if indent is None: + orig_len = term_len(line) + line = line.lstrip() + indent = orig_len - term_len(line) + buf.append(line) + _flush_par() + + rv = [] + for indent, raw, text in p: + with wrapper.extra_indent(" " * indent): + if raw: + rv.append(wrapper.indent_only(text)) + else: + rv.append(wrapper.fill(text)) + + return "\n\n".join(rv) + + +class HelpFormatter: + """This class helps with formatting text-based help pages. It's + usually just needed for very special internal cases, but it's also + exposed so that developers can write their own fancy outputs. + + At present, it always writes into memory. + + :param indent_increment: the additional increment for each level. + :param width: the width for the text. This defaults to the terminal + width clamped to a maximum of 78. + """ + + def __init__( + self, + indent_increment: int = 2, + width: int | None = None, + max_width: int | None = None, + ) -> None: + import shutil + + self.indent_increment = indent_increment + if max_width is None: + max_width = 80 + if width is None: + width = FORCED_WIDTH + if width is None: + width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50) + self.width = width + self.current_indent: int = 0 + self.buffer: list[str] = [] + + def write(self, string: str) -> None: + """Writes a unicode string into the internal buffer.""" + self.buffer.append(string) + + def indent(self) -> None: + """Increases the indentation.""" + self.current_indent += self.indent_increment + + def dedent(self) -> None: + """Decreases the indentation.""" + self.current_indent -= self.indent_increment + + def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None: + """Writes a usage line into the buffer. + + :param prog: the program name. + :param args: whitespace separated list of arguments. + :param prefix: The prefix for the first line. Defaults to + ``"Usage: "``. + """ + if prefix is None: + prefix = f"{_('Usage:')} " + + usage_prefix = f"{prefix:>{self.current_indent}}{prog} " + text_width = self.width - self.current_indent + + if text_width >= (term_len(usage_prefix) + 20): + # The arguments will fit to the right of the prefix. + indent = " " * term_len(usage_prefix) + self.write( + wrap_text( + args, + text_width, + initial_indent=usage_prefix, + subsequent_indent=indent, + ) + ) + else: + # The prefix is too long, put the arguments on the next line. + self.write(usage_prefix) + self.write("\n") + indent = " " * (max(self.current_indent, term_len(prefix)) + 4) + self.write( + wrap_text( + args, text_width, initial_indent=indent, subsequent_indent=indent + ) + ) + + self.write("\n") + + def write_heading(self, heading: str) -> None: + """Writes a heading into the buffer.""" + self.write(f"{'':>{self.current_indent}}{heading}:\n") + + def write_paragraph(self) -> None: + """Writes a paragraph into the buffer.""" + if self.buffer: + self.write("\n") + + def write_text(self, text: str) -> None: + """Writes re-indented text into the buffer. This rewraps and + preserves paragraphs. + """ + indent = " " * self.current_indent + self.write( + wrap_text( + text, + self.width, + initial_indent=indent, + subsequent_indent=indent, + preserve_paragraphs=True, + ) + ) + self.write("\n") + + def write_dl( + self, + rows: cabc.Sequence[tuple[str, str]], + col_max: int = 30, + col_spacing: int = 2, + ) -> None: + """Writes a definition list into the buffer. This is how options + and commands are usually formatted. + + :param rows: a list of two item tuples for the terms and values. + :param col_max: the maximum width of the first column. + :param col_spacing: the number of spaces between the first and + second column. + """ + rows = list(rows) + widths = measure_table(rows) + if len(widths) != 2: + raise TypeError("Expected two columns for definition list") + + first_col = min(widths[0], col_max) + col_spacing + + for first, second in iter_rows(rows, len(widths)): + self.write(f"{'':>{self.current_indent}}{first}") + if not second: + self.write("\n") + continue + if term_len(first) <= first_col - col_spacing: + self.write(" " * (first_col - term_len(first))) + else: + self.write("\n") + self.write(" " * (first_col + self.current_indent)) + + text_width = max(self.width - first_col - 2, 10) + wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) + lines = wrapped_text.splitlines() + + if lines: + self.write(f"{lines[0]}\n") + + for line in lines[1:]: + self.write(f"{'':>{first_col + self.current_indent}}{line}\n") + else: + self.write("\n") + + @contextmanager + def section(self, name: str) -> cabc.Iterator[None]: + """Helpful context manager that writes a paragraph, a heading, + and the indents. + + :param name: the section name that is written as heading. + """ + self.write_paragraph() + self.write_heading(name) + self.indent() + try: + yield + finally: + self.dedent() + + @contextmanager + def indentation(self) -> cabc.Iterator[None]: + """A context manager that increases the indentation.""" + self.indent() + try: + yield + finally: + self.dedent() + + def getvalue(self) -> str: + """Returns the buffer contents.""" + return "".join(self.buffer) + + +def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]: + """Given a list of option strings this joins them in the most appropriate + way and returns them in the form ``(formatted_string, + any_prefix_is_slash)`` where the second item in the tuple is a flag that + indicates if any of the option prefixes was a slash. + """ + rv = [] + any_prefix_is_slash = False + + for opt in options: + prefix = _split_opt(opt)[0] + + if prefix == "/": + any_prefix_is_slash = True + + rv.append((len(prefix), opt)) + + rv.sort(key=lambda x: x[0]) + return ", ".join(x[1] for x in rv), any_prefix_is_slash diff --git a/miniconda3/lib/python3.13/site-packages/click/globals.py b/miniconda3/lib/python3.13/site-packages/click/globals.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f91723d21cefdf658be327174e1f8ccdc20fcd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/globals.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +import typing as t +from threading import local + +if t.TYPE_CHECKING: + from .core import Context + +_local = local() + + +@t.overload +def get_current_context(silent: t.Literal[False] = False) -> Context: ... + + +@t.overload +def get_current_context(silent: bool = ...) -> Context | None: ... + + +def get_current_context(silent: bool = False) -> Context | None: + """Returns the current click context. This can be used as a way to + access the current context object from anywhere. This is a more implicit + alternative to the :func:`pass_context` decorator. This function is + primarily useful for helpers such as :func:`echo` which might be + interested in changing its behavior based on the current context. + + To push the current context, :meth:`Context.scope` can be used. + + .. versionadded:: 5.0 + + :param silent: if set to `True` the return value is `None` if no context + is available. The default behavior is to raise a + :exc:`RuntimeError`. + """ + try: + return t.cast("Context", _local.stack[-1]) + except (AttributeError, IndexError) as e: + if not silent: + raise RuntimeError("There is no active click context.") from e + + return None + + +def push_context(ctx: Context) -> None: + """Pushes a new context to the current stack.""" + _local.__dict__.setdefault("stack", []).append(ctx) + + +def pop_context() -> None: + """Removes the top level from the stack.""" + _local.stack.pop() + + +def resolve_color_default(color: bool | None = None) -> bool | None: + """Internal helper to get the default value of the color flag. If a + value is passed it's returned unchanged, otherwise it's looked up from + the current context. + """ + if color is not None: + return color + + ctx = get_current_context(silent=True) + + if ctx is not None: + return ctx.color + + return None diff --git a/miniconda3/lib/python3.13/site-packages/click/parser.py b/miniconda3/lib/python3.13/site-packages/click/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..a8b7d2634a89df3c9e0b7a1f85dfd4bace60a608 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/parser.py @@ -0,0 +1,532 @@ +""" +This module started out as largely a copy paste from the stdlib's +optparse module with the features removed that we do not need from +optparse because we implement them in Click on a higher level (for +instance 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 stdlib +is that there are differences in 2.x and 3.x about the error messages +generated and optparse in the stdlib uses gettext for no good reason +and might cause us issues. + +Click uses parts of optparse written by Gregory P. Ward and maintained +by 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 Foundation +from __future__ import annotations + +import collections.abc as cabc +import typing as t +from collections import deque +from gettext import gettext as _ +from gettext import ngettext + +from .exceptions import BadArgumentUsage +from .exceptions import BadOptionUsage +from .exceptions import NoSuchOption +from .exceptions import UsageError + +if t.TYPE_CHECKING: + 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") + +# Sentinel value that indicates an option was passed as a flag without a +# value but is not a flag option. Option.consume_value uses this to +# prompt or use the flag_value. +_flag_needs_value = object() + + +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 `None`. + """ + args = deque(args) + nargs_spec = deque(nargs_spec) + rv: list[str | tuple[str | None, ...] | None] = [] + spos: int | None = None + + def _fetch(c: deque[V]) -> V | None: + try: + if spos is None: + return c.popleft() + else: + return c.pop() + except IndexError: + return None + + while nargs_spec: + nargs = _fetch(nargs_spec) + + if nargs is None: + continue + + if nargs == 1: + rv.append(_fetch(args)) + 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(None) + + # 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, + state: _ParsingState, + ) -> None: + if self.nargs > 1: + assert value is not None + holes = sum(1 for x in value if x is None) + if holes == len(value): + value = None + elif holes != 0: + raise BadArgumentUsage( + _("Argument {name!r} takes {nargs} values.").format( + name=self.dest, nargs=self.nargs + ) + ) + + if self.nargs == -1 and self.obj.envvar is not None and value == (): + # Replace empty tuple with None so that a value from the + # environment may be tried. + value = None + + 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 = None + + 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 = None + + 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 + ) -> t.Any: + nargs = option.nargs + + 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) diff --git a/miniconda3/lib/python3.13/site-packages/click/py.typed b/miniconda3/lib/python3.13/site-packages/click/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/click/shell_completion.py b/miniconda3/lib/python3.13/site-packages/click/shell_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..6c39d5eb3889000b499d37262cc5f7de8b7a443e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/shell_completion.py @@ -0,0 +1,644 @@ +from __future__ import annotations + +import collections.abc as cabc +import os +import re +import typing as t +from gettext import gettext as _ + +from .core import Argument +from .core import Command +from .core import Context +from .core import Group +from .core import Option +from .core import Parameter +from .core import ParameterSource +from .utils import echo + + +def shell_complete( + cli: Command, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + complete_var: str, + instruction: str, +) -> int: + """Perform shell completion for the given CLI program. + + :param cli: Command being called. + :param ctx_args: Extra arguments to pass to + ``cli.make_context``. + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. + :param instruction: Value of ``complete_var`` with the completion + instruction and shell, in the form ``instruction_shell``. + :return: Status code to exit with. + """ + shell, _, instruction = instruction.partition("_") + comp_cls = get_completion_class(shell) + + if comp_cls is None: + return 1 + + comp = comp_cls(cli, ctx_args, prog_name, complete_var) + + if instruction == "source": + echo(comp.source()) + return 0 + + if instruction == "complete": + echo(comp.complete()) + return 0 + + return 1 + + +class CompletionItem: + """Represents a completion value and metadata about the value. The + default metadata is ``type`` to indicate special shell handling, + and ``help`` if a shell supports showing a help string next to the + value. + + Arbitrary parameters can be passed when creating the object, and + accessed using ``item.attr``. If an attribute wasn't passed, + accessing it returns ``None``. + + :param value: The completion suggestion. + :param type: Tells the shell script to provide special completion + support for the type. Click uses ``"dir"`` and ``"file"``. + :param help: String shown next to the value if supported. + :param kwargs: Arbitrary metadata. The built-in implementations + don't use this, but custom type completions paired with custom + shell support could use it. + """ + + __slots__ = ("value", "type", "help", "_info") + + def __init__( + self, + value: t.Any, + type: str = "plain", + help: str | None = None, + **kwargs: t.Any, + ) -> None: + self.value: t.Any = value + self.type: str = type + self.help: str | None = help + self._info = kwargs + + def __getattr__(self, name: str) -> t.Any: + return self._info.get(name) + + +# Only Bash >= 4.4 has the nosort option. +_SOURCE_BASH = """\ +%(complete_func)s() { + local IFS=$'\\n' + local response + + response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \ +%(complete_var)s=bash_complete $1) + + for completion in $response; do + IFS=',' read type value <<< "$completion" + + if [[ $type == 'dir' ]]; then + COMPREPLY=() + compopt -o dirnames + elif [[ $type == 'file' ]]; then + COMPREPLY=() + compopt -o default + elif [[ $type == 'plain' ]]; then + COMPREPLY+=($value) + fi + done + + return 0 +} + +%(complete_func)s_setup() { + complete -o nosort -F %(complete_func)s %(prog_name)s +} + +%(complete_func)s_setup; +""" + +_SOURCE_ZSH = """\ +#compdef %(prog_name)s + +%(complete_func)s() { + local -a completions + local -a completions_with_descriptions + local -a response + (( ! $+commands[%(prog_name)s] )) && return 1 + + response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \ +%(complete_var)s=zsh_complete %(prog_name)s)}") + + for type key descr in ${response}; do + if [[ "$type" == "plain" ]]; then + if [[ "$descr" == "_" ]]; then + completions+=("$key") + else + completions_with_descriptions+=("$key":"$descr") + fi + elif [[ "$type" == "dir" ]]; then + _path_files -/ + elif [[ "$type" == "file" ]]; then + _path_files -f + fi + done + + if [ -n "$completions_with_descriptions" ]; then + _describe -V unsorted completions_with_descriptions -U + fi + + if [ -n "$completions" ]; then + compadd -U -V unsorted -a completions + fi +} + +if [[ $zsh_eval_context[-1] == loadautofunc ]]; then + # autoload from fpath, call function directly + %(complete_func)s "$@" +else + # eval/source/. command, register function for later + compdef %(complete_func)s %(prog_name)s +fi +""" + +_SOURCE_FISH = """\ +function %(complete_func)s; + set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \ +COMP_CWORD=(commandline -t) %(prog_name)s); + + for completion in $response; + set -l metadata (string split "," $completion); + + if test $metadata[1] = "dir"; + __fish_complete_directories $metadata[2]; + else if test $metadata[1] = "file"; + __fish_complete_path $metadata[2]; + else if test $metadata[1] = "plain"; + echo $metadata[2]; + end; + end; +end; + +complete --no-files --command %(prog_name)s --arguments \ +"(%(complete_func)s)"; +""" + + +class ShellComplete: + """Base class for providing shell completion support. A subclass for + a given shell will override attributes and methods to implement the + completion instructions (``source`` and ``complete``). + + :param cli: Command being called. + :param prog_name: Name of the executable in the shell. + :param complete_var: Name of the environment variable that holds + the completion instruction. + + .. versionadded:: 8.0 + """ + + name: t.ClassVar[str] + """Name to register the shell as with :func:`add_completion_class`. + This is used in completion instructions (``{name}_source`` and + ``{name}_complete``). + """ + + source_template: t.ClassVar[str] + """Completion script template formatted by :meth:`source`. This must + be provided by subclasses. + """ + + def __init__( + self, + cli: Command, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + complete_var: str, + ) -> None: + self.cli = cli + self.ctx_args = ctx_args + self.prog_name = prog_name + self.complete_var = complete_var + + @property + def func_name(self) -> str: + """The name of the shell function defined by the completion + script. + """ + safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII) + return f"_{safe_name}_completion" + + def source_vars(self) -> dict[str, t.Any]: + """Vars for formatting :attr:`source_template`. + + By default this provides ``complete_func``, ``complete_var``, + and ``prog_name``. + """ + return { + "complete_func": self.func_name, + "complete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def source(self) -> str: + """Produce the shell script that defines the completion + function. By default this ``%``-style formats + :attr:`source_template` with the dict returned by + :meth:`source_vars`. + """ + return self.source_template % self.source_vars() + + def get_completion_args(self) -> tuple[list[str], str]: + """Use the env vars defined by the shell script to return a + tuple of ``args, incomplete``. This must be implemented by + subclasses. + """ + raise NotImplementedError + + def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]: + """Determine the context and last complete command or parameter + from the complete args. Call that object's ``shell_complete`` + method to get the completions for the incomplete value. + + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ + ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args) + obj, incomplete = _resolve_incomplete(ctx, args, incomplete) + return obj.shell_complete(ctx, incomplete) + + def format_completion(self, item: CompletionItem) -> str: + """Format a completion item into the form recognized by the + shell script. This must be implemented by subclasses. + + :param item: Completion item to format. + """ + raise NotImplementedError + + def complete(self) -> str: + """Produce the completion data to send back to the shell. + + By default this calls :meth:`get_completion_args`, gets the + completions, then calls :meth:`format_completion` for each + completion. + """ + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + out = [self.format_completion(item) for item in completions] + return "\n".join(out) + + +class BashComplete(ShellComplete): + """Shell completion for Bash.""" + + name = "bash" + source_template = _SOURCE_BASH + + @staticmethod + def _check_version() -> None: + import shutil + import subprocess + + bash_exe = shutil.which("bash") + + if bash_exe is None: + match = None + else: + output = subprocess.run( + [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'], + stdout=subprocess.PIPE, + ) + match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode()) + + if match is not None: + major, minor = match.groups() + + if major < "4" or major == "4" and minor < "4": + echo( + _( + "Shell completion is not supported for Bash" + " versions older than 4.4." + ), + err=True, + ) + else: + echo( + _("Couldn't detect Bash version, shell completion is not supported."), + err=True, + ) + + def source(self) -> str: + self._check_version() + return super().source() + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: + return f"{item.type},{item.value}" + + +class ZshComplete(ShellComplete): + """Shell completion for Zsh.""" + + name = "zsh" + source_template = _SOURCE_ZSH + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: + return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}" + + +class FishComplete(ShellComplete): + """Shell completion for Fish.""" + + name = "fish" + source_template = _SOURCE_FISH + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = split_arg_string(os.environ["COMP_WORDS"]) + incomplete = os.environ["COMP_CWORD"] + args = cwords[1:] + + # Fish stores the partial word in both COMP_WORDS and + # COMP_CWORD, remove it from complete args. + if incomplete and args and args[-1] == incomplete: + args.pop() + + return args, incomplete + + def format_completion(self, item: CompletionItem) -> str: + if item.help: + return f"{item.type},{item.value}\t{item.help}" + + return f"{item.type},{item.value}" + + +ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]") + + +_available_shells: dict[str, type[ShellComplete]] = { + "bash": BashComplete, + "fish": FishComplete, + "zsh": ZshComplete, +} + + +def add_completion_class( + cls: ShellCompleteType, name: str | None = None +) -> ShellCompleteType: + """Register a :class:`ShellComplete` subclass under the given name. + The name will be provided by the completion instruction environment + variable during completion. + + :param cls: The completion class that will handle completion for the + shell. + :param name: Name to register the class under. Defaults to the + class's ``name`` attribute. + """ + if name is None: + name = cls.name + + _available_shells[name] = cls + + return cls + + +def get_completion_class(shell: str) -> type[ShellComplete] | None: + """Look up a registered :class:`ShellComplete` subclass by the name + provided by the completion instruction environment variable. If the + name isn't registered, returns ``None``. + + :param shell: Name the class is registered under. + """ + return _available_shells.get(shell) + + +def split_arg_string(string: str) -> list[str]: + """Split an argument string as with :func:`shlex.split`, but don't + fail if the string is incomplete. Ignores a missing closing quote or + incomplete escape sequence and uses the partial token as-is. + + .. code-block:: python + + split_arg_string("example 'my file") + ["example", "my file"] + + split_arg_string("example my\\") + ["example", "my"] + + :param string: String to split. + + .. versionchanged:: 8.2 + Moved to ``shell_completion`` from ``parser``. + """ + import shlex + + lex = shlex.shlex(string, posix=True) + lex.whitespace_split = True + lex.commenters = "" + out = [] + + try: + for token in lex: + out.append(token) + except ValueError: + # Raised when end-of-string is reached in an invalid state. Use + # the partial token as-is. The quote or escape character is in + # lex.state, not lex.token. + out.append(lex.token) + + return out + + +def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: + """Determine if the given parameter is an argument that can still + accept values. + + :param ctx: Invocation context for the command represented by the + parsed complete args. + :param param: Argument object being checked. + """ + if not isinstance(param, Argument): + return False + + assert param.name is not None + # Will be None if expose_value is False. + value = ctx.params.get(param.name) + return ( + param.nargs == -1 + or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE + or ( + param.nargs > 1 + and isinstance(value, (tuple, list)) + and len(value) < param.nargs + ) + ) + + +def _start_of_option(ctx: Context, value: str) -> bool: + """Check if the value looks like the start of an option.""" + if not value: + return False + + c = value[0] + return c in ctx._opt_prefixes + + +def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool: + """Determine if the given parameter is an option that needs a value. + + :param args: List of complete args before the incomplete value. + :param param: Option object being checked. + """ + if not isinstance(param, Option): + return False + + if param.is_flag or param.count: + return False + + last_option = None + + for index, arg in enumerate(reversed(args)): + if index + 1 > param.nargs: + break + + if _start_of_option(ctx, arg): + last_option = arg + + return last_option is not None and last_option in param.opts + + +def _resolve_context( + cli: Command, + ctx_args: cabc.MutableMapping[str, t.Any], + prog_name: str, + args: list[str], +) -> Context: + """Produce the context hierarchy starting with the command and + traversing the complete arguments. This only follows the commands, + it doesn't trigger input prompts or callbacks. + + :param cli: Command being called. + :param prog_name: Name of the executable in the shell. + :param args: List of complete args before the incomplete value. + """ + ctx_args["resilient_parsing"] = True + with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx: + args = ctx._protected_args + ctx.args + + while args: + command = ctx.command + + if isinstance(command, Group): + if not command.chain: + name, cmd, args = command.resolve_command(ctx, args) + + if cmd is None: + return ctx + + with cmd.make_context( + name, args, parent=ctx, resilient_parsing=True + ) as sub_ctx: + ctx = sub_ctx + args = ctx._protected_args + ctx.args + else: + sub_ctx = ctx + + while args: + name, cmd, args = command.resolve_command(ctx, args) + + if cmd is None: + return ctx + + with cmd.make_context( + name, + args, + parent=ctx, + allow_extra_args=True, + allow_interspersed_args=False, + resilient_parsing=True, + ) as sub_sub_ctx: + sub_ctx = sub_sub_ctx + args = sub_ctx.args + + ctx = sub_ctx + args = [*sub_ctx._protected_args, *sub_ctx.args] + else: + break + + return ctx + + +def _resolve_incomplete( + ctx: Context, args: list[str], incomplete: str +) -> tuple[Command | Parameter, str]: + """Find the Click object that will handle the completion of the + incomplete value. Return the object and the incomplete value. + + :param ctx: Invocation context for the command represented by + the parsed complete args. + :param args: List of complete args before the incomplete value. + :param incomplete: Value being completed. May be empty. + """ + # Different shells treat an "=" between a long option name and + # value differently. Might keep the value joined, return the "=" + # as a separate item, or return the split name and value. Always + # split and discard the "=" to make completion easier. + if incomplete == "=": + incomplete = "" + elif "=" in incomplete and _start_of_option(ctx, incomplete): + name, _, incomplete = incomplete.partition("=") + args.append(name) + + # The "--" marker tells Click to stop treating values as options + # even if they start with the option character. If it hasn't been + # given and the incomplete arg looks like an option, the current + # command will provide option name completions. + if "--" not in args and _start_of_option(ctx, incomplete): + return ctx.command, incomplete + + params = ctx.command.get_params(ctx) + + # If the last complete arg is an option name with an incomplete + # value, the option will provide value completions. + for param in params: + if _is_incomplete_option(ctx, args, param): + return param, incomplete + + # It's not an option name or value. The first argument without a + # parsed value will provide value completions. + for param in params: + if _is_incomplete_argument(ctx, param): + return param, incomplete + + # There were no unparsed arguments, the command may be a group that + # will provide command name completions. + return ctx.command, incomplete diff --git a/miniconda3/lib/python3.13/site-packages/click/termui.py b/miniconda3/lib/python3.13/site-packages/click/termui.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbb22216c4bac521eee02fbac97e3b67f302076 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/termui.py @@ -0,0 +1,877 @@ +from __future__ import annotations + +import collections.abc as cabc +import inspect +import io +import itertools +import sys +import typing as t +from contextlib import AbstractContextManager +from gettext import gettext as _ + +from ._compat import isatty +from ._compat import strip_ansi +from .exceptions import Abort +from .exceptions import UsageError +from .globals import resolve_color_default +from .types import Choice +from .types import convert_type +from .types import ParamType +from .utils import echo +from .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 = 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 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 = 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. + :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): ". + + .. 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.rstrip(" "), nl=False, err=err) + # Echo a space to stdout to work around an issue where + # readline causes backspace to clear the whole line. + return f(" ") + 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.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.rstrip(" "), nl=False, err=err) + # Echo a space to stdout to work around an issue where + # readline causes backspace to clear the whole line. + value = visible_prompt_func(" ").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.overload +def 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.overload +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]: ... + + +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.overload +def 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.overload +def edit( + text: str, + editor: str | None = None, + env: cabc.Mapping[str, str] | None = None, + require_save: bool = True, + extension: str = ".txt", +) -> str | None: ... + + +@t.overload +def 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) diff --git a/miniconda3/lib/python3.13/site-packages/click/testing.py b/miniconda3/lib/python3.13/site-packages/click/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..7c0e8741e2d07f54294a82792c776d08c639add4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/testing.py @@ -0,0 +1,565 @@ +from __future__ import annotations + +import collections.abc as cabc +import contextlib +import io +import os +import shlex +import shutil +import sys +import tempfile +import typing as t +from types import TracebackType + +from . import _compat +from . import formatting +from . import termui +from . import utils +from ._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.contextmanager +def _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 `` and `` 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): + def __init__( + self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any + ) -> None: + super().__init__(buffer, **kwargs) + self._name = name + self._mode = mode + + @property + def name(self) -> str: + return self._name + + @property + def mode(self) -> str: + return self._mode + + def __next__(self) -> str: # type: ignore + try: + line = super().__next__() + except StopIteration as e: + raise EOFError() from e + return line + + +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 `` and ``, 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 `` 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 `` writes + to ``. 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 `` 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 + `` and `` streams. + + .. versionchanged:: 8.2 + Always returns the `` stream. + + .. versionchanged:: 8.0 + `` 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() + + 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="", 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="", mode="w" + ) + + sys.stderr = _NamedTextIOWrapper( + stream_mixer.stderr, + encoding=self.charset, + name="", + mode="w", + errors="backslashreplace", + ) + + @_pause_echo(echo_input) # type: ignore + def visible_input(prompt: str | None = None) -> str: + sys.stdout.write(prompt or "") + val = next(text_input).rstrip("\r\n") + 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() + return next(text_input).rstrip("\r\n") + + @_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 + 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 + + 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 + + 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: + try: + shutil.rmtree(dt) + except OSError: + pass diff --git a/miniconda3/lib/python3.13/site-packages/click/types.py b/miniconda3/lib/python3.13/site-packages/click/types.py new file mode 100644 index 0000000000000000000000000000000000000000..684cb3b1e6107bada194d18968de69a7f383a2a0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/types.py @@ -0,0 +1,1165 @@ +from __future__ import annotations + +import collections.abc as cabc +import enum +import os +import stat +import sys +import typing as t +from datetime import datetime +from gettext import gettext as _ +from gettext import ngettext + +from ._compat import _get_argv_encoding +from ._compat import open_stream +from .exceptions import BadParameter +from .utils import format_filename +from .utils import LazyFile +from .utils import safecall + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .core import Context + from .core import Parameter + from .shell_completion import CompletionItem + +ParamTypeValue = t.TypeVar("ParamTypeValue") + + +class ParamType: + """Represents the type of a parameter. Validates and converts values + from the command line or Python into the correct type. + + To implement a custom type, subclass and implement at least the + following: + + - The :attr:`name` class attribute must be set. + - Calling an instance of the type with ``None`` must return + ``None``. This is already implemented by default. + - :meth:`convert` must convert string values to the correct type. + - :meth:`convert` must accept values that are already the correct + type. + - It must be able to convert a value if the ``ctx`` and ``param`` + arguments are ``None``. This can occur when converting prompt + input. + """ + + is_composite: t.ClassVar[bool] = False + arity: t.ClassVar[int] = 1 + + #: the descriptive name of this type + name: str + + #: if a list of this type is expected and the value is pulled from a + #: string environment variable, this is what splits it up. `None` + #: means any whitespace. For all parameters the general rule is that + #: whitespace splits them up. The exception are paths and files which + #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on + #: Windows). + envvar_list_splitter: t.ClassVar[str | None] = None + + def to_info_dict(self) -> dict[str, t.Any]: + """Gather information that could be useful for a tool generating + user-facing documentation. + + Use :meth:`click.Context.to_info_dict` to traverse the entire + CLI structure. + + .. versionadded:: 8.0 + """ + # The class name without the "ParamType" suffix. + param_type = type(self).__name__.partition("ParamType")[0] + param_type = param_type.partition("ParameterType")[0] + + # Custom subclasses might not remember to set a name. + if hasattr(self, "name"): + name = self.name + else: + name = param_type + + return {"param_type": param_type, "name": name} + + def __call__( + self, + value: t.Any, + param: Parameter | None = None, + ctx: Context | None = None, + ) -> t.Any: + if value is not None: + return self.convert(value, param, ctx) + + def get_metavar(self, param: Parameter, ctx: Context) -> str | None: + """Returns the metavar default for this param if it provides one.""" + + def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None: + """Optionally might return extra information about a missing + parameter. + + .. versionadded:: 2.0 + """ + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + """Convert the value to the correct type. This is not called if + the value is ``None`` (the missing value). + + This must accept string values from the command line, as well as + values that are already the correct type. It may also convert + other compatible types. + + The ``param`` and ``ctx`` arguments may be ``None`` in certain + situations, such as when converting prompt input. + + If the value cannot be converted, call :meth:`fail` with a + descriptive message. + + :param value: The value to convert. + :param param: The parameter that is using this type to convert + its value. May be ``None``. + :param ctx: The current context that arrived at this value. May + be ``None``. + """ + return value + + def split_envvar_value(self, rv: str) -> cabc.Sequence[str]: + """Given a value from an environment variable this splits it up + into small chunks depending on the defined envvar list splitter. + + If the splitter is set to `None`, which means that whitespace splits, + then leading and trailing whitespace is ignored. Otherwise, leading + and trailing splitters usually lead to empty items being included. + """ + return (rv or "").split(self.envvar_list_splitter) + + def fail( + self, + message: str, + param: Parameter | None = None, + ctx: Context | None = None, + ) -> t.NoReturn: + """Helper method to fail with an invalid value message.""" + raise BadParameter(message, ctx=ctx, param=param) + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Return a list of + :class:`~click.shell_completion.CompletionItem` objects for the + incomplete value. Most types do not provide completions, but + some do, and this allows custom types to provide custom + completions as well. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + return [] + + +class CompositeParamType(ParamType): + is_composite = True + + @property + def arity(self) -> int: # type: ignore + raise NotImplementedError() + + +class FuncParamType(ParamType): + def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None: + self.name: str = func.__name__ + self.func = func + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["func"] = self.func + return info_dict + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + try: + return self.func(value) + except ValueError: + try: + value = str(value) + except UnicodeError: + value = value.decode("utf-8", "replace") + + self.fail(value, param, ctx) + + +class UnprocessedParamType(ParamType): + name = "text" + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + return value + + def __repr__(self) -> str: + return "UNPROCESSED" + + +class StringParamType(ParamType): + name = "text" + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + if isinstance(value, bytes): + enc = _get_argv_encoding() + try: + value = value.decode(enc) + except UnicodeError: + fs_enc = sys.getfilesystemencoding() + if fs_enc != enc: + try: + value = value.decode(fs_enc) + except UnicodeError: + value = value.decode("utf-8", "replace") + else: + value = value.decode("utf-8", "replace") + return value + return str(value) + + def __repr__(self) -> str: + return "STRING" + + +class Choice(ParamType, t.Generic[ParamTypeValue]): + """The choice type allows a value to be checked against a fixed set + of supported values. + + You may pass any iterable value which will be converted to a tuple + and thus will only be iterated once. + + The resulting value will always be one of the originally passed choices. + See :meth:`normalize_choice` for more info on the mapping of strings + to choices. See :ref:`choice-opts` for an example. + + :param case_sensitive: Set to false to make choices case + insensitive. Defaults to true. + + .. versionchanged:: 8.2.0 + Non-``str`` ``choices`` are now supported. It can additionally be any + iterable. Before you were not recommended to pass anything but a list or + tuple. + + .. versionadded:: 8.2.0 + Choice normalization can be overridden via :meth:`normalize_choice`. + """ + + name = "choice" + + def __init__( + self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True + ) -> None: + self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices) + self.case_sensitive = case_sensitive + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["choices"] = self.choices + info_dict["case_sensitive"] = self.case_sensitive + return info_dict + + def _normalized_mapping( + self, ctx: Context | None = None + ) -> cabc.Mapping[ParamTypeValue, str]: + """ + Returns mapping where keys are the original choices and the values are + the normalized values that are accepted via the command line. + + This is a simple wrapper around :meth:`normalize_choice`, use that + instead which is supported. + """ + return { + choice: self.normalize_choice( + choice=choice, + ctx=ctx, + ) + for choice in self.choices + } + + def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str: + """ + Normalize a choice value, used to map a passed string to a choice. + Each choice must have a unique normalized value. + + By default uses :meth:`Context.token_normalize_func` and if not case + sensitive, convert it to a casefolded value. + + .. versionadded:: 8.2.0 + """ + normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice) + + if ctx is not None and ctx.token_normalize_func is not None: + normed_value = ctx.token_normalize_func(normed_value) + + if not self.case_sensitive: + normed_value = normed_value.casefold() + + return normed_value + + def get_metavar(self, param: Parameter, ctx: Context) -> str | None: + if param.param_type_name == "option" and not param.show_choices: # type: ignore + choice_metavars = [ + convert_type(type(choice)).name.upper() for choice in self.choices + ] + choices_str = "|".join([*dict.fromkeys(choice_metavars)]) + else: + choices_str = "|".join( + [str(i) for i in self._normalized_mapping(ctx=ctx).values()] + ) + + # Use curly braces to indicate a required argument. + if param.required and param.param_type_name == "argument": + return f"{{{choices_str}}}" + + # Use square braces to indicate an option or optional argument. + return f"[{choices_str}]" + + def get_missing_message(self, param: Parameter, ctx: Context | None) -> str: + """ + Message shown when no choice is passed. + + .. versionchanged:: 8.2.0 Added ``ctx`` argument. + """ + return _("Choose from:\n\t{choices}").format( + choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values()) + ) + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> ParamTypeValue: + """ + For a given value from the parser, normalize it and find its + matching normalized value in the list of choices. Then return the + matched "original" choice. + """ + normed_value = self.normalize_choice(choice=value, ctx=ctx) + normalized_mapping = self._normalized_mapping(ctx=ctx) + + try: + return next( + original + for original, normalized in normalized_mapping.items() + if normalized == normed_value + ) + except StopIteration: + self.fail( + self.get_invalid_choice_message(value=value, ctx=ctx), + param=param, + ctx=ctx, + ) + + def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str: + """Get the error message when the given choice is invalid. + + :param value: The invalid value. + + .. versionadded:: 8.2 + """ + choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values())) + return ngettext( + "{value!r} is not {choice}.", + "{value!r} is not one of {choices}.", + len(self.choices), + ).format(value=value, choice=choices_str, choices=choices_str) + + def __repr__(self) -> str: + return f"Choice({list(self.choices)})" + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Complete choices that start with the incomplete value. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + str_choices = map(str, self.choices) + + if self.case_sensitive: + matched = (c for c in str_choices if c.startswith(incomplete)) + else: + incomplete = incomplete.lower() + matched = (c for c in str_choices if c.lower().startswith(incomplete)) + + return [CompletionItem(c) for c in matched] + + +class DateTime(ParamType): + """The DateTime type converts date strings into `datetime` objects. + + The format strings which are checked are configurable, but default to some + common (non-timezone aware) ISO 8601 formats. + + When specifying *DateTime* formats, you should only pass a list or a tuple. + Other iterables, like generators, may lead to surprising results. + + The format strings are processed using ``datetime.strptime``, and this + consequently defines the format strings which are allowed. + + Parsing is tried using each format, in order, and the first format which + parses successfully is used. + + :param formats: A list or tuple of date format strings, in the order in + which they should be tried. Defaults to + ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, + ``'%Y-%m-%d %H:%M:%S'``. + """ + + name = "datetime" + + def __init__(self, formats: cabc.Sequence[str] | None = None): + self.formats: cabc.Sequence[str] = formats or [ + "%Y-%m-%d", + "%Y-%m-%dT%H:%M:%S", + "%Y-%m-%d %H:%M:%S", + ] + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["formats"] = self.formats + return info_dict + + def get_metavar(self, param: Parameter, ctx: Context) -> str | None: + return f"[{'|'.join(self.formats)}]" + + def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None: + try: + return datetime.strptime(value, format) + except ValueError: + return None + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + if isinstance(value, datetime): + return value + + for format in self.formats: + converted = self._try_to_convert_date(value, format) + + if converted is not None: + return converted + + formats_str = ", ".join(map(repr, self.formats)) + self.fail( + ngettext( + "{value!r} does not match the format {format}.", + "{value!r} does not match the formats {formats}.", + len(self.formats), + ).format(value=value, format=formats_str, formats=formats_str), + param, + ctx, + ) + + def __repr__(self) -> str: + return "DateTime" + + +class _NumberParamTypeBase(ParamType): + _number_class: t.ClassVar[type[t.Any]] + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + try: + return self._number_class(value) + except ValueError: + self.fail( + _("{value!r} is not a valid {number_type}.").format( + value=value, number_type=self.name + ), + param, + ctx, + ) + + +class _NumberRangeBase(_NumberParamTypeBase): + def __init__( + self, + min: float | None = None, + max: float | None = None, + min_open: bool = False, + max_open: bool = False, + clamp: bool = False, + ) -> None: + self.min = min + self.max = max + self.min_open = min_open + self.max_open = max_open + self.clamp = clamp + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict.update( + min=self.min, + max=self.max, + min_open=self.min_open, + max_open=self.max_open, + clamp=self.clamp, + ) + return info_dict + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + import operator + + rv = super().convert(value, param, ctx) + lt_min: bool = self.min is not None and ( + operator.le if self.min_open else operator.lt + )(rv, self.min) + gt_max: bool = self.max is not None and ( + operator.ge if self.max_open else operator.gt + )(rv, self.max) + + if self.clamp: + if lt_min: + return self._clamp(self.min, 1, self.min_open) # type: ignore + + if gt_max: + return self._clamp(self.max, -1, self.max_open) # type: ignore + + if lt_min or gt_max: + self.fail( + _("{value} is not in the range {range}.").format( + value=rv, range=self._describe_range() + ), + param, + ctx, + ) + + return rv + + def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: + """Find the valid value to clamp to bound in the given + direction. + + :param bound: The boundary value. + :param dir: 1 or -1 indicating the direction to move. + :param open: If true, the range does not include the bound. + """ + raise NotImplementedError + + def _describe_range(self) -> str: + """Describe the range for use in help text.""" + if self.min is None: + op = "<" if self.max_open else "<=" + return f"x{op}{self.max}" + + if self.max is None: + op = ">" if self.min_open else ">=" + return f"x{op}{self.min}" + + lop = "<" if self.min_open else "<=" + rop = "<" if self.max_open else "<=" + return f"{self.min}{lop}x{rop}{self.max}" + + def __repr__(self) -> str: + clamp = " clamped" if self.clamp else "" + return f"<{type(self).__name__} {self._describe_range()}{clamp}>" + + +class IntParamType(_NumberParamTypeBase): + name = "integer" + _number_class = int + + def __repr__(self) -> str: + return "INT" + + +class IntRange(_NumberRangeBase, IntParamType): + """Restrict an :data:`click.INT` value to a range of accepted + values. See :ref:`ranges`. + + If ``min`` or ``max`` are not passed, any value is accepted in that + direction. If ``min_open`` or ``max_open`` are enabled, the + corresponding boundary is not included in the range. + + If ``clamp`` is enabled, a value outside the range is clamped to the + boundary instead of failing. + + .. versionchanged:: 8.0 + Added the ``min_open`` and ``max_open`` parameters. + """ + + name = "integer range" + + def _clamp( # type: ignore + self, bound: int, dir: t.Literal[1, -1], open: bool + ) -> int: + if not open: + return bound + + return bound + dir + + +class FloatParamType(_NumberParamTypeBase): + name = "float" + _number_class = float + + def __repr__(self) -> str: + return "FLOAT" + + +class FloatRange(_NumberRangeBase, FloatParamType): + """Restrict a :data:`click.FLOAT` value to a range of accepted + values. See :ref:`ranges`. + + If ``min`` or ``max`` are not passed, any value is accepted in that + direction. If ``min_open`` or ``max_open`` are enabled, the + corresponding boundary is not included in the range. + + If ``clamp`` is enabled, a value outside the range is clamped to the + boundary instead of failing. This is not supported if either + boundary is marked ``open``. + + .. versionchanged:: 8.0 + Added the ``min_open`` and ``max_open`` parameters. + """ + + name = "float range" + + def __init__( + self, + min: float | None = None, + max: float | None = None, + min_open: bool = False, + max_open: bool = False, + clamp: bool = False, + ) -> None: + super().__init__( + min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp + ) + + if (min_open or max_open) and clamp: + raise TypeError("Clamping is not supported for open bounds.") + + def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: + if not open: + return bound + + # Could use math.nextafter here, but clamping an + # open float range doesn't seem to be particularly useful. It's + # left up to the user to write a callback to do it if needed. + raise RuntimeError("Clamping is not supported for open bounds.") + + +class BoolParamType(ParamType): + name = "boolean" + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + if value in {False, True}: + return bool(value) + + norm = value.strip().lower() + + if norm in {"1", "true", "t", "yes", "y", "on"}: + return True + + if norm in {"0", "false", "f", "no", "n", "off"}: + return False + + self.fail( + _("{value!r} is not a valid boolean.").format(value=value), param, ctx + ) + + def __repr__(self) -> str: + return "BOOL" + + +class UUIDParameterType(ParamType): + name = "uuid" + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + import uuid + + if isinstance(value, uuid.UUID): + return value + + value = value.strip() + + try: + return uuid.UUID(value) + except ValueError: + self.fail( + _("{value!r} is not a valid UUID.").format(value=value), param, ctx + ) + + def __repr__(self) -> str: + return "UUID" + + +class File(ParamType): + """Declares a parameter to be a file for reading or writing. The file + is automatically closed once the context tears down (after the command + finished working). + + Files can be opened for reading or writing. The special value ``-`` + indicates stdin or stdout depending on the mode. + + By default, the file is opened for reading text data, but it can also be + opened in binary mode or for writing. The encoding parameter can be used + to force a specific encoding. + + The `lazy` flag controls if the file should be opened immediately or upon + first IO. The default is to be non-lazy for standard input and output + streams as well as files opened for reading, `lazy` otherwise. When opening a + file lazily for reading, it is still opened temporarily for validation, but + will not be held open until first IO. lazy is mainly useful when opening + for writing to avoid creating the file until it is needed. + + Files can also be opened atomically in which case all writes go into a + separate file in the same folder and upon completion the file will + be moved over to the original location. This is useful if a file + regularly read by other users is modified. + + See :ref:`file-args` for more information. + + .. versionchanged:: 2.0 + Added the ``atomic`` parameter. + """ + + name = "filename" + envvar_list_splitter: t.ClassVar[str] = os.path.pathsep + + def __init__( + self, + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + ) -> None: + self.mode = mode + self.encoding = encoding + self.errors = errors + self.lazy = lazy + self.atomic = atomic + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict.update(mode=self.mode, encoding=self.encoding) + return info_dict + + def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool: + if self.lazy is not None: + return self.lazy + if os.fspath(value) == "-": + return False + elif "w" in self.mode: + return True + return False + + def convert( + self, + value: str | os.PathLike[str] | t.IO[t.Any], + param: Parameter | None, + ctx: Context | None, + ) -> t.IO[t.Any]: + if _is_file_like(value): + return value + + value = t.cast("str | os.PathLike[str]", value) + + try: + lazy = self.resolve_lazy_flag(value) + + if lazy: + lf = LazyFile( + value, self.mode, self.encoding, self.errors, atomic=self.atomic + ) + + if ctx is not None: + ctx.call_on_close(lf.close_intelligently) + + return t.cast("t.IO[t.Any]", lf) + + f, should_close = open_stream( + value, self.mode, self.encoding, self.errors, atomic=self.atomic + ) + + # If a context is provided, we automatically close the file + # at the end of the context execution (or flush out). If a + # context does not exist, it's the caller's responsibility to + # properly close the file. This for instance happens when the + # type is used with prompts. + if ctx is not None: + if should_close: + ctx.call_on_close(safecall(f.close)) + else: + ctx.call_on_close(safecall(f.flush)) + + return f + except OSError as e: + self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx) + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Return a special completion marker that tells the completion + system to use the shell to provide file path completions. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + return [CompletionItem(incomplete, type="file")] + + +def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]: + return hasattr(value, "read") or hasattr(value, "write") + + +class Path(ParamType): + """The ``Path`` type is similar to the :class:`File` type, but + returns the filename instead of an open file. Various checks can be + enabled to validate the type of file and permissions. + + :param exists: The file or directory needs to exist for the value to + be valid. If this is not set to ``True``, and the file does not + exist, then all further checks are silently skipped. + :param file_okay: Allow a file as a value. + :param dir_okay: Allow a directory as a value. + :param readable: if true, a readable check is performed. + :param writable: if true, a writable check is performed. + :param executable: if true, an executable check is performed. + :param resolve_path: Make the value absolute and resolve any + symlinks. A ``~`` is not expanded, as this is supposed to be + done by the shell only. + :param allow_dash: Allow a single dash as a value, which indicates + a standard stream (but does not open it). Use + :func:`~click.open_file` to handle opening this value. + :param path_type: Convert the incoming path value to this type. If + ``None``, keep Python's default, which is ``str``. Useful to + convert to :class:`pathlib.Path`. + + .. versionchanged:: 8.1 + Added the ``executable`` parameter. + + .. versionchanged:: 8.0 + Allow passing ``path_type=pathlib.Path``. + + .. versionchanged:: 6.0 + Added the ``allow_dash`` parameter. + """ + + envvar_list_splitter: t.ClassVar[str] = os.path.pathsep + + def __init__( + self, + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: type[t.Any] | None = None, + executable: bool = False, + ): + self.exists = exists + self.file_okay = file_okay + self.dir_okay = dir_okay + self.readable = readable + self.writable = writable + self.executable = executable + self.resolve_path = resolve_path + self.allow_dash = allow_dash + self.type = path_type + + if self.file_okay and not self.dir_okay: + self.name: str = _("file") + elif self.dir_okay and not self.file_okay: + self.name = _("directory") + else: + self.name = _("path") + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict.update( + exists=self.exists, + file_okay=self.file_okay, + dir_okay=self.dir_okay, + writable=self.writable, + readable=self.readable, + allow_dash=self.allow_dash, + ) + return info_dict + + def coerce_path_result( + self, value: str | os.PathLike[str] + ) -> str | bytes | os.PathLike[str]: + if self.type is not None and not isinstance(value, self.type): + if self.type is str: + return os.fsdecode(value) + elif self.type is bytes: + return os.fsencode(value) + else: + return t.cast("os.PathLike[str]", self.type(value)) + + return value + + def convert( + self, + value: str | os.PathLike[str], + param: Parameter | None, + ctx: Context | None, + ) -> str | bytes | os.PathLike[str]: + rv = value + + is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-") + + if not is_dash: + if self.resolve_path: + rv = os.path.realpath(rv) + + try: + st = os.stat(rv) + except OSError: + if not self.exists: + return self.coerce_path_result(rv) + self.fail( + _("{name} {filename!r} does not exist.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if not self.file_okay and stat.S_ISREG(st.st_mode): + self.fail( + _("{name} {filename!r} is a file.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + if not self.dir_okay and stat.S_ISDIR(st.st_mode): + self.fail( + _("{name} {filename!r} is a directory.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if self.readable and not os.access(rv, os.R_OK): + self.fail( + _("{name} {filename!r} is not readable.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if self.writable and not os.access(rv, os.W_OK): + self.fail( + _("{name} {filename!r} is not writable.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + if self.executable and not os.access(value, os.X_OK): + self.fail( + _("{name} {filename!r} is not executable.").format( + name=self.name.title(), filename=format_filename(value) + ), + param, + ctx, + ) + + return self.coerce_path_result(rv) + + def shell_complete( + self, ctx: Context, param: Parameter, incomplete: str + ) -> list[CompletionItem]: + """Return a special completion marker that tells the completion + system to use the shell to provide path completions for only + directories or any paths. + + :param ctx: Invocation context for this command. + :param param: The parameter that is requesting completion. + :param incomplete: Value being completed. May be empty. + + .. versionadded:: 8.0 + """ + from click.shell_completion import CompletionItem + + type = "dir" if self.dir_okay and not self.file_okay else "file" + return [CompletionItem(incomplete, type=type)] + + +class Tuple(CompositeParamType): + """The default behavior of Click is to apply a type on a value directly. + This works well in most cases, except for when `nargs` is set to a fixed + count and different types should be used for different items. In this + case the :class:`Tuple` type can be used. This type can only be used + if `nargs` is set to a fixed number. + + For more information see :ref:`tuple-type`. + + This can be selected by using a Python tuple literal as a type. + + :param types: a list of types that should be used for the tuple items. + """ + + def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None: + self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types] + + def to_info_dict(self) -> dict[str, t.Any]: + info_dict = super().to_info_dict() + info_dict["types"] = [t.to_info_dict() for t in self.types] + return info_dict + + @property + def name(self) -> str: # type: ignore + return f"<{' '.join(ty.name for ty in self.types)}>" + + @property + def arity(self) -> int: # type: ignore + return len(self.types) + + def convert( + self, value: t.Any, param: Parameter | None, ctx: Context | None + ) -> t.Any: + len_type = len(self.types) + len_value = len(value) + + if len_value != len_type: + self.fail( + ngettext( + "{len_type} values are required, but {len_value} was given.", + "{len_type} values are required, but {len_value} were given.", + len_value, + ).format(len_type=len_type, len_value=len_value), + param=param, + ctx=ctx, + ) + + return tuple( + ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False) + ) + + +def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType: + """Find the most appropriate :class:`ParamType` for the given Python + type. If the type isn't provided, it can be inferred from a default + value. + """ + guessed_type = False + + if ty is None and default is not None: + if isinstance(default, (tuple, list)): + # If the default is empty, ty will remain None and will + # return STRING. + if default: + item = default[0] + + # A tuple of tuples needs to detect the inner types. + # Can't call convert recursively because that would + # incorrectly unwind the tuple to a single type. + if isinstance(item, (tuple, list)): + ty = tuple(map(type, item)) + else: + ty = type(item) + else: + ty = type(default) + + guessed_type = True + + if isinstance(ty, tuple): + return Tuple(ty) + + if isinstance(ty, ParamType): + return ty + + if ty is str or ty is None: + return STRING + + if ty is int: + return INT + + if ty is float: + return FLOAT + + if ty is bool: + return BOOL + + if guessed_type: + return STRING + + if __debug__: + try: + if issubclass(ty, ParamType): + raise AssertionError( + f"Attempted to use an uninstantiated parameter type ({ty})." + ) + except TypeError: + # ty is an instance (correct), so issubclass fails. + pass + + return FuncParamType(ty) + + +#: A dummy parameter type that just does nothing. From a user's +#: perspective this appears to just be the same as `STRING` but +#: internally no string conversion takes place if the input was bytes. +#: This is usually useful when working with file paths as they can +#: appear in bytes and unicode. +#: +#: For path related uses the :class:`Path` type is a better choice but +#: there are situations where an unprocessed type is useful which is why +#: it is is provided. +#: +#: .. versionadded:: 4.0 +UNPROCESSED = UnprocessedParamType() + +#: A unicode string parameter type which is the implicit default. This +#: can also be selected by using ``str`` as type. +STRING = StringParamType() + +#: An integer parameter. This can also be selected by using ``int`` as +#: type. +INT = IntParamType() + +#: A floating point value parameter. This can also be selected by using +#: ``float`` as type. +FLOAT = FloatParamType() + +#: A boolean parameter. This is the default for boolean flags. This can +#: also be selected by using ``bool`` as a type. +BOOL = BoolParamType() + +#: A UUID parameter. +UUID = UUIDParameterType() + + +class OptionHelpExtra(t.TypedDict, total=False): + envvars: tuple[str, ...] + default: str + range: str + required: str diff --git a/miniconda3/lib/python3.13/site-packages/click/utils.py b/miniconda3/lib/python3.13/site-packages/click/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2fe5889cee75d559092442696f9b23bf20ebfb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/click/utils.py @@ -0,0 +1,627 @@ +from __future__ import annotations + +import collections.abc as cabc +import os +import re +import sys +import typing as t +from functools import update_wrapper +from types import ModuleType +from types import TracebackType + +from ._compat import _default_text_stderr +from ._compat import _default_text_stdout +from ._compat import _find_binary_writer +from ._compat import auto_wrap_for_ansi +from ._compat import binary_streams +from ._compat import open_stream +from ._compat import should_strip_ansi +from ._compat import strip_ansi +from ._compat import text_streams +from ._compat import WIN +from .globals import resolve_color_default + +if t.TYPE_CHECKING: + import typing_extensions as te + + P = te.ParamSpec("P") + +R = t.TypeVar("R") + + +def _posixify(name: str) -> str: + return "-".join(name.split()).lower() + + +def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]: + """Wraps a function so that it swallows exceptions.""" + + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: + try: + return func(*args, **kwargs) + except Exception: + pass + return None + + return update_wrapper(wrapper, func) + + +def make_str(value: t.Any) -> str: + """Converts a value into a valid string.""" + if isinstance(value, bytes): + try: + return value.decode(sys.getfilesystemencoding()) + except UnicodeError: + return value.decode("utf-8", "replace") + return str(value) + + +def make_default_short_help(help: str, max_length: int = 45) -> str: + """Returns a condensed version of help string.""" + # Consider only the first paragraph. + paragraph_end = help.find("\n\n") + + if paragraph_end != -1: + help = help[:paragraph_end] + + # Collapse newlines, tabs, and spaces. + words = help.split() + + if not words: + return "" + + # The first paragraph started with a "no rewrap" marker, ignore it. + if words[0] == "\b": + words = words[1:] + + total_length = 0 + last_index = len(words) - 1 + + for i, word in enumerate(words): + total_length += len(word) + (i > 0) + + if total_length > max_length: # too long, truncate + break + + if word[-1] == ".": # sentence end, truncate without "..." + return " ".join(words[: i + 1]) + + if total_length == max_length and i != last_index: + break # not at sentence end, truncate with "..." + else: + return " ".join(words) # no truncation needed + + # Account for the length of the suffix. + total_length += len("...") + + # remove words until the length is short enough + while i > 0: + total_length -= len(words[i]) + (i > 0) + + if total_length <= max_length: + break + + i -= 1 + + return " ".join(words[:i]) + "..." + + +class LazyFile: + """A lazy file works like a regular file but it does not fully open + the file but it does perform some basic checks early to see if the + filename parameter does make sense. This is useful for safely opening + files for writing. + """ + + def __init__( + self, + filename: str | os.PathLike[str], + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + atomic: bool = False, + ): + self.name: str = os.fspath(filename) + self.mode = mode + self.encoding = encoding + self.errors = errors + self.atomic = atomic + self._f: t.IO[t.Any] | None + self.should_close: bool + + if self.name == "-": + self._f, self.should_close = open_stream(filename, mode, encoding, errors) + else: + if "r" in mode: + # Open and close the file in case we're opening it for + # reading so that we can catch at least some errors in + # some cases early. + open(filename, mode).close() + self._f = None + self.should_close = True + + def __getattr__(self, name: str) -> t.Any: + return getattr(self.open(), name) + + def __repr__(self) -> str: + if self._f is not None: + return repr(self._f) + return f"" + + def open(self) -> t.IO[t.Any]: + """Opens the file if it's not yet open. This call might fail with + a :exc:`FileError`. Not handling this error will produce an error + that Click shows. + """ + if self._f is not None: + return self._f + try: + rv, self.should_close = open_stream( + self.name, self.mode, self.encoding, self.errors, atomic=self.atomic + ) + except OSError as e: + from .exceptions import FileError + + raise FileError(self.name, hint=e.strerror) from e + self._f = rv + return rv + + def close(self) -> None: + """Closes the underlying file, no matter what.""" + if self._f is not None: + self._f.close() + + def close_intelligently(self) -> None: + """This function only closes the file if it was opened by the lazy + file wrapper. For instance this will never close stdin. + """ + if self.should_close: + self.close() + + def __enter__(self) -> LazyFile: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close_intelligently() + + def __iter__(self) -> cabc.Iterator[t.AnyStr]: + self.open() + return iter(self._f) # type: ignore + + +class KeepOpenFile: + def __init__(self, file: t.IO[t.Any]) -> None: + self._file: t.IO[t.Any] = file + + def __getattr__(self, name: str) -> t.Any: + return getattr(self._file, name) + + def __enter__(self) -> KeepOpenFile: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + tb: TracebackType | None, + ) -> None: + pass + + def __repr__(self) -> str: + return repr(self._file) + + def __iter__(self) -> cabc.Iterator[t.AnyStr]: + return iter(self._file) + + +def echo( + message: t.Any | None = None, + file: t.IO[t.Any] | None = None, + nl: bool = True, + err: bool = False, + color: bool | None = None, +) -> None: + """Print a message and newline to stdout or a file. This should be + used instead of :func:`print` because it provides better support + for different data, files, and environments. + + Compared to :func:`print`, this does the following: + + - Ensures that the output encoding is not misconfigured on Linux. + - Supports Unicode in the Windows console. + - Supports writing to binary outputs, and supports writing bytes + to text outputs. + - Supports colors and styles on Windows. + - Removes ANSI color and style codes if the output does not look + like an interactive terminal. + - Always flushes the output. + + :param message: The string or bytes to output. Other objects are + converted to strings. + :param file: The file to write to. Defaults to ``stdout``. + :param err: Write to ``stderr`` instead of ``stdout``. + :param nl: Print a newline after the message. Enabled by default. + :param color: Force showing or hiding colors and other styles. By + default Click will remove color if the output does not look like + an interactive terminal. + + .. versionchanged:: 6.0 + Support Unicode output on the Windows console. Click does not + modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` + will still not support Unicode. + + .. versionchanged:: 4.0 + Added the ``color`` parameter. + + .. versionadded:: 3.0 + Added the ``err`` parameter. + + .. versionchanged:: 2.0 + Support colors on Windows if colorama is installed. + """ + if file is None: + if err: + file = _default_text_stderr() + else: + file = _default_text_stdout() + + # There are no standard streams attached to write to. For example, + # pythonw on Windows. + if file is None: + return + + # Convert non bytes/text into the native string type. + if message is not None and not isinstance(message, (str, bytes, bytearray)): + out: str | bytes | None = str(message) + else: + out = message + + if nl: + out = out or "" + if isinstance(out, str): + out += "\n" + else: + out += b"\n" + + if not out: + file.flush() + return + + # If there is a message and the value looks like bytes, we manually + # need to find the binary stream and write the message in there. + # This is done separately so that most stream types will work as you + # would expect. Eg: you can write to StringIO for other cases. + if isinstance(out, (bytes, bytearray)): + binary_file = _find_binary_writer(file) + + if binary_file is not None: + file.flush() + binary_file.write(out) + binary_file.flush() + return + + # ANSI style code support. For no message or bytes, nothing happens. + # When outputting to a file instead of a terminal, strip codes. + else: + color = resolve_color_default(color) + + if should_strip_ansi(file, color): + out = strip_ansi(out) + elif WIN: + if auto_wrap_for_ansi is not None: + file = auto_wrap_for_ansi(file, color) # type: ignore + elif not color: + out = strip_ansi(out) + + file.write(out) # type: ignore + file.flush() + + +def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO: + """Returns a system stream for byte processing. + + :param name: the name of the stream to open. Valid names are ``'stdin'``, + ``'stdout'`` and ``'stderr'`` + """ + opener = binary_streams.get(name) + if opener is None: + raise TypeError(f"Unknown standard stream '{name}'") + return opener() + + +def get_text_stream( + name: t.Literal["stdin", "stdout", "stderr"], + encoding: str | None = None, + errors: str | None = "strict", +) -> t.TextIO: + """Returns a system stream for text processing. This usually returns + a wrapped stream around a binary stream returned from + :func:`get_binary_stream` but it also can take shortcuts for already + correctly configured streams. + + :param name: the name of the stream to open. Valid names are ``'stdin'``, + ``'stdout'`` and ``'stderr'`` + :param encoding: overrides the detected default encoding. + :param errors: overrides the default error mode. + """ + opener = text_streams.get(name) + if opener is None: + raise TypeError(f"Unknown standard stream '{name}'") + return opener(encoding, errors) + + +def open_file( + filename: str | os.PathLike[str], + mode: str = "r", + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool = False, + atomic: bool = False, +) -> t.IO[t.Any]: + """Open a file, with extra behavior to handle ``'-'`` to indicate + a standard stream, lazy open on write, and atomic write. Similar to + the behavior of the :class:`~click.File` param type. + + If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is + wrapped so that using it in a context manager will not close it. + This makes it possible to use the function without accidentally + closing a standard stream: + + .. code-block:: python + + with open_file(filename) as f: + ... + + :param filename: The name or Path of the file to open, or ``'-'`` for + ``stdin``/``stdout``. + :param mode: The mode in which to open the file. + :param encoding: The encoding to decode or encode a file opened in + text mode. + :param errors: The error handling mode. + :param lazy: Wait to open the file until it is accessed. For read + mode, the file is temporarily opened to raise access errors + early, then closed until it is read again. + :param atomic: Write to a temporary file and replace the given file + on close. + + .. versionadded:: 3.0 + """ + if lazy: + return t.cast( + "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic) + ) + + f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic) + + if not should_close: + f = t.cast("t.IO[t.Any]", KeepOpenFile(f)) + + return f + + +def format_filename( + filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], + shorten: bool = False, +) -> str: + """Format a filename as a string for display. Ensures the filename can be + displayed by replacing any invalid bytes or surrogate escapes in the name + with the replacement character ``�``. + + Invalid bytes or surrogate escapes will raise an error when written to a + stream with ``errors="strict"``. This will typically happen with ``stdout`` + when the locale is something like ``en_GB.UTF-8``. + + Many scenarios *are* safe to write surrogates though, due to PEP 538 and + PEP 540, including: + + - Writing to ``stderr``, which uses ``errors="backslashreplace"``. + - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens + stdout and stderr with ``errors="surrogateescape"``. + - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. + - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. + Python opens stdout and stderr with ``errors="surrogateescape"``. + + :param filename: formats a filename for UI display. This will also convert + the filename into unicode without failing. + :param shorten: this optionally shortens the filename to strip of the + path that leads up to it. + """ + if shorten: + filename = os.path.basename(filename) + else: + filename = os.fspath(filename) + + if isinstance(filename, bytes): + filename = filename.decode(sys.getfilesystemencoding(), "replace") + else: + filename = filename.encode("utf-8", "surrogateescape").decode( + "utf-8", "replace" + ) + + return filename + + +def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str: + r"""Returns the config folder for the application. The default behavior + is to return whatever is most appropriate for the operating system. + + To give you an idea, for an app called ``"Foo Bar"``, something like + the following folders could be returned: + + Mac OS X: + ``~/Library/Application Support/Foo Bar`` + Mac OS X (POSIX): + ``~/.foo-bar`` + Unix: + ``~/.config/foo-bar`` + Unix (POSIX): + ``~/.foo-bar`` + Windows (roaming): + ``C:\Users\\AppData\Roaming\Foo Bar`` + Windows (not roaming): + ``C:\Users\\AppData\Local\Foo Bar`` + + .. versionadded:: 2.0 + + :param app_name: the application name. This should be properly capitalized + and can contain whitespace. + :param roaming: controls if the folder should be roaming or not on Windows. + Has no effect otherwise. + :param force_posix: if this is set to `True` then on any POSIX system the + folder will be stored in the home folder with a leading + dot instead of the XDG config home or darwin's + application support folder. + """ + if WIN: + key = "APPDATA" if roaming else "LOCALAPPDATA" + folder = os.environ.get(key) + if folder is None: + folder = os.path.expanduser("~") + return os.path.join(folder, app_name) + if force_posix: + return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}")) + if sys.platform == "darwin": + return os.path.join( + os.path.expanduser("~/Library/Application Support"), app_name + ) + return os.path.join( + os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), + _posixify(app_name), + ) + + +class PacifyFlushWrapper: + """This wrapper is used to catch and suppress BrokenPipeErrors resulting + from ``.flush()`` being called on broken pipe during the shutdown/final-GC + of the Python interpreter. Notably ``.flush()`` is always called on + ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any + other cleanup code, and the case where the underlying file is not a broken + pipe, all calls and attributes are proxied. + """ + + def __init__(self, wrapped: t.IO[t.Any]) -> None: + self.wrapped = wrapped + + def flush(self) -> None: + try: + self.wrapped.flush() + except OSError as e: + import errno + + if e.errno != errno.EPIPE: + raise + + def __getattr__(self, attr: str) -> t.Any: + return getattr(self.wrapped, attr) + + +def _detect_program_name( + path: str | None = None, _main: ModuleType | None = None +) -> str: + """Determine the command used to run the program, for use in help + text. If a file or entry point was executed, the file name is + returned. If ``python -m`` was used to execute a module or package, + ``python -m name`` is returned. + + This doesn't try to be too precise, the goal is to give a concise + name for help text. Files are only shown as their name without the + path. ``python`` is only shown for modules, and the full path to + ``sys.executable`` is not shown. + + :param path: The Python file being executed. Python puts this in + ``sys.argv[0]``, which is used by default. + :param _main: The ``__main__`` module. This should only be passed + during internal testing. + + .. versionadded:: 8.0 + Based on command args detection in the Werkzeug reloader. + + :meta private: + """ + if _main is None: + _main = sys.modules["__main__"] + + if not path: + path = sys.argv[0] + + # The value of __package__ indicates how Python was called. It may + # not exist if a setuptools script is installed as an egg. It may be + # set incorrectly for entry points created with pip on Windows. + # It is set to "" inside a Shiv or PEX zipapp. + if getattr(_main, "__package__", None) in {None, ""} or ( + os.name == "nt" + and _main.__package__ == "" + and not os.path.exists(path) + and os.path.exists(f"{path}.exe") + ): + # Executed a file, like "python app.py". + return os.path.basename(path) + + # Executed a module, like "python -m example". + # Rewritten by Python from "-m script" to "/path/to/script.py". + # Need to look at main module to determine how it was executed. + py_module = t.cast(str, _main.__package__) + name = os.path.splitext(os.path.basename(path))[0] + + # A submodule like "example.cli". + if name != "__main__": + py_module = f"{py_module}.{name}" + + return f"python -m {py_module.lstrip('.')}" + + +def _expand_args( + args: cabc.Iterable[str], + *, + user: bool = True, + env: bool = True, + glob_recursive: bool = True, +) -> list[str]: + """Simulate Unix shell expansion with Python functions. + + See :func:`glob.glob`, :func:`os.path.expanduser`, and + :func:`os.path.expandvars`. + + This is intended for use on Windows, where the shell does not do any + expansion. It may not exactly match what a Unix shell would do. + + :param args: List of command line arguments to expand. + :param user: Expand user home directory. + :param env: Expand environment variables. + :param glob_recursive: ``**`` matches directories recursively. + + .. versionchanged:: 8.1 + Invalid glob patterns are treated as empty expansions rather + than raising an error. + + .. versionadded:: 8.0 + + :meta private: + """ + from glob import glob + + out = [] + + for arg in args: + if user: + arg = os.path.expanduser(arg) + + if env: + arg = os.path.expandvars(arg) + + try: + matches = glob(arg, recursive=glob_recursive) + except re.error: + matches = [] + + if not matches: + out.append(arg) + else: + out.extend(matches) + + return out diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ee9fa7aac2230432fb4556f507f43c811749b632 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/METADATA @@ -0,0 +1,239 @@ +Metadata-Version: 2.4 +Name: conda +Version: 26.1.1 +Summary: OS-agnostic, system-level binary package manager. +Project-URL: changelog, https://github.com/conda/conda/blob/main/CHANGELOG.md +Project-URL: documentation, https://docs.conda.io/projects/conda/en/stable/ +Project-URL: repository, https://github.com/conda/conda +Author-email: "Anaconda, Inc." +License: BSD 3-Clause License + + Copyright (c) 2012, Anaconda, Inc. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 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 NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + --- + + Conda incorporates the following libraries into its distributed code: + + * auxlib, licensed as ISC + * frozendict, license as LGPL-3.0 +License-File: AUTHORS.md +License-File: LICENSE +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.10 +Requires-Dist: archspec>=0.2.3 +Requires-Dist: boltons>=23.0.0 +Requires-Dist: charset-normalizer +Requires-Dist: conda-package-handling>=2.2.0 +Requires-Dist: distro>=1.5.0 +Requires-Dist: frozendict>=2.4.2 +Requires-Dist: jsonpatch>=1.32 +Requires-Dist: menuinst>=2 +Requires-Dist: packaging>=23.0 +Requires-Dist: platformdirs>=3.10.0 +Requires-Dist: pluggy>=1.0.0 +Requires-Dist: pycosat>=0.6.3 +Requires-Dist: requests<3,>=2.28.0 +Requires-Dist: ruamel-yaml<0.19,>=0.11.14 +Requires-Dist: setuptools>=60.0.0 +Requires-Dist: tqdm>=4 +Requires-Dist: truststore>=0.8.0; python_version >= '3.10' +Requires-Dist: zstandard>=0.15 +Description-Content-Type: text/markdown + +[conda-logo]: https://s3.amazonaws.com/conda-dev/conda_logo.svg +[tests-badge]: https://img.shields.io/github/actions/workflow/status/conda/conda/tests.yml?branch=main&event=schedule&logo=github&label=tests +[codecov-badge]: https://img.shields.io/codecov/c/github/conda/conda/main?logo=codecov +[codspeed-badge]: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json +[release-badge]: https://img.shields.io/github/v/release/conda/conda?logo=github +[anaconda-badge]: https://img.shields.io/conda/vn/anaconda/conda?logo=anaconda +[conda-forge-badge]: https://img.shields.io/conda/vn/conda-forge/conda?logo=conda-forge +[calver-badge]: https://img.shields.io/badge/calver-YY.MM.MICRO-22bfda.svg +[gitpod]: https://gitpod.io/button/open-in-gitpod.svg + +[![Conda Logo][conda-logo]](https://github.com/conda/conda) + +[![GitHub Scheduled Tests][tests-badge]](https://github.com/conda/conda/actions/workflows/tests.yml?query=branch%3Amain+event%3Aschedule) +[![Codecov Status][codecov-badge]](https://codecov.io/gh/conda/conda/branch/main) +[![CodSpeed Performance Benchmarks][codspeed-badge]](https://codspeed.io/conda/conda) +[![CalVer Versioning][calver-badge]](https://calver.org) +
+[![GitHub Release][release-badge]](https://github.com/conda/conda/releases) +[![Anaconda Package][anaconda-badge]](https://anaconda.org/anaconda/conda) +[![conda-forge Package][conda-forge-badge]](https://anaconda.org/conda-forge/conda) + +Conda is a cross-platform, language-agnostic binary package manager. It is a +package manager used in conda distributions like [Miniforge](https://github.com/conda-forge/miniforge) +and the [Anaconda Distribution](https://www.anaconda.com/distribution/), but it may be +used for other systems as well. Conda makes environments first-class +citizens, making it easy to create independent environments even for C +libraries. The conda command line interface is written entirely in Python, +and is BSD licensed open source. + +Conda is enhanced by organizations, tools, and repositories created and managed by +the amazing members of the [conda community](https://conda.org/). Some of them +can be found [here](https://github.com/conda/conda/wiki/Conda-Community). + + +## Installation + +To bootstrap a minimal distribution, use a minimal installer such as [Miniconda](https://docs.anaconda.com/free/miniconda/) or [Miniforge](https://conda-forge.org/download/). + +Conda is also included in the [Anaconda Distribution](https://repo.anaconda.com). + +## Updating conda + +To update `conda` to the newest version, use the following command: + +``` +$ conda update --name base conda +``` + +> [!TIP] +> It is possible that `conda update` does not install the newest version +> if the existing `conda` version is far behind the current release. +> In this case, updating needs to be done in stages. +> +> For example, to update from `conda 4.12` to `conda 23.10.0`, +> `conda 22.11.1` needs to be installed first: +> +> ``` +> $ conda install --name base conda=22.11.1 +> $ conda update conda +> ``` + +## Getting Started + +If you install the Anaconda Distribution, you will already have hundreds of packages +installed. You can see what packages are installed by running: + +```bash +$ conda list +``` + +to see all the packages that are available, use: + +```bash +$ conda search +``` + +and to install a package, use + +```bash +$ conda install +``` + +The real power of conda comes from its ability to manage environments. +In conda, an environment can be thought of as a completely separate installation. +Conda installs packages into environments efficiently using [hard links](https://en.wikipedia.org/wiki/Hard_link) by default when it is possible, so +environments are space efficient, and take seconds to create. + +The default environment, which `conda` itself is installed into, is called `base`. +To create another environment, use the `conda create` command. +For instance, to create an environment with PyTorch, you would run: + +```bash +$ conda create --name ml-project pytorch +``` + +This creates an environment called `ml-project` with the latest version of PyTorch, and its dependencies. + +We can now activate this environment: + +```bash +$ conda activate ml-project +``` + +This puts the `bin` directory of the `ml-project` environment in the front of the `PATH`, +and sets it as the default environment for all subsequent conda commands. + +To go back to the base environment, use: + +```bash +$ conda deactivate +``` + +## Building Your Own Packages + +You can easily build your own packages for conda, and upload them +to [anaconda.org](https://anaconda.org), a free service for hosting +packages for conda, as well as other package managers. +To build a package, create a recipe. Package building documentation is available +[here](https://docs.conda.io/projects/conda-build/en/latest/). +See [AnacondaRecipes](https://github.com/AnacondaRecipes) for the recipes that make up the Anaconda Distribution and `defaults` channel. +[Conda-forge](https://conda-forge.org/feedstocks/) and [Bioconda](https://github.com/bioconda/bioconda-recipes) are community-driven conda-based distributions. + +To upload to anaconda.org, create an account. Then, install the +anaconda-client and login: + +```bash +$ conda install anaconda-client +$ anaconda login +``` + +Then, after you build your recipe: + +```bash +$ conda build +``` + +you will be prompted to upload to anaconda.org. + +To add your anaconda.org channel, or other's channels, to conda so +that `conda install` will find and install their packages, run: + +```bash +$ conda config --add channels https://conda.anaconda.org/username +``` + +(replacing `username` with the username of the person whose channel you want +to add). + +## Getting Help + +- [Documentation](https://docs.conda.io/projects/conda/en/latest) +- [Zulip chat](https://conda.zulipchat.com/) +- [Bluesky](https://bsky.app/profile/conda.org) +- [Bug Reports/Feature Requests](https://github.com/conda/conda/issues) +- [Installer/Package Issues](https://github.com/ContinuumIO/anaconda-issues/issues) + +## Contributing + +Contributions to conda are welcome. See the [contributing](CONTRIBUTING.md) documentation +for instructions on setting up a development environment. diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..8a6034ddb04465c842e71b507f7c5537222fe320 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/RECORD @@ -0,0 +1,475 @@ +../../../bin/conda,sha256=ifk9n2WWV8ClqWaGNFXxoRhzS2-Fy_cthEyx-a_XQB0,448 +conda-26.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda-26.1.1.dist-info/METADATA,sha256=dPouysq-PnBWygOq6SlIjSU4wEfEWahYKjwqGkqMtpY,9835 +conda-26.1.1.dist-info/RECORD,, +conda-26.1.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda-26.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +conda-26.1.1.dist-info/direct_url.json,sha256=VA3sbeRDqpyXZ038dlHEJjp4K7S8kiAtqP6aJU2CnqE,101 +conda-26.1.1.dist-info/entry_points.txt,sha256=i2OKMWwJQMdb0QjJpnyFmNqWpChIOSPrfC4vyadMo90,50 +conda-26.1.1.dist-info/licenses/AUTHORS.md,sha256=iVCVvtc7w1U7KhPrUXuU7Gvq3-gkKrRX7280Rcvz_V4,7911 +conda-26.1.1.dist-info/licenses/LICENSE,sha256=HzaVtzgJPLb2mjIQBNmZPY-bZwT_3iojygvFWXBvJAo,1638 +conda/__init__.py,sha256=Q2_2wex2U6S65y8qgebSwqCU9IrGTSFnHVnBgrrD7-E,6013 +conda/__main__.py,sha256=2FR_IlM54h7lP1TbwtdlPqHGFpGLSwOEzjW7-uCkv9M,165 +conda/__pycache__/__init__.cpython-313.pyc,, +conda/__pycache__/__main__.cpython-313.pyc,, +conda/__pycache__/_vendor.cpython-313.pyc,, +conda/__pycache__/_version.cpython-313.pyc,, +conda/__pycache__/activate.cpython-313.pyc,, +conda/__pycache__/api.cpython-313.pyc,, +conda/__pycache__/deprecations.cpython-313.pyc,, +conda/__pycache__/exception_handler.cpython-313.pyc,, +conda/__pycache__/exceptions.cpython-313.pyc,, +conda/__pycache__/exports.cpython-313.pyc,, +conda/__pycache__/history.cpython-313.pyc,, +conda/__pycache__/instructions.cpython-313.pyc,, +conda/__pycache__/misc.cpython-313.pyc,, +conda/__pycache__/plan.cpython-313.pyc,, +conda/__pycache__/reporters.cpython-313.pyc,, +conda/__pycache__/resolve.cpython-313.pyc,, +conda/__pycache__/utils.cpython-313.pyc,, +conda/_vendor.py,sha256=z3U462TQqDIrgEb_bVO3n0HgO2ZzKqIDTgLB7ppahQM,197 +conda/_version.py,sha256=zli0x26kPLV1BXRVu_m7wzRRkHFLR2QX1LAi22HLVEU,706 +conda/activate.py,sha256=QLq2xoZKiUmG9JXlo1ILPBI6qrQbbOIf2CpbnMibn-8,44267 +conda/api.py,sha256=wN_4orjNOd4Ty6nnRHH93AYrRzw3o9akQu6LvMQNUa8,17522 +conda/auxlib/LICENSE,sha256=JweyjAPYaVmBvTE10tfsPfV29-IYkrtMWAaZL3MSVh4,802 +conda/auxlib/__init__.py,sha256=JlKX85n2J6iX4flo9n1XXWjkzaMVo0ocPsua6X7NgoE,3042 +conda/auxlib/__pycache__/__init__.cpython-313.pyc,, +conda/auxlib/__pycache__/collection.cpython-313.pyc,, +conda/auxlib/__pycache__/compat.cpython-313.pyc,, +conda/auxlib/__pycache__/decorators.cpython-313.pyc,, +conda/auxlib/__pycache__/entity.cpython-313.pyc,, +conda/auxlib/__pycache__/exceptions.cpython-313.pyc,, +conda/auxlib/__pycache__/ish.cpython-313.pyc,, +conda/auxlib/__pycache__/logz.cpython-313.pyc,, +conda/auxlib/__pycache__/type_coercion.cpython-313.pyc,, +conda/auxlib/collection.py,sha256=APwSFGy5xotgOGJTyjlFVRPz_bRhKszb0HPUCXcjjqE,1941 +conda/auxlib/compat.py,sha256=NYtjb6ECJPchBfVGDMnw4M_FxLNFETDlxBcsFHCi9bI,1352 +conda/auxlib/decorators.py,sha256=ebhm_M7O92h8E0ElZ1c5m4GYmnEz2lELvMv_LJiNpNM,6388 +conda/auxlib/entity.py,sha256=jTd8ViUPSITJbLiZQEcuDdI78Cd79nIb5tXPdZC4pq4,33626 +conda/auxlib/exceptions.py,sha256=tGut8GRJTZYdw2ProFnqSGkF_b_I96aszhpcIJrv9BU,901 +conda/auxlib/ish.py,sha256=bq9Pukx8xphUsc_qQH708U_ZU_rUhlNBRJ-InKGY6Q0,1964 +conda/auxlib/logz.py,sha256=vEwmZFI_LvwjWHEDvF1mxiiGG9oppf-E5oB6K0pDEhI,6089 +conda/auxlib/type_coercion.py,sha256=nvQKnhD8DEaJMuemRSrgHnRDXbOYL5UMmojQw07KPiw,8936 +conda/base/__init__.py,sha256=x4VUuXPG2qbUrJ5KZnFQDD7p1ZvnHsL8G5RuEqTsYxY,520 +conda/base/__pycache__/__init__.cpython-313.pyc,, +conda/base/__pycache__/constants.cpython-313.pyc,, +conda/base/__pycache__/context.cpython-313.pyc,, +conda/base/constants.py,sha256=iNL2mygxJYKVFLafQIcOrXJ6UrHVkx9JcAFJcS2Lt5M,11874 +conda/base/context.py,sha256=cU_rR7Id-98bkJy64byOI9ZmiOsd021V2x5KL22-F-k,90605 +conda/cli/__init__.py,sha256=DkuX3aN6mu_d2Qyx0z0l_783Y4ZTzL64HyeQ6sF7AY8,106 +conda/cli/__pycache__/__init__.cpython-313.pyc,, +conda/cli/__pycache__/actions.cpython-313.pyc,, +conda/cli/__pycache__/common.cpython-313.pyc,, +conda/cli/__pycache__/conda_argparse.cpython-313.pyc,, +conda/cli/__pycache__/condarc.cpython-313.pyc,, +conda/cli/__pycache__/find_commands.cpython-313.pyc,, +conda/cli/__pycache__/helpers.cpython-313.pyc,, +conda/cli/__pycache__/install.cpython-313.pyc,, +conda/cli/__pycache__/main.cpython-313.pyc,, +conda/cli/__pycache__/main_clean.cpython-313.pyc,, +conda/cli/__pycache__/main_commands.cpython-313.pyc,, +conda/cli/__pycache__/main_compare.cpython-313.pyc,, +conda/cli/__pycache__/main_config.cpython-313.pyc,, +conda/cli/__pycache__/main_create.cpython-313.pyc,, +conda/cli/__pycache__/main_env.cpython-313.pyc,, +conda/cli/__pycache__/main_env_config.cpython-313.pyc,, +conda/cli/__pycache__/main_env_create.cpython-313.pyc,, +conda/cli/__pycache__/main_env_list.cpython-313.pyc,, +conda/cli/__pycache__/main_env_remove.cpython-313.pyc,, +conda/cli/__pycache__/main_env_update.cpython-313.pyc,, +conda/cli/__pycache__/main_env_vars.cpython-313.pyc,, +conda/cli/__pycache__/main_export.cpython-313.pyc,, +conda/cli/__pycache__/main_info.cpython-313.pyc,, +conda/cli/__pycache__/main_init.cpython-313.pyc,, +conda/cli/__pycache__/main_install.cpython-313.pyc,, +conda/cli/__pycache__/main_list.cpython-313.pyc,, +conda/cli/__pycache__/main_mock_activate.cpython-313.pyc,, +conda/cli/__pycache__/main_mock_deactivate.cpython-313.pyc,, +conda/cli/__pycache__/main_notices.cpython-313.pyc,, +conda/cli/__pycache__/main_package.cpython-313.pyc,, +conda/cli/__pycache__/main_pip.cpython-313.pyc,, +conda/cli/__pycache__/main_remove.cpython-313.pyc,, +conda/cli/__pycache__/main_rename.cpython-313.pyc,, +conda/cli/__pycache__/main_run.cpython-313.pyc,, +conda/cli/__pycache__/main_search.cpython-313.pyc,, +conda/cli/__pycache__/main_update.cpython-313.pyc,, +conda/cli/actions.py,sha256=-2G1HfcO7BW5JMKYlg1FyUfXumugY7xIKD2enVDXd9s,1673 +conda/cli/common.py,sha256=-ENiR15ygyWxfVkMLLtH-bU6Ftvr1OHvcKWdksNN7KA,12015 +conda/cli/conda_argparse.py,sha256=2Cl5v-NeUC3dFCRV88ko9WzawYVXmEcnE2Xiw11kY4w,13428 +conda/cli/condarc.py,sha256=3413pzjTk6061FkHzD-y7TUFgAYg_cYOYirkMOghOLY,20023 +conda/cli/find_commands.py,sha256=IImE12iwOXHSh61hkeu7rnFq8nj4nUbVSiTr4dyPk4A,2596 +conda/cli/helpers.py,sha256=qRvzO2mNCfkG6FzEZ6RPPxLGu_LmuG6o4ZN8pCbhoXA,20580 +conda/cli/install.py,sha256=mqgchwYNaD4LvYjibe-qBo22QOVT1WhEO4lpZFbGA_E,21706 +conda/cli/main.py,sha256=HpdLRjCzqcv8uSjlCZDe_qO7dFZ5QSHnAzLI4kcveSI,3527 +conda/cli/main_clean.py,sha256=X62utCiU1AJ0Q8DF1xpvql690s5FFHdRQCwzlA7noAc,12202 +conda/cli/main_commands.py,sha256=YEuLYFl5RKmMydtGy0AlOuugUk5lyRx_Ho40fNWhrGU,1120 +conda/cli/main_compare.py,sha256=jtyA9O5zsTlaT7AbUMwRXCL8uzgcmWHpoP-AGwzizEc,4119 +conda/cli/main_config.py,sha256=2kSITQhX2gnjRK6VoFr2gbOLuOOu2gjXoLvzIt8RbNU,26554 +conda/cli/main_create.py,sha256=f3ycWtpICumaMQRjTyccuhlygrwpV9ZaWfQncqKr8vg,5861 +conda/cli/main_env.py,sha256=DIfhSFDec8vc8MyhVXSc3qJvaWU5F7okSl_lSEykKz4,1239 +conda/cli/main_env_config.py,sha256=0flWw1EFTuhoHiHjQc0YsSBcKgGLemDorlskWOgYTk8,1167 +conda/cli/main_env_create.py,sha256=UwnDAvxHOb0e63C4_8Qsc5kECJ1bWKfd6P9c7fkILpU,6704 +conda/cli/main_env_list.py,sha256=s0P-ZWbcGIDZXJVrqC86MQ-NpBxvjOIjr6VhrQ99YlI,1333 +conda/cli/main_env_remove.py,sha256=bRyZzx2Q_pE7sGNKy53_EMhxX2Et4oE9Lfb6utujAkk,1505 +conda/cli/main_env_update.py,sha256=n_cN4UQw1fOgBJqw5GnPnJL6llETAFfhPB_MkClFaYw,5686 +conda/cli/main_env_vars.py,sha256=Vpm5yCP5VbJenejI3v-wnkPdOUgYmL-oL6rXphBsQlU,4623 +conda/cli/main_export.py,sha256=w6W68fWrGVe5DWhwVnk6F5YZbgFwwv5l6ukcRUfxKTs,7081 +conda/cli/main_info.py,sha256=HGizaVvmm92Qi4Ig3sS7SA7Ybk2aYn2K_v7nvVC6rQM,19555 +conda/cli/main_init.py,sha256=CFOBRgkmE8l5FMm-gG6RW0_31wxmMgUHyvVFo7_jqV8,6192 +conda/cli/main_install.py,sha256=onN18JEbbTfW9epssy83hOXBBxrbJpmCD6oWN8XFvag,5725 +conda/cli/main_list.py,sha256=BKTdWy_-jtT8yi95211opM0uZlm9C_6_z-UZDm2ImuE,12858 +conda/cli/main_mock_activate.py,sha256=QvVDdvO3x4DF-adTZzAmSzO5oaASQ8Ka0NTmJX64xSU,893 +conda/cli/main_mock_deactivate.py,sha256=atOwd6Ufhfbqf6hdUhGkWJLSjyPEJmZhGInc2z8haT4,823 +conda/cli/main_notices.py,sha256=y_HWkFN5k-sl6u443sfDCBXYF7lgZr--mS8UkcfdD8M,1666 +conda/cli/main_package.py,sha256=JqJTLg_K4GbdJqpf-wcKBfPrYgwJRHK1NBrKh82xhec,8743 +conda/cli/main_pip.py,sha256=34ltgt1y2cnmkta7PH0ORo-wvCnUj-W7sufwIkr8u30,872 +conda/cli/main_remove.py,sha256=Z7DWuqJoojCaeCCsU_AmjH6GRLFYMWWaSBTNfENiYSE,7722 +conda/cli/main_rename.py,sha256=D_wm4_q65zHNhJ7cxTQI9hHagqogHqeREapVeFw6ZaM,5665 +conda/cli/main_run.py,sha256=LOy0oXHTX1LfIBTNNPABFyvnapIqnxErIWhVgiYGVoA,4697 +conda/cli/main_search.py,sha256=XbXRuhB82iC62zkg5Ru6SSxq00-sOibnerIKQFQNUvU,10437 +conda/cli/main_update.py,sha256=NJkLab64brc1hi6-0Af15LdB4rMK3Uovp4CidNbzMbQ,3962 +conda/common/__init__.py,sha256=L4D64etjtKML2s_v1lAescFsHOLo59Hy1vmbCXu8MWQ,494 +conda/common/__pycache__/__init__.cpython-313.pyc,, +conda/common/__pycache__/_logic.cpython-313.pyc,, +conda/common/__pycache__/compat.cpython-313.pyc,, +conda/common/__pycache__/configuration.cpython-313.pyc,, +conda/common/__pycache__/constants.cpython-313.pyc,, +conda/common/__pycache__/io.cpython-313.pyc,, +conda/common/__pycache__/iterators.cpython-313.pyc,, +conda/common/__pycache__/logic.cpython-313.pyc,, +conda/common/__pycache__/signals.cpython-313.pyc,, +conda/common/__pycache__/toposort.cpython-313.pyc,, +conda/common/__pycache__/url.cpython-313.pyc,, +conda/common/_logic.py,sha256=XN58SBEqr4DknUVDNTpyvnkTsBOJylC__H7yTW5SW2Y,27446 +conda/common/_os/__init__.py,sha256=cRSBZvZv1CNufTFh1Umwc6kPdZL8XBdeW__d5sWzkyo,436 +conda/common/_os/__pycache__/__init__.cpython-313.pyc,, +conda/common/_os/__pycache__/linux.cpython-313.pyc,, +conda/common/_os/__pycache__/osx.cpython-313.pyc,, +conda/common/_os/__pycache__/unix.cpython-313.pyc,, +conda/common/_os/__pycache__/windows.cpython-313.pyc,, +conda/common/_os/linux.py,sha256=M6WRLM7xg-_bdiDQn2G8KoDpMlL3PKjfr4Rr2mHqH3k,2053 +conda/common/_os/osx.py,sha256=saOdjucF997z2NqLWZtgreBw7QyVr1QPyQj16RthKwY,742 +conda/common/_os/unix.py,sha256=3CtSycesTuZvW1-RyVIOHKflAube51kuhpE4zyQxrtg,353 +conda/common/_os/windows.py,sha256=v7EdkAoYy_c-slRftV183uWgsts8AEJfa3OovNnUHfM,5496 +conda/common/compat.py,sha256=GVs3hyAi78D_zsc0zCuddL7EH0mNK52pjWYjRxwH7mI,3071 +conda/common/configuration.py,sha256=7xLT4CF3LGJS0OFF4OilW4_MP_yxsN2p5NFXqjxYkMY,64743 +conda/common/constants.py,sha256=7_84KD-o_ynHgWi585MyQiO7R59OA6ir4qHUOj_3SI8,589 +conda/common/io.py,sha256=ZPMoxLgljgurdoSf7jJ8XBf0Js6zfTFJXECcxVgwWLQ,17176 +conda/common/iterators.py,sha256=CaBL-LeCuC7SRpnnsksbi7ACsGfoeqv3RdFi7AhtrV4,1107 +conda/common/logic.py,sha256=aAXlesrY2PBuiuW4KkqiG_X35JNj7ZQUAxazEiVa1PE,11114 +conda/common/path/__init__.py,sha256=BBqIz_wVZZbTesvcHGqzEbeSS64ERQMJngSKA4-h7QI,6207 +conda/common/path/__pycache__/__init__.cpython-313.pyc,, +conda/common/path/__pycache__/_cygpath.cpython-313.pyc,, +conda/common/path/__pycache__/directories.cpython-313.pyc,, +conda/common/path/__pycache__/python.cpython-313.pyc,, +conda/common/path/__pycache__/windows.cpython-313.pyc,, +conda/common/path/_cygpath.py,sha256=zO7RLyGZipH7Xh1j0aKaUj5K3QBbe5nK8Vnr3ccqM48,7046 +conda/common/path/directories.py,sha256=MeM1hKS3eMntg4IlSW2HU52xC4sbMw--0-tsKnzG_Ms,1675 +conda/common/path/python.py,sha256=8Rh5DK5LxdzqCWdv03S3LtvEnMnshxRCKUQb9M6g5Po,4275 +conda/common/path/windows.py,sha256=IFZuuEYJnBBlMhkWaluL8OTghtwaECIM-GLQJexAVFo,5444 +conda/common/pkg_formats/__init__.py,sha256=PeVza2KsTmy4DSq8qe9IjJe3jw8J5WpY0_LVI7MtRow,201 +conda/common/pkg_formats/__pycache__/__init__.cpython-313.pyc,, +conda/common/pkg_formats/__pycache__/python.cpython-313.pyc,, +conda/common/pkg_formats/python.py,sha256=tIhnl6PoliqKnwgdRrTjtX1EumfWCa8Sz6AiFUaV5cU,1083 +conda/common/serialize/__init__.py,sha256=8Fbb9_pLXstw7BddIYsNnm2zYr2X9o-D8E8ivRa8hIE,2655 +conda/common/serialize/__pycache__/__init__.cpython-313.pyc,, +conda/common/serialize/__pycache__/json.cpython-313.pyc,, +conda/common/serialize/__pycache__/yaml.cpython-313.pyc,, +conda/common/serialize/json.py,sha256=VIxLM1D_6rwu0MioZJdKGPuedxb8cSJUq78xoRVF5FQ,2750 +conda/common/serialize/yaml.py,sha256=z1kyQ-3uv5sVEryvvEKD19beAUbvAwrIYC9HaZMO0e8,2903 +conda/common/signals.py,sha256=a7er8UB5MFO8v1cxw41ZLNzU0KLcR1Y2vFf5eLeZnzI,1788 +conda/common/toposort.py,sha256=jaT1bsNO7nTradJogvPdq9QX-aBQQMzF4gQTjCnv-gE,3288 +conda/common/url.py,sha256=0P6jx_dzQoQp-hnAsKwB3IdfWFb1m9rhzkvWBqNlzvA,15626 +conda/core/__init__.py,sha256=JLaLQ6HLYXkAiCNfoI5_oNpD7MF_dV24dCw6-CSP3S0,698 +conda/core/__pycache__/__init__.cpython-313.pyc,, +conda/core/__pycache__/envs_manager.cpython-313.pyc,, +conda/core/__pycache__/index.cpython-313.pyc,, +conda/core/__pycache__/initialize.cpython-313.pyc,, +conda/core/__pycache__/link.cpython-313.pyc,, +conda/core/__pycache__/package_cache_data.cpython-313.pyc,, +conda/core/__pycache__/path_actions.cpython-313.pyc,, +conda/core/__pycache__/portability.cpython-313.pyc,, +conda/core/__pycache__/prefix_data.cpython-313.pyc,, +conda/core/__pycache__/solve.cpython-313.pyc,, +conda/core/__pycache__/subdir_data.cpython-313.pyc,, +conda/core/envs_manager.py,sha256=fZxc3FNwqi2r4lHWGwbWdc3Ct48uazagpHv8m0_5i7I,7699 +conda/core/index.py,sha256=jKkKlRoIcR_DbvZQyZWhdMpIim6IEMMvCsHqqm-Tng8,26666 +conda/core/initialize.py,sha256=Iy_2GhuB1fOQD3IFz7vutwskbMBF8FQHzBtK1Dyijbc,80730 +conda/core/link.py,sha256=Hrm8sTfVB6EIWfu4cY3A5dSrkqmCz7j0AU-p8P7mk68,64734 +conda/core/package_cache_data.py,sha256=qKUvckY3nbvqKoiKf2Q9Zn502jB_d86gpmGESuOx8Zk,40492 +conda/core/path_actions.py,sha256=AiB9GFnKo33mXkowwO2wI9KYfNPYAPvcHs2uAUMtvYs,53228 +conda/core/portability.py,sha256=btWAzco3Y-riaZxiEgTdh9YUAqL1obZzVQrDGZIGm1U,16066 +conda/core/prefix_data.py,sha256=rRswbE-qcwDxGriR6jPYZszFVOoDto3amh-FLjUFR8Y,33559 +conda/core/solve.py,sha256=Hv_LyD1sZqZcpEsUAELD8wYqvwQWbYP4Pz0O1jrJoCA,62818 +conda/core/subdir_data.py,sha256=Fyb1oz80gWnw46554TGW8A7t4-iz9nZ5tSRXv-BqIxs,28754 +conda/deprecations.py,sha256=5sjJt11Grj2uDrQxzhzKCSyg2TH4dY7kClcQquwhMvo,17610 +conda/env/__init__.py,sha256=Xc6wOJSxSUQz7Z91PPbZ27WAv28rNuNGy0WSNda9uQc,75 +conda/env/__pycache__/__init__.cpython-313.pyc,, +conda/env/__pycache__/env.cpython-313.pyc,, +conda/env/__pycache__/pip_util.cpython-313.pyc,, +conda/env/env.py,sha256=kLpaqV83EwSG64yNcEaL1mDzuckIZ4NM9lYr-UVX-mY,15281 +conda/env/installers/__init__.py,sha256=Xc6wOJSxSUQz7Z91PPbZ27WAv28rNuNGy0WSNda9uQc,75 +conda/env/installers/__pycache__/__init__.cpython-313.pyc,, +conda/env/installers/__pycache__/base.cpython-313.pyc,, +conda/env/installers/__pycache__/conda.cpython-313.pyc,, +conda/env/installers/__pycache__/pip.cpython-313.pyc,, +conda/env/installers/base.py,sha256=n3aymNtgTz1sEs3Bd6Yp4YGBcvy40jSjoXbJDbgPWLs,466 +conda/env/installers/conda.py,sha256=H9E6qLbmNyONfjexWnGPl3TOyPOKBE43QYVCa_A-ziQ,5076 +conda/env/installers/pip.py,sha256=zCebxvkWSdA-3ZwpAq_Ji8WROR-wbu9bN3EDCbVtpJQ,2585 +conda/env/pip_util.py,sha256=igmRvci1WH69H9Cs15pfrW4uxH3pHbJtUPfJqI1q8HY,1420 +conda/env/specs/__init__.py,sha256=mn7CyomLGWZakOnRusTGHzwg9prKu7VMA4GuA303cy0,2482 +conda/env/specs/__pycache__/__init__.cpython-313.pyc,, +conda/env/specs/__pycache__/binstar.cpython-313.pyc,, +conda/env/specs/__pycache__/cep_24.cpython-313.pyc,, +conda/env/specs/__pycache__/explicit.cpython-313.pyc,, +conda/env/specs/__pycache__/requirements.cpython-313.pyc,, +conda/env/specs/__pycache__/yaml_file.cpython-313.pyc,, +conda/env/specs/binstar.py,sha256=CDq5Lh6Jp0EOntGPMJhdJ_ZixDH3J7YG0cYY6v9orww,241 +conda/env/specs/cep_24.py,sha256=UpLY2onzlPKm7q_QN3yx-hvtO0ITCuFF1BPLtnFvaoo,1924 +conda/env/specs/explicit.py,sha256=ypKWMVPRY6APy2EZKhtjOJGgxfUjUco37wAmsN-yGLc,2263 +conda/env/specs/requirements.py,sha256=8Tny8qi1XAQER-q-fQ8pR1rk_PGGHgTnnkwgUXI1ang,5123 +conda/env/specs/yaml_file.py,sha256=r2dSHemjZ1mZedbGn_x0Pwd0EZCr0tEdYP8llLt5Iww,2687 +conda/exception_handler.py,sha256=R-meQ93yBKJrUUO1hKgQ4poqPpxY3T1wJ6-CkeZ75xo,15218 +conda/exceptions.py,sha256=rVzw3wSP6HNtdn_-WTiI1iPVcIMm7QN1b5mjQxqkH9M,49298 +conda/exports.py,sha256=y9BQ6nLLZpKd58vX1nwKnHjE_jwLWJ1ZDPvCMgdK-sc,9472 +conda/gateways/__init__.py,sha256=nGB6VGny0Pmr87aFRZJt_jv4FZmUVp3L3PBxvf2dONQ,732 +conda/gateways/__pycache__/__init__.cpython-313.pyc,, +conda/gateways/__pycache__/anaconda_client.cpython-313.pyc,, +conda/gateways/__pycache__/logging.cpython-313.pyc,, +conda/gateways/__pycache__/subprocess.cpython-313.pyc,, +conda/gateways/anaconda_client.py,sha256=XmlnbyRj45H12lnsRMHA9Uq18h7VdQcnM0tTo7a6D7o,1893 +conda/gateways/connection/__init__.py,sha256=EF2jMXXPZKDeSHkKmT-pUnq_YR_lj08bd08WkNNyDNA,973 +conda/gateways/connection/__pycache__/__init__.cpython-313.pyc,, +conda/gateways/connection/__pycache__/download.cpython-313.pyc,, +conda/gateways/connection/__pycache__/session.cpython-313.pyc,, +conda/gateways/connection/adapters/__init__.py,sha256=Xc6wOJSxSUQz7Z91PPbZ27WAv28rNuNGy0WSNda9uQc,75 +conda/gateways/connection/adapters/__pycache__/__init__.cpython-313.pyc,, +conda/gateways/connection/adapters/__pycache__/ftp.cpython-313.pyc,, +conda/gateways/connection/adapters/__pycache__/http.cpython-313.pyc,, +conda/gateways/connection/adapters/__pycache__/localfs.cpython-313.pyc,, +conda/gateways/connection/adapters/__pycache__/s3.cpython-313.pyc,, +conda/gateways/connection/adapters/ftp.py,sha256=4VYeQ1cyGki2RJ0gXigEbucGkZHM8m35hv-ht4X06Es,9554 +conda/gateways/connection/adapters/http.py,sha256=xRxsRkwaHqpq5BHiLGzsWxQiT76gWGZ5npFSnND7Cz4,2825 +conda/gateways/connection/adapters/localfs.py,sha256=7MdYuRJFybr7I5IrUk-QMO2CxHLDOetq3T2-oLBNkN0,1821 +conda/gateways/connection/adapters/s3.py,sha256=g1Vt_6NJ_wurVIaj_gO5oTpKGIXf07Mmz42f8tkcRdI,3308 +conda/gateways/connection/download.py,sha256=ssi99wnvvp68fsgdIGMUHouCapuhGQJhCCcRj_EtBoM,16245 +conda/gateways/connection/session.py,sha256=C584RPldGOe2rYMkXEGhqcpkbnYkP7kr6lRlYT0EoxQ,14754 +conda/gateways/disk/__init__.py,sha256=1FIK1_eBng0XtJ95nIj9qonndsPNtM9kFcMbBHylAA8,3575 +conda/gateways/disk/__pycache__/__init__.cpython-313.pyc,, +conda/gateways/disk/__pycache__/create.cpython-313.pyc,, +conda/gateways/disk/__pycache__/delete.cpython-313.pyc,, +conda/gateways/disk/__pycache__/link.cpython-313.pyc,, +conda/gateways/disk/__pycache__/lock.cpython-313.pyc,, +conda/gateways/disk/__pycache__/permissions.cpython-313.pyc,, +conda/gateways/disk/__pycache__/read.cpython-313.pyc,, +conda/gateways/disk/__pycache__/test.cpython-313.pyc,, +conda/gateways/disk/__pycache__/update.cpython-313.pyc,, +conda/gateways/disk/create.py,sha256=TVN-1muegqSWpr7Cc5Nh9Gjcx9t_SkoAHalhsilNFRo,16465 +conda/gateways/disk/delete.py,sha256=yNynZ08_AbXp36evbkvnMteQm1IN6mk4SVfNyVZBjIA,10187 +conda/gateways/disk/link.py,sha256=F4UQQBRh2RzOW-zs-RvHTHEvaQ-YAqdWHT_hc9dsRIY,13614 +conda/gateways/disk/lock.py,sha256=E6FXGnkwd2nn-IY22eSYuTFyMTs3whAsMe2LsVTBFvU,2856 +conda/gateways/disk/permissions.py,sha256=yAOWFjeI9bmXUKQzHOWAdyfkdvnUlxtBg3FsY_XKpog,3057 +conda/gateways/disk/read.py,sha256=JarRL13NdvTARC6pN4ADaf28bVbMBI0X3cv7meEN0lo,8495 +conda/gateways/disk/test.py,sha256=3VhyYVpZIhvg0pjju6L_-7UQ9MKSt8vGaUSdl37CmVU,3420 +conda/gateways/disk/update.py,sha256=0SVJ3MQQLgqEH-Jt_XYwWt8i5qFhLPI3Bk8TDLXznrM,6150 +conda/gateways/logging.py,sha256=9mlAwBSy-oo7fEVAENEHFd4RO71TLRNwU5eix5vRpeI,7384 +conda/gateways/repodata/__init__.py,sha256=wSDjKJ-Ol4xMrUmGVBu5BCGPJ5QYsJHLPJ4s0guzlO8,33792 +conda/gateways/repodata/__pycache__/__init__.cpython-313.pyc,, +conda/gateways/repodata/__pycache__/lock.cpython-313.pyc,, +conda/gateways/repodata/jlap/__init__.py,sha256=ClUn_wwlAxu9PuxnDidDZV_S-KDQsLA2aYVdwIw0Qzo,138 +conda/gateways/repodata/jlap/__pycache__/__init__.cpython-313.pyc,, +conda/gateways/repodata/jlap/__pycache__/core.cpython-313.pyc,, +conda/gateways/repodata/jlap/__pycache__/fetch.cpython-313.pyc,, +conda/gateways/repodata/jlap/__pycache__/interface.cpython-313.pyc,, +conda/gateways/repodata/jlap/core.py,sha256=4-zcI0we_C0MDv2fme_jJ7OWe9N1ZBXL27ORtodoWvs,4146 +conda/gateways/repodata/jlap/fetch.py,sha256=hdskf1KV9qZd7XpB-FxyVcik7xnETVKlADLP3ky4q2Y,16284 +conda/gateways/repodata/jlap/interface.py,sha256=V9_4QC_Iq5XL5BTjeTJBnrjyqSkDJlDAdJ3dostsFDs,4659 +conda/gateways/repodata/lock.py,sha256=K8QRj_0au17Ozx7WKc-9Fu2ci5PAvNxkQoNesvKSCqc,195 +conda/gateways/subprocess.py,sha256=9F8XQUcHBB1wTiDi00ntLyS75YrpfFarrG4i0H3R5a4,4846 +conda/history.py,sha256=AVpl9FibV3c2XGQ7QYxTZ_faTIhQLdZ-dLfzCPh_RxE,15693 +conda/instructions.py,sha256=QbSD5GjLh2QnWN2xjrHJ7Nr_tD0NNVEsFk8TpOHGr9A,2769 +conda/misc.py,sha256=IvYJINZvYbNiJxPjoWAUSGcHzOI3XQ6fKoPnX-7xxIE,12628 +conda/models/__init__.py,sha256=3LnN1LhlKAdCERPdWTMimFGYNYSzFAtF3S7JJzeNGcg,685 +conda/models/__pycache__/__init__.cpython-313.pyc,, +conda/models/__pycache__/channel.cpython-313.pyc,, +conda/models/__pycache__/dist.cpython-313.pyc,, +conda/models/__pycache__/enums.cpython-313.pyc,, +conda/models/__pycache__/environment.cpython-313.pyc,, +conda/models/__pycache__/match_spec.cpython-313.pyc,, +conda/models/__pycache__/package_info.cpython-313.pyc,, +conda/models/__pycache__/prefix_graph.cpython-313.pyc,, +conda/models/__pycache__/records.cpython-313.pyc,, +conda/models/__pycache__/version.cpython-313.pyc,, +conda/models/channel.py,sha256=swYUXSgj0tNzYqm19-4ogrSca-InhMR-nysMx0ghj2A,24371 +conda/models/dist.py,sha256=NViRx6xFI5oomfbnT9Ps46UlMyt9Jd52UaKYbaSoYo0,12093 +conda/models/enums.py,sha256=enz1jNBFHc08lpmQi89gME564ONmCowZaZhPXL2ODDQ,4884 +conda/models/environment.py,sha256=FdBorQmkjoj7vtKr1V9xbRqiVdrJIp1j39CVYfNFyQc,21553 +conda/models/match_spec.py,sha256=khpcHkualGfaOY9YeLRD-YxOl0t6k2pmtiEiF5nOG-E,43607 +conda/models/package_info.py,sha256=PhFu10iyInC0dzt7v_okEh6wXFftKU7XzXI1lzW7VHI,2257 +conda/models/prefix_graph.py,sha256=6AxnQZnpHAEwJ3ZhCyXE0GldDvfR8g2Ai2Bd1B_PZOk,16633 +conda/models/records.py,sha256=l4nO-HSnxJu90ufiU5O_8M1hmH4zF4We6qss6Vo4rHo,24239 +conda/models/version.py,sha256=YXMB0Rnu_LzIn8-yPBuLMiU4I0wonqJqObVJgFPMrDQ,26182 +conda/notices/__init__.py,sha256=qZejFJsNxj8WzUycGz1CnTwDKjSIMLk2qmIXJQiF-NU,115 +conda/notices/__pycache__/__init__.cpython-313.pyc,, +conda/notices/__pycache__/cache.cpython-313.pyc,, +conda/notices/__pycache__/core.cpython-313.pyc,, +conda/notices/__pycache__/fetch.cpython-313.pyc,, +conda/notices/__pycache__/types.cpython-313.pyc,, +conda/notices/__pycache__/views.cpython-313.pyc,, +conda/notices/cache.py,sha256=nWlxj-uZXg3DvaDC-cVxIS0hRflCIfocms7w3Xf5gGQ,5231 +conda/notices/core.py,sha256=XrGZ4zA10c0EE5DuaU2Tm3Im0L0NCMT01J7sQLRVyCM,7170 +conda/notices/fetch.py,sha256=nSnrTMZ8veuUnGQ-sywtWG8v41AoweBkyKrkkvj4e-M,2607 +conda/notices/types.py,sha256=-Wz3ikqyMAQ6_HtXXpQF7eTZLPoCbzeabHhShSDuaAo,3631 +conda/notices/views.py,sha256=EerPVSennF1abV_Xks_NZCI_VAaZ79tuMDzaht-cJ38,2040 +conda/plan.py,sha256=Jnf4yxMDBgkMGcecgPOOWA_1o-0owx9LrMG4f-i5884,5678 +conda/plugins/__init__.py,sha256=guYmeJ8-9xk7TV9Fl4s3T_s-zYRkwcioJ7K-HtKAhCA,3955 +conda/plugins/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/__pycache__/config.cpython-313.pyc,, +conda/plugins/__pycache__/hookspec.cpython-313.pyc,, +conda/plugins/__pycache__/manager.cpython-313.pyc,, +conda/plugins/__pycache__/solvers.cpython-313.pyc,, +conda/plugins/__pycache__/types.cpython-313.pyc,, +conda/plugins/config.py,sha256=r-tab7jcI18aDT9ARhp60NDxoMIsqPyL6AzEpM2_yD4,4294 +conda/plugins/environment_exporters/__init__.py,sha256=Mn6hopuxj57k3HiE9ZGWWi_jYdbpE5eKMxBnpb2a6Oc,326 +conda/plugins/environment_exporters/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/environment_exporters/__pycache__/environment_yml.cpython-313.pyc,, +conda/plugins/environment_exporters/__pycache__/explicit.cpython-313.pyc,, +conda/plugins/environment_exporters/__pycache__/requirements_txt.cpython-313.pyc,, +conda/plugins/environment_exporters/environment_yml.py,sha256=AAmKkx9QmAscqFkaR3-2bW7078wJaxoAZdqzAvgw30Y,3738 +conda/plugins/environment_exporters/explicit.py,sha256=EnBldjck9e0DB2st_Xz2acNX5kXJ9_xnfQajpWse89A,3574 +conda/plugins/environment_exporters/requirements_txt.py,sha256=5h_FmUQ9ZhkkoCQn-4wLRmrMySMA0fRlVjZGFbtUMxw,2197 +conda/plugins/environment_specifiers/__init__.py,sha256=3VXIblGv0UoN97guytGN6CPu0iukygbVM7LG6WN6dYI,364 +conda/plugins/environment_specifiers/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/environment_specifiers/__pycache__/cep_24.cpython-313.pyc,, +conda/plugins/environment_specifiers/__pycache__/environment_yml.cpython-313.pyc,, +conda/plugins/environment_specifiers/__pycache__/explicit.cpython-313.pyc,, +conda/plugins/environment_specifiers/__pycache__/requirements_txt.cpython-313.pyc,, +conda/plugins/environment_specifiers/cep_24.py,sha256=55itTvzAl8RMgOdnTXRoRzxEqOGe8ZCatpxsR3g2xlE,454 +conda/plugins/environment_specifiers/environment_yml.py,sha256=fODwplvMbMqR5-ms9Ycpsx9Ae1zBb2vGh1_4MfBQODs,456 +conda/plugins/environment_specifiers/explicit.py,sha256=rNm3jFmaCPcwctwURoQW3omdh23mU9n7rUzCTGOy5fc,426 +conda/plugins/environment_specifiers/requirements_txt.py,sha256=us-fxuqBYujBX5I3sDNNUbQcOKnyP5R9sVJGsl7AiXw,454 +conda/plugins/hookspec.py,sha256=WD2GkuXQlXVlLHtuQwPN8xM6hSMi5zOOzaVxBdv9WTc,24661 +conda/plugins/manager.py,sha256=k4fO38vR0woc0Bxbu_C7YY9iK52EYlajKvTtcOerfgw,35020 +conda/plugins/package_extractors/__init__.py,sha256=AlXLPDZVxlJ3exyjjs4FrOPCQDA5ZzdJMeP3eDExRP0,148 +conda/plugins/package_extractors/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/package_extractors/__pycache__/conda.cpython-313.pyc,, +conda/plugins/package_extractors/conda.py,sha256=Vu-yqWGMdHw0EYkkUrV4fDxVznlwZmw_Lj2cYtLgYVE,2503 +conda/plugins/post_solves/__init__.py,sha256=okGqcsGXCNX5kc8HWc2nTFLwrAVubbuHETEcc7I6yeY,285 +conda/plugins/post_solves/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/post_solves/__pycache__/signature_verification.cpython-313.pyc,, +conda/plugins/post_solves/signature_verification.py,sha256=LCO1i-_4fSqWioNdjH6AUCfRDDj9dbqWhbQ0rMULBYM,761 +conda/plugins/prefix_data_loaders/__init__.py,sha256=w3WDOPuwTxVfPhG7jOqYmWY6tvRYK7qPUlZyF13vAJQ,112 +conda/plugins/prefix_data_loaders/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/prefix_data_loaders/pypi/__init__.py,sha256=nevdkxAtLAYX_j65g1gAQpLWl4FQOnCjVLiAM9WIpkw,6353 +conda/plugins/prefix_data_loaders/pypi/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/prefix_data_loaders/pypi/__pycache__/pkg_format.cpython-313.pyc,, +conda/plugins/prefix_data_loaders/pypi/pkg_format.py,sha256=cij6eFV0ol_mYW2WWhqaVKPSb2HRzDdUktqx5O1zAdE,48895 +conda/plugins/reporter_backends/__init__.py,sha256=ry9SFj-ie-bsYej1T7XeKJ2YRzQWagQY4vvDiNfmMnE,130 +conda/plugins/reporter_backends/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/reporter_backends/__pycache__/console.cpython-313.pyc,, +conda/plugins/reporter_backends/__pycache__/json.cpython-313.pyc,, +conda/plugins/reporter_backends/console.py,sha256=zhrRKhSAZbXsmla3U45453Mqu80RT0ZW7BRvT28Gwr4,8597 +conda/plugins/reporter_backends/json.py,sha256=d2HZHXyisliOO129zJmjusj7dfR21tdjs7whmoOLwcc,3552 +conda/plugins/solvers.py,sha256=lZ99mLvog0oX0S2vs1SgfF9mIeRCITrVxse6qr9ilZc,496 +conda/plugins/subcommands/__init__.py,sha256=D9JxxKjbqbK4AZcm8eJnfJJjr4Aw4AodquXQaRjQCMs,116 +conda/plugins/subcommands/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/subcommands/doctor/__init__.py,sha256=AQISE_iDfIvSRM7EHAvoQE8HaRoZJ6Cd0aflkw6-8PM,4516 +conda/plugins/subcommands/doctor/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__init__.py,sha256=-loNJSufygQGC-4rBFhucQo6oX9H83NTDz6KH0dYK7w,656 +conda/plugins/subcommands/doctor/health_checks/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__pycache__/altered_files.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__pycache__/consistency.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__pycache__/environment_txt.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__pycache__/file_locking.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__pycache__/missing_files.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__pycache__/pinned.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/__pycache__/requests_ca_bundle.cpython-313.pyc,, +conda/plugins/subcommands/doctor/health_checks/altered_files.py,sha256=WfvE1JvsjtiCaaFuOphkQ7CuH6XdRfy6pFs8n6cMWOM,3871 +conda/plugins/subcommands/doctor/health_checks/consistency.py,sha256=o-0vWWgEzmXbqJQQa6_MRm0Kwpxzv2c0p40EIANREvk,4652 +conda/plugins/subcommands/doctor/health_checks/environment_txt.py,sha256=Gfb1LdbvoXS_02HBzgP8CauXozfBM2AMl7VrgwaeEmM,2757 +conda/plugins/subcommands/doctor/health_checks/file_locking.py,sha256=jaTbCb18LOyB7FVtLrS5fbmKKxhFwLxMzJoDEAkXKs0,1202 +conda/plugins/subcommands/doctor/health_checks/missing_files.py,sha256=woOoReBPhI6lzw7zBmgBlw3Q3U9HQcZjY3qnjTsUZIM,3031 +conda/plugins/subcommands/doctor/health_checks/pinned.py,sha256=SuLobGBw0pBaoEZAAWB1s6rcPCBxu0sxIweUigbNgPg,4080 +conda/plugins/subcommands/doctor/health_checks/requests_ca_bundle.py,sha256=kg7A_ymiQKqnI88WO8H9PsvoXRC34FGOGBF47zSbNb8,1893 +conda/plugins/types.py,sha256=TyNC27S7JHgaen-_uwg-CVmxAPNF_iy91axgKvcYofg,22039 +conda/plugins/virtual_packages/__init__.py,sha256=5xFFWXkcLptae63gkhH8Ya1XbLAAG-ww_A1TKMxloSE,321 +conda/plugins/virtual_packages/__pycache__/__init__.cpython-313.pyc,, +conda/plugins/virtual_packages/__pycache__/archspec.cpython-313.pyc,, +conda/plugins/virtual_packages/__pycache__/conda.cpython-313.pyc,, +conda/plugins/virtual_packages/__pycache__/cuda.cpython-313.pyc,, +conda/plugins/virtual_packages/__pycache__/freebsd.cpython-313.pyc,, +conda/plugins/virtual_packages/__pycache__/linux.cpython-313.pyc,, +conda/plugins/virtual_packages/__pycache__/osx.cpython-313.pyc,, +conda/plugins/virtual_packages/__pycache__/windows.cpython-313.pyc,, +conda/plugins/virtual_packages/archspec.py,sha256=vtIwgWqFlpQ9VwisfypOZBFUUOhKsbb1ukCDuRyiP3o,782 +conda/plugins/virtual_packages/conda.py,sha256=1odWmsaOvEkKJijlZlarTlVvXkwAcbwTmxzRV7kvDLg,615 +conda/plugins/virtual_packages/cuda.py,sha256=JgkmfZnuVkFc99YWH4TguptbJ-varvEcoEYQdJAdIqk,5221 +conda/plugins/virtual_packages/freebsd.py,sha256=JbHw7Rylkc22cd3Sbwmt1XueltWilE4hMcPMQiu_EGI,708 +conda/plugins/virtual_packages/linux.py,sha256=C-xd9MpVWoHw3I412PpESmuQ5gJr-pRG47sSL2OXD3M,2534 +conda/plugins/virtual_packages/osx.py,sha256=PlIuTf4zf2nCKax-wYrark33qKJ7EiZ4s-90f4utQyc,1263 +conda/plugins/virtual_packages/windows.py,sha256=G1rIfYPAO0cAhb0wR20lK09rPcFQzioiZvsfyFoOchw,1048 +conda/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda/reporters.py,sha256=S8AUE_gLFtIIffdIRgvJmBYKr6NHpNRGH-ErLX2VTnU,2787 +conda/resolve.py,sha256=Eljw-s-IxSRaTN1WE40qaeHizCyPEc9mlYUAtAseMec,69223 +conda/shell/Library/bin/conda.bat,sha256=hKsbqhMFT8BkUqiuz7WqYsXPsK0vkZD47iVh-J4Bf74,121 +conda/shell/Scripts/activate.bat,sha256=5W1-QLkOBdt8ukBOFfhcIQnEphc6XV1-tv6hI_4YLEA,1111 +conda/shell/bin/activate,sha256=RNhzx3837W_voLmBF7kPiCsZHYj8BCBgshDsgUg35C4,149 +conda/shell/bin/deactivate,sha256=jm6Z5CsrAQl1RiGZNPo2H1b2RU_6v5HQPTh88JMJk8I,237 +conda/shell/cli-32.exe,sha256=AXDdpglRnAiLHkYZoeHRWgFwGmxRS7Vfmahfy71UFjE,53016 +conda/shell/cli-64.exe,sha256=ksFczN7sw4Vsad19R_4B2Nd4K29K2h29hnkKXnAupz8,54040 +conda/shell/conda.xsh,sha256=qnsGmsr3m5s8mqQwOHnryzDkRWQxvJQy46nkSPAGgM4,7390 +conda/shell/conda_icon.ico,sha256=OdhQ1RaSD84ZdELWRVg0TxsPacDbayB7n6BCFzD1SQE,126355 +conda/shell/condabin/Conda.psm1,sha256=xwP7_p0xeULdlPuZT2ATcbuZhe9ZQZuGcx-vJP2ufWg,7731 +conda/shell/condabin/_conda_activate.bat,sha256=fMesb0Kjt5PEYUXxaBgsuWePr7mCySePtAy3KAmJM0Q,3116 +conda/shell/condabin/activate.bat,sha256=EqSYwn1ietETn45sCPAolmz3TPWmIprqHQsUIQxYViE,143 +conda/shell/condabin/conda-hook.ps1,sha256=CPhZL_Usn1Jqg5wHj5_HO2NR9OlCtlxcQwyZcYfWNV0,90 +conda/shell/condabin/conda.bat,sha256=Kw1kNMG0wMRtXCUgJ376sbDO9oNOWXjikm_6uq3X47s,729 +conda/shell/condabin/conda_auto_activate.bat,sha256=ZCmP1B6KCQ98AX8madnybnMiiKVaGD-6YyAmi2gTjJQ,715 +conda/shell/condabin/conda_hook.bat,sha256=a5BCc15kVj796u_i9Pa1mQlPPMZ7fRHI-RpeHP4Dp-c,641 +conda/shell/condabin/deactivate.bat,sha256=sQV8wQYB6RaUysTLgLFVaOWQuwobY-f6ShsbqBMS2KM,188 +conda/shell/condabin/rename_tmp.bat,sha256=6D-r8u3iWM2rUeMT5-hQ19TkKpaywVZzy4Hdq7dpNYs,149 +conda/shell/etc/fish/conf.d/conda.fish,sha256=u75-0zl1THLTJfL8gF-pmry2Gx_30Caq6NHnEPR-gqA,3444 +conda/shell/etc/profile.d/conda.csh,sha256=ymLhXdGlyDZGnHQP1CIUJ8um4b8lq_3TTPYj3KIzw5o,2022 +conda/shell/etc/profile.d/conda.sh,sha256=Zraru-9b2UMrXy_MgQrJ9Fw4wHQg88FLSd1FhNxggK8,2201 +conda/testing/__init__.py,sha256=GmEBCU47O4PCMxV6JuSSf4l8P3CH0zC-xEEacSFENnQ,2954 +conda/testing/__pycache__/__init__.cpython-313.pyc,, +conda/testing/__pycache__/cases.cpython-313.pyc,, +conda/testing/__pycache__/fixtures.cpython-313.pyc,, +conda/testing/__pycache__/helpers.cpython-313.pyc,, +conda/testing/__pycache__/http_test_server.cpython-313.pyc,, +conda/testing/__pycache__/integration.cpython-313.pyc,, +conda/testing/__pycache__/solver_helpers.cpython-313.pyc,, +conda/testing/cases.py,sha256=oEZufgaOAkmQAqVyWbKHeQ9gufW4b-wgFN0PRyTZpS0,453 +conda/testing/fixtures.py,sha256=XQ6Zpr7IgisEKQSxX6HcLJ7ons-KyrOAyrgGcz4606Q,24391 +conda/testing/gateways/__init__.py,sha256=Xc6wOJSxSUQz7Z91PPbZ27WAv28rNuNGy0WSNda9uQc,75 +conda/testing/gateways/__pycache__/__init__.cpython-313.pyc,, +conda/testing/gateways/__pycache__/fixtures.cpython-313.pyc,, +conda/testing/gateways/fixtures.py,sha256=XFVySza_IaVEAipgmvkX2koGV3FLBgmk3xMFGyxpWIU,4383 +conda/testing/helpers.py,sha256=5COnkpCamzJvVRgn8WxxGs_KnexCde-2OZpdyHbcrOo,23127 +conda/testing/http_test_server.py,sha256=1iSQujto5zynsqycLMb-FfGCEd2LCvRHCKCA4lF_gCQ,2920 +conda/testing/integration.py,sha256=lWWQ-EHU6hf-OU_rniXD814RBCG-tHsUPAY-SPBgH-0,3828 +conda/testing/notices/__init__.py,sha256=Xc6wOJSxSUQz7Z91PPbZ27WAv28rNuNGy0WSNda9uQc,75 +conda/testing/notices/__pycache__/__init__.cpython-313.pyc,, +conda/testing/notices/__pycache__/fixtures.cpython-313.pyc,, +conda/testing/notices/__pycache__/helpers.cpython-313.pyc,, +conda/testing/notices/fixtures.py,sha256=xZRj1B1aJhL56WPVpbyKmd7jZINu2Qs8i5SLKIEv1Q8,1294 +conda/testing/notices/helpers.py,sha256=4NnsyobQqmczvWH1OHObnjfyQvFL_1rnzIWLMQOlQdI,4053 +conda/testing/solver_helpers.py,sha256=J_sVEaDMUy7mlHnP0xthEmhlM3nISRB6xQn-rJkj-qg,47104 +conda/trust/__init__.py,sha256=hQHUKs8Qf-lBCCfm23taKt-U_uvDrYYRuAzMXOozwYA,274 +conda/trust/__pycache__/__init__.cpython-313.pyc,, +conda/trust/__pycache__/constants.cpython-313.pyc,, +conda/trust/__pycache__/signature_verification.cpython-313.pyc,, +conda/trust/constants.py,sha256=zlFUPQSbj97z6gNkbtRNo5a-PffCMkthzEAhe3AVK4U,2816 +conda/trust/signature_verification.py,sha256=IlpDSQhwLufgcK4IbWVMzFiLBLadIbFUDsZO34P3AG8,11540 +conda/utils.py,sha256=rapC3wPPnllTk5HLj13xCECOB1qSbD210kC5tqVvzGU,16313 +conda_env/README.md,sha256=aSlTDVqtGwv4Cc-xBZ_00WotjCZkj1912SNKHa95FBQ,2389 +conda_env/__init__.py,sha256=_MeKNchxNWv6ONduTfaHQCpkcB_mJzRkeQ97z8qE3nQ,196 +conda_env/__pycache__/__init__.cpython-313.pyc,, +conda_env/cli/__init__.py,sha256=G8ALfOi7Gn1pmAowcRFnmsU-aCif2MoEQ_v9SJ6AX9w,152 +conda_env/cli/__pycache__/__init__.cpython-313.pyc,, +conda_env/installers/__init__.py,sha256=G8ALfOi7Gn1pmAowcRFnmsU-aCif2MoEQ_v9SJ6AX9w,152 +conda_env/installers/__pycache__/__init__.cpython-313.pyc,, +tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.bat,sha256=ExRqo4kq6_IrZpUTur2J2WdoFSi-EX9MzYFC3KrOKHM,120 +tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.sh,sha256=v_2Cxyn3WEKgVKYoBEuB5WsMtdypkQ3U3SObt1jt2Yc,74 +tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.bat,sha256=5O5-sotlPKxEQyOz44t08meMxSgQ_4370db7XuwUSLQ,52 +tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.sh,sha256=4KIMhteeaC0tHmB5exM26OiFCv9uJyu2yCFj3QrnMRI,90 diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..35057da2e742a04ce914be7c0c8f607aee4c5982 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_177140125005974/croot/conda_1771402194624/work/conda-src"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..6d7da3a6e231bb52990a75097606ab894b85d227 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +conda = conda.cli.main_pip:main diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/licenses/AUTHORS.md b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/licenses/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..e2fc5f759d97e5726805021828f7f5eb8326c65a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/licenses/AUTHORS.md @@ -0,0 +1,487 @@ +All of the people who have made at least one contribution to conda. +Authors are sorted alphabetically. + +* ARF1 +* Aaron Meurer +* Abheek Mathur +* Adrian Freund +* Agriya Khetarpal +* Ahmet Deger +* Alain Domissy +* Alan Du +* Albert DeFusco +* Albert Kottke +* Alberto Gobbi +* Alex Alvarez +* Alex Hall +* Alex Liew +* Alex Wiltschko +* Ali Abbas Zaidi +* Alisue +* Almar Klein +* Amelio Vazquez-Reina +* Amir Mohammadi +* Andrea Ghensi +* Andreas Girgensohn +* Andrew Achkar +* Andrew Arendt +* Andrew M. Farrell +* Andy Kipp +* Andy R. Terrel +* Angela Gloyna +* Aniket Patil +* Anthon van der Neut +* Anthony Scopatz +* Antoine Gallix +* Antoine Prouvost +* Antony Lee +* Anže Starič +* ApurvaWavhal +* Armin Burgmeier +* Arqam Hussain +* Attila Nagy +* Aurelien Vallee +* Avalon +* Bas Nijholt +* Bastian Zimmermann +* Ben Bodenmiller +* Ben Mares +* Benedikt Wildenhain +* Benjamin Bertrand +* Benjamin Fischer +* Benjamin Wilhelm +* Benjamin Zaitlen +* Bernardo da Eira Duarte +* Bernd Jünger +* Berton Earnshaw +* Bhanuja Karumuru +* Bianca Henderson +* Billy Keyes +* Blake Nicholson +* Bocong Sui +* Bojan Delic +* Brad Erickson +* Brad Nemanich +* Brad S +* Bradley Kreider +* Brennan Chapman +* Brent Pedersen +* Brett Cannon +* Brett Randall +* Brian W. Hart +* Bruno Oliveira +* Bryan Van de Ven +* Carl Anderson +* Carlos H Brandt +* Casper da Costa-Luis +* Chawye Hsu +* Cheng H. Lee +* Chris Burr +* Chris Granade +* Chris Linton-Ford +* Chris Osborn +* Chris Tomkins-Tinch +* Christine Doig +* Christoph Buchner +* Christoph Deil +* Christoph Stich +* Christopher Barber +* Christopher Granade +* Christopher Howard +* Christopher J. Wright +* Christos Panopoulos +* ColemanTom +* Colin Brislawn +* Conda Bot +* Cong +* Connor Martin +* Crystal Soja +* Daekwon Yun +* Dainese Hsiao +* Dan Blanchard +* Dan Dascalescu +* Dan Lovell +* Dan Meador +* Dan Yeaw +* Daniel Bast +* Daniel Holth +* Daniel Hook +* Daniel Wehner +* Daniel Zeng +* Dario Curreri +* Darren Dale +* Dave +* Dave Hirschfeld +* Dave Hogue +* Dave Masino +* David Froger +* David Kent +* David Li +* David Mertz +* David Warde-Farley +* Deepyaman Datta +* Dennis George +* Derek Ludwig +* Diogo de Campos +* Duncan Macleod +* Dylan Morroll +* Dylan Orzel +* Dzianis Shpektarau +* Ed Reed +* Eli Rykoff +* Elsa Granger +* Eric Dill +* Eric Prestat +* Erik Sundell +* Erik Whiting +* Ernst Reissner +* Eugene Van den Bulke +* Evo +* Faith Rider +* Faustin Carter +* FelisNivalis +* Filipe Laíns +* Flavio Martins +* Florenz A. P. Hollebrandse +* Floris Bruynooghe +* Forrest Waters +* Frederic Bastien +* Gabe Martin-Dempesy +* Gabriel Reis +* Gayan Silva +* Geir Ove Myhr +* George Hartzell +* Giacomo Cirò +* Gil Forsyth +* Giles Cope +* Gonzalo Peña-Castellanos +* Greg Brener +* Gregor Kržmanc +* Guilherme Quentel Melo +* Guo Ci +* Hamza Sheikh +* Havoc Pennington +* Henning Schroder +* Hsin-Hsiang Peng +* Hugo Buddelmeijer +* Iain Gillis +* Ian Fitchet +* Ian Stokes-Rees +* Igor Igamberdiev +* Ikko Eltociear Ashimine +* Ilan Cosman +* Ilan Schnell +* Ilango Rajagopal +* InfiniteChai +* Isaiah Norton +* Isuru Fernando +* Ivan Smirnov +* Jacob Hultman +* Jacob Smith +* Jacopo Sabbatini +* Jacques Kvam +* Jaime Rodríguez-Guerra +* James Domingo +* James Myatt +* James Penn +* James Sexton +* James Winegar +* Jan-Benedikt Jagusch +* Jan-Philipp Igla +* Jannis Leidel +* Jason Carpenter +* Jason Grout +* Jason Vestuto +* Javier Rovegno +* Jayson Messenger +* Jeffrey Gill +* Jeremy Liu +* Jerimiah Willhite +* Jesse Hamer +* Jillian Rowe +* Joao Azevedo +* Joe D +* Joe Jevnik +* Joel Hull +* Joel Kim +* Joel Tony +* Johan Carlin +* Johannes Köster +* John Ayad +* John Flavin +* John Kirkham +* Johnny Núñez Cano +* Jonas Haag +* Jonathan J. Helmus +* Josh Mayer +* Juan Luis Cano Rodríguez +* Juan Nunez-Iglesias +* Julien Schueller +* Justin Wood (Callek) +* Justus Schwabedal +* Justyn Harriman +* Kahlil Hodgson +* Kai Tietz +* Kale Franz +* Kamil Kwiek +* Kannan Jayachandran +* Kara de la Marck +* Katherine Abrikian +* Katherine Kinnaman +* Kelvin Ou +* Ken Odegard +* Kenneth Laskoski +* Kenneth Schackart +* Kerry Watson +* Kevin Deldycke +* Kfir Zvi +* Kian-Meng Ang +* Klaus Zimmermann +* Korijn van Golen +* Kurt Wheeler +* Kyle Gerard Felker +* Larry Bradley +* Lila Hickey +* Lorcan Hamill +* Lori A. Burns +* Loïc Estève +* Luc J. Bourhis +* Luis Gutierrez +* Maggie Mari +* Mahe Iram Khan +* Majid alDosari +* Mak Sze Chun +* Maksim Rakitin +* Mandeep Bhutani +* Mansour Moufid +* Marcel Bargull +* Marcel Stimberg +* Marcelo Duarte Trevisani +* Marcin Wojdyr +* Marco Esters +* Marco Rossi +* Marcos Vanetta +* Marcus Caisey +* Mario Juric +* Mark Edzel Potane +* Mark Harfouche +* Mark Wiebe +* Markus Gerstel +* Marland Sitt +* Martin Dengler +* Martin Kou +* Martin Lang +* Martin Prüsse +* Martin Raden +* Mary M +* Matt Craig +* Matt Kramer +* Matthew Anderson +* Matthew Dillon +* Matthew Feickert +* Matthew Linebaugh +* Matthew R. Becker +* Matthew Rocklin +* Matthew Wardrop +* Matthieu Guillaumin +* Matthieu Muffato +* MatthieuDartiailh +* Matti Picus +* Maurice Meyer +* Max Reeder +* Maximilian Noethe +* Maya Gilad +* Meixu Song +* Mervin Fansler +* Michael Albert +* Michael C. Grant +* Michael Heilman +* Michael Kincaid +* Michael Marchetti +* Michael Sarahan +* Michael Wild +* Michaël Defferrard +* Michele Mastropietro +* Mickey Rose +* Mihir Rege +* Mika Fischer +* Mike Croucher +* MinRK +* Minh Phan +* Monius +* Morgan Parry +* Morten Enemark Lund +* Murray Read +* NaincyKumariKnoldus +* Nate Coraor +* Nathan Nguyen +* Navdeeppal Singh +* Nehal J Wani +* Nelson Liu +* Ni Huang +* Nicholas Blair +* Nicholas Pierotti +* Nick Eubank +* Nicky Sandhu +* Nikhil Dhandre +* Nikhil Raverkar +* Niklas Holm +* Nils Koch +* Nir Ganani +* Nitin Madnani +* Nixon Kwok +* Noah Pendleton +* Ofek Lev +* Ohad Ravid +* Oleg Samoylenko +* Oleh Khoma +* Ondřej Čertík +* Orion Poplawski +* Patricio Hubmann +* Patrick Snape +* Paul Yim +* Pavel Zwerschke +* Pete Bachant +* Peter Cable +* Peter Talley +* Peter Williams +* Peyton Murray +* Phil Elson +* Philip Thomas +* Philippe Mathieu +* Philippe Ombredanne +* Pirzada Ahmad Faraz +* Pradipta Ghosh +* Preston Moore +* Rachel Rigdon +* Rafael de Barros +* Ralf Gommers +* Rami Chowdhury +* Ramsey D'silva +* Ravi Gummadi +* Ray Donnelly +* Remi Rampin +* Riccardo Vianello +* Rich Lewis +* Richard Gowers +* Robert Johansson +* Robin +* Roger Erens +* Rollin Thomas +* Ryan Grout +* Ryan Keith +* Rüdiger Busche +* Saad Parwaiz +* Sachin G Biradar +* Sam Davis +* Sam Haese +* Sam Nicholls +* Samson Yeung +* Samuel Debionne +* Samuel Walters-Nevet +* Sanskrati +* Santi Villalba +* Santiago Castro +* Sarah Bird +* Saranya Mahalingam +* Satyam Vyas +* Sauco Cano Navarro +* Schuyler Martin +* Scott Evtuch +* Scruel Tao +* Sean Ross-Ross +* Sebastien Awwad +* Sergio Oller +* Serhii Kupriienko +* Shannon Green +* Shaun Thompson +* Shaun Walbridge +* Sidhant Bansal +* Simon Høxbro Hansen +* Simon Li +* Simon McLaren +* Skipper Seabold +* Sophia Castellarin +* Spencer Mathews +* Srivas Venkatesh +* Stan Seibert +* Stanis Shkel +* Stefaan Lippens +* Stefan Scherfke +* Stefan Seefeld +* Steffen Van +* Stephan Hoyer +* Stephen Robinson +* Steve Palmroth +* Steven Engler +* Stijn Verstraeten +* Stuart Berg +* Sumanth +* Sylvain Corlay +* Tadeu Manoel +* Tarcisio +* Teake Nutma +* Thomas Holder +* Thomas Kluyver +* Thomas Lam +* Thomas Wiecki +* Thorsten Beier +* Théo Segonds +* Tian Zhang +* Tianchen Zhong +* Tim Gates +* Tim Hoffmann +* Tim Hopper +* Tim Snyder +* Tobias Megies +* Tom Hu +* Tom Saleeba +* Travis E. Oliphant +* Travis Hathaway +* Travis Swicegood +* Trent Nelson +* Troy Powell +* Tyler Kim +* Tyrone Grandison +* Udo-Peter Steyer +* Ujjwal Das +* Ullrich Koethe +* Uwe L. Korn +* Valentin Haenel +* Victor Ma +* Vlad Frolov +* Vlad Zagorodniy +* Vladyslav Shevchenko +* Wes Roach +* Wes Turner +* Will Warner +* Willy Chen +* Winston Sebastian Pais +* Wolf Vollprecht +* Wolfgang Ulmer +* Xuehai Pan +* Xylar Asay-Davis +* Yaroslav Dmytryk +* Yuval Reches +* Yuvi Panda +* Zach Heaton +* Zahari +* Zhiwei Liang +* Zongyuan Zuo +* dependabot[bot] +* endolith +* giumas +* kanehira +* lexual +* mcopes73 +* oinizan +* ovz +* padeoe +* peter1000 +* pre-commit CI +* saraneem +* shadow_walker +* ugurthemaster +* wulmer +* Øystein Idema Torget +* İrem "Siren" Kuyucu diff --git a/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a2fbff055a4a2c501a54936ad1ec343ea049bce2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda-26.1.1.dist-info/licenses/LICENSE @@ -0,0 +1,35 @@ +BSD 3-Clause License + +Copyright (c) 2012, Anaconda, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +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 NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--- + +Conda incorporates the following libraries into its distributed code: + +* auxlib, licensed as ISC +* frozendict, license as LGPL-3.0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b3b3c9b4dfcf706be0c9e90bd08182e6e6b2940 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/__init__.py @@ -0,0 +1,194 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""OS-agnostic, system-level binary package manager.""" + +from __future__ import annotations + +import os +import sys +from json import JSONEncoder # noqa: TID251 +from os.path import abspath, dirname +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable + from subprocess import Popen + from typing import Any + +try: + from ._version import __version__ +except ImportError: + # _version.py is only created after running `pip install` + try: + from setuptools_scm import get_version + + __version__ = get_version(root="..", relative_to=__file__) + except (ImportError, OSError, LookupError): + # ImportError: setuptools_scm isn't installed + # OSError: git isn't installed + # LookupError: setuptools_scm unable to detect version + # Conda abides by CEP-8 which specifies using CalVer, so the dev version is: + # YY.MM.MICRO.devN+gHASH[.dirty] + __version__ = "0.0.0.dev0+placeholder" + +__all__ = ( + "__name__", + "__version__", + "__author__", + "__email__", + "__license__", + "__summary__", + "__url__", + "CONDA_PACKAGE_ROOT", + "CondaError", + "CondaMultiError", + "CondaExitZero", + "conda_signal_handler", + "__copyright__", +) + +__name__ = "conda" +__author__ = "Anaconda, Inc." +__email__ = "conda@continuum.io" +__license__ = "BSD-3-Clause" +__copyright__ = "Copyright (c) 2012, Anaconda, Inc." +__summary__ = __doc__ +__url__ = "https://github.com/conda/conda" + +if os.getenv("CONDA_ROOT") is None: + os.environ["CONDA_ROOT"] = sys.prefix + +CONDA_PACKAGE_ROOT = abspath(dirname(__file__)) +"""The conda package directory.""" + +CONDA_SOURCE_ROOT = dirname(CONDA_PACKAGE_ROOT) +"""The path within which to find the conda package. + +If ``conda`` is statically installed this is the site-packages. If ``conda`` is an editable +install or otherwise uninstalled this is the git repo. +""" + + +class CondaError(Exception): + return_code: int = 1 + reportable: bool = False # Exception may be reported to core maintainers + + def __init__(self, message: str | None, caused_by: Any = None, **kwargs): + self.message = message or "" + self._kwargs = kwargs + self._caused_by = caused_by + super().__init__(message) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}: {self}" + + def __str__(self) -> str: + try: + return str(self.message) % self._kwargs + except Exception: + debug_message = "\n".join( + ( + "class: " + self.__class__.__name__, + "message:", + self.message, + "kwargs:", + str(self._kwargs), + "", + ) + ) + print(debug_message, file=sys.stderr) + raise + + def dump_map(self) -> dict[str, Any]: + result = {k: v for k, v in vars(self).items() if not k.startswith("_")} + result.update( + exception_type=str(type(self)), + exception_name=self.__class__.__name__, + message=str(self), + error=repr(self), + caused_by=repr(self._caused_by), + **self._kwargs, + ) + return result + + +class CondaMultiError(CondaError): + def __init__(self, errors: Iterable[CondaError]): + self.errors = errors + super().__init__(None) + + def __repr__(self) -> str: + errs = [] + for e in self.errors: + if isinstance(e, EnvironmentError) and not isinstance(e, CondaError): + errs.append(str(e)) + else: + # We avoid Python casting this back to a str() + # by using e.__repr__() instead of repr(e) + # https://github.com/scrapy/cssselect/issues/34 + errs.append(e.__repr__()) + res = "\n".join(errs) + return res + + def __str__(self) -> str: + return "\n".join(str(e) for e in self.errors) + "\n" + + def dump_map(self) -> dict[str, str | tuple[str, ...]]: + return dict( + exception_type=str(type(self)), + exception_name=self.__class__.__name__, + errors=tuple(error.dump_map() for error in self.errors), + error="Multiple Errors Encountered.", + ) + + def contains(self, exception_class: BaseException | tuple[BaseException]) -> bool: + return any(isinstance(e, exception_class) for e in self.errors) + + +class CondaExitZero(CondaError): + return_code = 0 + + +ACTIVE_SUBPROCESSES: Iterable[Popen] = set() + + +def conda_signal_handler(signum: int, frame: Any): + # This function is in the base __init__.py so that it can be monkey-patched by other code + # if downstream conda users so choose. The biggest danger of monkey-patching is that + # unlink/link transactions don't get rolled back if interrupted mid-transaction. + for p in ACTIVE_SUBPROCESSES: + if p.poll() is None: + p.send_signal(signum) + + from .exceptions import CondaSignalInterrupt + + raise CondaSignalInterrupt(signum) + + +def _default(self, obj): + from frozendict import frozendict + + from .deprecations import deprecated + + if isinstance(obj, frozendict): + deprecated.topic( + "26.3", + "26.9", + topic="Monkey-patching `json.JSONEncoder` to support `frozendict`", + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", + ) + return dict(obj) + elif hasattr(obj, "to_json"): + deprecated.topic( + "26.3", + "26.9", + topic="Monkey-patching `json.JSONEncoder` to support `obj.to_json()`", + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", + ) + return obj.to_json() + return _default.default(obj) + + +# FUTURE: conda 26.3, remove the following monkey patching +_default.default = JSONEncoder().default +JSONEncoder.default = _default diff --git a/miniconda3/lib/python3.13/site-packages/conda/__main__.py b/miniconda3/lib/python3.13/site-packages/conda/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..791e8e9cdbab3f17320b9f900dca2ebfdfcd03a4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/__main__.py @@ -0,0 +1,9 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda as a module entry point.""" + +import sys + +from .cli import main + +sys.exit(main()) diff --git a/miniconda3/lib/python3.13/site-packages/conda/_vendor.py b/miniconda3/lib/python3.13/site-packages/conda/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..7d6e4b982021a48c7dcbcdfc380ee38b208b2fde --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/_vendor.py @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from .deprecations import deprecated + +deprecated.module("25.9", "26.3", addendum="Conda no longer vendors dependencies.") diff --git a/miniconda3/lib/python3.13/site-packages/conda/_version.py b/miniconda3/lib/python3.13/site-packages/conda/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..633d6cf44910bd38e8190c3bfdaf6d9b15c88277 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/_version.py @@ -0,0 +1,34 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] + COMMIT_ID = Union[str, None] +else: + VERSION_TUPLE = object + COMMIT_ID = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE +commit_id: COMMIT_ID +__commit_id__: COMMIT_ID + +__version__ = version = '26.1.1' +__version_tuple__ = version_tuple = (26, 1, 1) + +__commit_id__ = commit_id = None diff --git a/miniconda3/lib/python3.13/site-packages/conda/activate.py b/miniconda3/lib/python3.13/site-packages/conda/activate.py new file mode 100644 index 0000000000000000000000000000000000000000..0fcb5c59e2507bc8a88d3715a79a5599d85b8b21 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/activate.py @@ -0,0 +1,1158 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda activate and deactivate logic. + +Implementation for all shell interface logic exposed via +`conda shell.* [activate|deactivate|reactivate|hook|commands]`. This includes a custom argument +parser, an abstract shell class, and special path handling for Windows. + +See conda.cli.main.main_sourced for the entry point into this module. +""" + +from __future__ import annotations + +import abc +import os +import re +import sys +from logging import getLogger +from os.path import ( + abspath, + basename, + dirname, + exists, + expanduser, + expandvars, + isdir, + join, +) +from pathlib import Path +from typing import TYPE_CHECKING + +# Since we have to have configuration context here, anything imported by +# conda.base.context is fair game, but nothing more. +from . import CONDA_PACKAGE_ROOT +from .auxlib.compat import Utf8NamedTemporaryFile +from .base.constants import ( + CONDA_ENV_VARS_UNSET_VAR, + PACKAGE_ENV_VARS_DIR, + PREFIX_STATE_FILE, + RESERVED_ENV_VARS, +) +from .base.context import context, locate_prefix_by_name +from .common.compat import on_win +from .common.path import path_identity as _path_identity +from .common.path import paths_equal, unix_path_to_win, win_path_to_unix +from .common.serialize import json +from .deprecations import deprecated +from .exceptions import ActivateHelp, ArgumentError, DeactivateHelp, GenericHelp + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + +log = getLogger(__name__) + + +BUILTIN_COMMANDS = { + "activate": ActivateHelp(), + "deactivate": DeactivateHelp(), + "hook": GenericHelp("hook"), + "commands": GenericHelp("commands"), + "reactivate": GenericHelp("reactivate"), +} + + +class _Activator(metaclass=abc.ABCMeta): + # Activate and deactivate have three tasks + # 1. Set and unset environment variables + # 2. Execute/source activate.d/deactivate.d scripts + # 3. Update the command prompt + # + # Shells should also use 'reactivate' following conda's install, update, and + # remove/uninstall commands. + # + # All core logic is in build_activate() or build_deactivate(), and is independent of + # shell type. Each returns a map containing the keys: + # export_vars + # unset_var + # activate_scripts + # deactivate_scripts + # + # The value of the CONDA_PROMPT_MODIFIER environment variable holds conda's contribution + # to the command prompt. + # + # To implement support for a new shell, ideally one would only need to add shell-specific + # information to the __init__ method of this class. + + # The following instance variables must be defined by each implementation. + pathsep_join: str + sep: str + path_conversion: Callable[ + [str | Iterable[str] | None], str | tuple[str, ...] | None + ] + script_extension: str + + tempfile_extension: str | None + """Temporary file's extension, None writes to stdout instead.""" + command_join: str + + unset_var_tmpl: str + export_var_tmpl: str + path_var_tmpl: str + set_var_tmpl: str + run_script_tmpl: str + + hook_source_path: Path | None + inline_hook_source: bool + + needs_line_ending_fix: bool + + def __init__(self, arguments=None): + self._raw_arguments = arguments + + def get_export_unset_vars(self, export_metavars=True, **kwargs): + """ + :param export_metavars: whether to export `conda_exe_vars` meta variables. + :param kwargs: environment variables to export. + .. if you pass and set any other variable to None, then it + emits it to the dict with a value of None. + + :return: A dict of env vars to export ordered the same way as kwargs. + And a list of env vars to unset. + """ + unset_vars = [] + export_vars = {} + + # split provided environment variables into exports vs unsets + for name, value in kwargs.items(): + if value is None: + unset_vars.append(name) + else: + export_vars[name] = value + + if export_metavars: + # split meta variables into exports vs unsets + for name, value in context.conda_exe_vars_dict.items(): + if value is None: + unset_vars.append(name) + elif "/" in value or "\\" in value: + export_vars[name] = self.path_conversion(value) + else: + export_vars[name] = value + else: + # unset all meta variables + unset_vars.extend(context.conda_exe_vars_dict) + + # normalize case if requested + if context.envvars_force_uppercase: + export_vars = {name.upper(): value for name, value in export_vars.items()} + unset_vars = [name.upper() for name in unset_vars] + + return export_vars, unset_vars + + def _finalize(self, commands, ext): + commands = (*commands, "") # add terminating newline + content = self.command_join.join(commands) + + # Normalize line endings for Unix shells on Windows + if on_win and self.path_conversion == win_path_to_unix: + content = content.replace("\r\n", "\n") + + if ext is None: + return content + elif ext: + with Utf8NamedTemporaryFile("w+", suffix=ext, delete=False) as tf: + # the default mode is 'w+b', and universal new lines don't work in that mode + tf.write(content) + return tf.name + else: + raise NotImplementedError() + + def activate(self): + if self.stack: + builder_result = self.build_stack(self.env_name_or_prefix) + else: + builder_result = self.build_activate(self.env_name_or_prefix) + return self._finalize( + self._yield_commands(builder_result), self.tempfile_extension + ) + + def deactivate(self): + return self._finalize( + self._yield_commands(self.build_deactivate()), self.tempfile_extension + ) + + def reactivate(self): + return self._finalize( + self._yield_commands(self.build_reactivate()), self.tempfile_extension + ) + + @deprecated.argument("25.9", "26.3", "auto_activate_base", rename="auto_activate") + def hook(self, auto_activate: bool | None = None) -> str: + builder: list[str] = [] + if preamble := self._hook_preamble(): + builder.append(preamble) + if self.hook_source_path: + if self.inline_hook_source: + builder.append(self.hook_source_path.read_text()) + else: + builder.append(self.run_script_tmpl % self.hook_source_path) + if auto_activate is None and context.auto_activate or auto_activate: + builder.append(f"conda activate '{context.default_activation_env}'\n") + postamble = self._hook_postamble() + if postamble is not None: + builder.append(postamble) + return "\n".join(builder) + + def execute(self): + # return value meant to be written to stdout + self._parse_and_set_args() + + # invoke pre/post commands, see conda.cli.conda_argparse.do_call + context.plugin_manager.invoke_pre_commands(self.command) + response = getattr(self, self.command)() + context.plugin_manager.invoke_post_commands(self.command) + return response + + def template_unset_var(self, key: str) -> str: + return self.unset_var_tmpl % key + + def template_export_var(self, key: str, value: str) -> str: + return self.export_var_tmpl % (key, value) + + def template_path_var(self, key: str, value: str) -> str: + return self.path_var_tmpl % (key, value) + + def _hook_preamble(self) -> str | None: + result = [] + for key, value in context.conda_exe_vars_dict.items(): + if value is None: + result.append(self.template_unset_var(key)) + elif {"/", "\\"}.intersection(value): + result.append(self.template_path_var(key, value)) + else: + result.append(self.template_export_var(key, value)) + if result: + return self.command_join.join(result) + self.command_join + return None + + def _hook_postamble(self) -> str | None: + return None + + def _parse_and_set_args(self) -> None: + command, *arguments = self._raw_arguments or [None] + help_flags = ("-h", "--help", "/?") + non_help_args = tuple(arg for arg in arguments if arg not in help_flags) + help_requested = len(arguments) != len(non_help_args) + remainder_args = list(arg for arg in non_help_args if arg and arg != command) + + if command not in BUILTIN_COMMANDS: + raise ArgumentError( + "'activate', 'deactivate', 'hook', 'commands', or 'reactivate' " + "command must be given." + (f", not '{command}'." if command else ".") + ) + elif help_requested: + raise BUILTIN_COMMANDS[command] + + if command.endswith("activate") or command == "hook": + try: + dev_idx = remainder_args.index("--dev") + except ValueError: + context.dev = False + else: + del remainder_args[dev_idx] + context.dev = True + + if command == "activate": + self.stack = context.auto_stack and context.shlvl <= context.auto_stack + try: + stack_idx = remainder_args.index("--stack") + except ValueError: + stack_idx = -1 + try: + no_stack_idx = remainder_args.index("--no-stack") + except ValueError: + no_stack_idx = -1 + if stack_idx >= 0 and no_stack_idx >= 0: + raise ArgumentError( + "cannot specify both --stack and --no-stack to " + command + ) + if stack_idx >= 0: + self.stack = True + del remainder_args[stack_idx] + if no_stack_idx >= 0: + self.stack = False + del remainder_args[no_stack_idx] + if len(remainder_args) > 1: + raise ArgumentError( + command + + " does not accept more than one argument:\n" + + str(remainder_args) + + "\n" + ) + if remainder_args: + self.env_name_or_prefix = remainder_args[0] + else: + self.env_name_or_prefix = context.default_activation_env + elif remainder_args: + raise ArgumentError( + f"{command} does not accept arguments\nremainder_args: {remainder_args}\n" + ) + + self.command = command + + def _yield_commands(self, cmds_dict): + for key, value in sorted(cmds_dict.get("export_path", {}).items()): + yield self.export_var_tmpl % (key, value) + + for script in cmds_dict.get("deactivate_scripts", ()): + yield self.run_script_tmpl % script + + for key in cmds_dict.get("unset_vars", ()): + yield self.unset_var_tmpl % key + + for key, value in cmds_dict.get("set_vars", {}).items(): + yield self.set_var_tmpl % (key, value) + + for key, value in cmds_dict.get("export_vars", {}).items(): + yield self.export_var_tmpl % (key, value) + + for script in cmds_dict.get("activate_scripts", ()): + yield self.run_script_tmpl % script + + def build_activate(self, env_name_or_prefix): + return self._build_activate_stack(env_name_or_prefix, False) + + def build_stack(self, env_name_or_prefix): + return self._build_activate_stack(env_name_or_prefix, True) + + def _build_activate_stack(self, env_name_or_prefix, stack): + # get environment prefix + if re.search(r"\\|/", env_name_or_prefix): + prefix = expand(env_name_or_prefix) + if not isdir(join(prefix, "conda-meta")): + from .exceptions import EnvironmentLocationNotFound + + raise EnvironmentLocationNotFound(prefix) + else: + prefix = locate_prefix_by_name(env_name_or_prefix) + + # get prior shlvl and prefix + old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + old_conda_prefix = os.getenv("CONDA_PREFIX") + + # if the prior active prefix is this prefix we are actually doing a reactivate + if old_conda_prefix == prefix and old_conda_shlvl > 0: + return self.build_reactivate() + + activate_scripts = self._get_activate_scripts(prefix) + conda_shlvl = old_conda_shlvl + 1 + conda_default_env = self._default_env(prefix) + conda_prompt_modifier = self._prompt_modifier(prefix, conda_default_env) + env_vars = { + name: value + for name, value in self._get_environment_env_vars(prefix).items() + if value != CONDA_ENV_VARS_UNSET_VAR + } + + # get clobbered environment variables + clobber_vars = set(env_vars).intersection(os.environ) + overwritten_clobber_vars = [ + clobber_var + for clobber_var in clobber_vars + if os.getenv(clobber_var) != env_vars[clobber_var] + ] + if overwritten_clobber_vars: + print( + "WARNING: overwriting environment variables set in the machine", + file=sys.stderr, + ) + print(f"overwriting variable {overwritten_clobber_vars}", file=sys.stderr) + for name in clobber_vars: + env_vars[f"__CONDA_SHLVL_{old_conda_shlvl}_{name}"] = os.getenv(name) + + if old_conda_shlvl == 0: + export_vars, unset_vars = self.get_export_unset_vars( + PATH=self.pathsep_join(self._add_prefix_to_path(prefix)), + CONDA_PREFIX=prefix, + CONDA_SHLVL=conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **env_vars, + ) + deactivate_scripts = () + elif stack: + export_vars, unset_vars = self.get_export_unset_vars( + PATH=self.pathsep_join(self._add_prefix_to_path(prefix)), + CONDA_PREFIX=prefix, + CONDA_SHLVL=conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **env_vars, + **{ + f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix, + f"CONDA_STACKED_{conda_shlvl}": "true", + }, + ) + deactivate_scripts = () + else: + export_vars, unset_vars = self.get_export_unset_vars( + PATH=self.pathsep_join( + self._replace_prefix_in_path(old_conda_prefix, prefix) + ), + CONDA_PREFIX=prefix, + CONDA_SHLVL=conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **env_vars, + **{ + f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix, + }, + ) + deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix) + + set_vars = {} + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "deactivate_scripts": deactivate_scripts, + "activate_scripts": activate_scripts, + } + + def build_deactivate(self): + self._deactivate = True + # query environment + old_conda_prefix = os.getenv("CONDA_PREFIX") + old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + if not old_conda_prefix or old_conda_shlvl < 1: + # no active environment, so cannot deactivate; do nothing + return { + "unset_vars": (), + "set_vars": {}, + "export_vars": {}, + "deactivate_scripts": (), + "activate_scripts": (), + } + deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix) + old_conda_environment_env_vars = self._get_environment_env_vars( + old_conda_prefix + ) + + new_conda_shlvl = old_conda_shlvl - 1 + set_vars = {} + if old_conda_shlvl == 1: + new_path = self.pathsep_join( + self._remove_prefix_from_path(old_conda_prefix) + ) + # You might think that you can remove the CONDA_EXE vars with export_metavars=False + # here so that "deactivate means deactivate" but you cannot since the conda shell + # scripts still refer to them and they only set them once at the top. We could change + # that though, the conda() shell function could set them instead of doing it at the + # top. This would be *much* cleaner. I personally cannot abide that I have + # deactivated conda and anything at all in my env still references it (apart from the + # shell script, we need something I suppose!) + export_vars, unset_vars = self.get_export_unset_vars( + CONDA_PREFIX=None, + CONDA_SHLVL=new_conda_shlvl, + CONDA_DEFAULT_ENV=None, + CONDA_PROMPT_MODIFIER=None, + ) + conda_prompt_modifier = "" + activate_scripts = () + export_path = {"PATH": new_path} + else: + if old_conda_shlvl <= 1: + raise ValueError("'old_conda_shlvl' must be 2 or larger") + new_prefix = os.getenv("CONDA_PREFIX_%d" % new_conda_shlvl) + if not new_prefix: + raise ValueError( + "This should not happen! You may have non-consecutive `CONDA_PREFIX_ " + "environment variables. Try restarting your shell and, if it persists, " + "check your shell profile to see what may be adding a faulty " + "CONDA_PREFIX_ environment variable." + ) + conda_default_env = self._default_env(new_prefix) + conda_prompt_modifier = self._prompt_modifier(new_prefix, conda_default_env) + new_conda_environment_env_vars = self._get_environment_env_vars(new_prefix) + + old_prefix_stacked = "CONDA_STACKED_%d" % old_conda_shlvl in os.environ + new_path = "" + + unset_vars = ["CONDA_PREFIX_%d" % new_conda_shlvl] + if old_prefix_stacked: + new_path = self.pathsep_join( + self._remove_prefix_from_path(old_conda_prefix) + ) + unset_vars.append("CONDA_STACKED_%d" % old_conda_shlvl) + else: + new_path = self.pathsep_join( + self._replace_prefix_in_path(old_conda_prefix, new_prefix) + ) + + export_vars, unset_vars2 = self.get_export_unset_vars( + CONDA_PREFIX=new_prefix, + CONDA_SHLVL=new_conda_shlvl, + CONDA_DEFAULT_ENV=conda_default_env, + CONDA_PROMPT_MODIFIER=conda_prompt_modifier, + **new_conda_environment_env_vars, + ) + unset_vars += unset_vars2 + export_path = {"PATH": new_path} + activate_scripts = self._get_activate_scripts(new_prefix) + + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + # Handle environment variables that need to be unset during deactivation + for env_var in old_conda_environment_env_vars.keys(): + if save_value := os.getenv(f"__CONDA_SHLVL_{new_conda_shlvl}_{env_var}"): + export_vars[env_var] = save_value + else: + # Apply case conversion for environment variables that need to be unset + if context.envvars_force_uppercase: + unset_vars.append(env_var.upper()) + else: + unset_vars.append(env_var) + + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "export_path": export_path, + "deactivate_scripts": deactivate_scripts, + "activate_scripts": activate_scripts, + } + + def build_reactivate(self): + self._reactivate = True + conda_prefix = os.getenv("CONDA_PREFIX") + conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + if not conda_prefix or conda_shlvl < 1: + # no active environment, so cannot reactivate; do nothing + return { + "unset_vars": [], + "set_vars": {}, + "export_vars": {}, + "deactivate_scripts": (), + "activate_scripts": (), + } + conda_default_env = os.getenv( + "CONDA_DEFAULT_ENV", self._default_env(conda_prefix) + ) + new_path = self.pathsep_join( + self._replace_prefix_in_path(conda_prefix, conda_prefix) + ) + set_vars = {} + conda_prompt_modifier = self._prompt_modifier(conda_prefix, conda_default_env) + if context.changeps1: + self._update_prompt(set_vars, conda_prompt_modifier) + + export_vars, unset_vars = self.get_export_unset_vars( + PATH=new_path, + CONDA_SHLVL=conda_shlvl, + CONDA_PROMPT_MODIFIER=self._prompt_modifier( + conda_prefix, conda_default_env + ), + ) + + # environment variables are set only to aid transition from conda 4.3 to conda 4.4 + return { + "unset_vars": unset_vars, + "set_vars": set_vars, + "export_vars": export_vars, + "deactivate_scripts": self._get_deactivate_scripts(conda_prefix), + "activate_scripts": self._get_activate_scripts(conda_prefix), + } + + def _get_starting_path_list(self): + # For isolation, running the conda test suite *without* env. var. inheritance + # every so often is a good idea. We should probably make this a pytest fixture + # along with one that tests both hardlink-only and copy-only, but before that + # conda's testsuite needs to be a lot faster! + clean_paths = { + "darwin": "/usr/bin:/bin:/usr/sbin:/sbin", + # You may think 'let us do something more clever here and interpolate + # `%windir%`' but the point here is the the whole env. is cleaned out + "win32": "C:\\Windows\\system32;" + "C:\\Windows;" + "C:\\Windows\\System32\\Wbem;" + "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\", + } + path = os.getenv( + "PATH", + clean_paths[sys.platform] if sys.platform in clean_paths else "/usr/bin", + ) + path_split = path.split(os.pathsep) + return path_split + + def _get_path_dirs(self, prefix): + if on_win: # pragma: unix no cover + yield prefix.rstrip(self.sep) + + # We need to stat(2) for possible environments because + # tests can't be told where to look! + # + # mingw-w64 is a legacy variant used by m2w64-* packages + # + # We could include clang32 and mingw32 variants + variants = [] + for variant in ["ucrt64", "clang64", "mingw64", "clangarm64"]: + path = self.sep.join((prefix, "Library", variant)) + + # MSYS2 /c/ + # cygwin /cygdrive/c/ + if re.match("^(/[A-Za-z]/|/cygdrive/[A-Za-z]/).*", prefix): + path = unix_path_to_win(path, prefix) + + if isdir(path): + variants.append(variant) + + if len(variants) > 1: + print( + f"WARNING: {prefix}: {variants} MSYS2 envs exist: please check your dependencies", + file=sys.stderr, + ) + print( + f"WARNING: conda list -n {self._default_env(prefix)}", + file=sys.stderr, + ) + + if variants: + yield self.sep.join((prefix, "Library", variants[0], "bin")) + + yield self.sep.join((prefix, "Library", "mingw-w64", "bin")) + yield self.sep.join((prefix, "Library", "usr", "bin")) + yield self.sep.join((prefix, "Library", "bin")) + yield self.sep.join((prefix, "Scripts")) + yield self.sep.join((prefix, "bin")) + else: + yield self.sep.join((prefix, "bin")) + + def _add_prefix_to_path(self, prefix, starting_path_dirs=None): + prefix = self.path_conversion(prefix) + if starting_path_dirs is None: + path_list = list(self.path_conversion(self._get_starting_path_list())) + else: + path_list = list(self.path_conversion(starting_path_dirs)) + + # If this is the first time we're activating an environment, we need to ensure that + # the condabin directory is included in the path list. + # Under normal conditions, if the shell hook is working correctly, this should + # never trigger. + old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0) + if not old_conda_shlvl and not any(p.endswith("condabin") for p in path_list): + condabin_dir = self.path_conversion(join(context.conda_prefix, "condabin")) + path_list.insert(0, condabin_dir) + + path_list[0:0] = list(self.path_conversion(self._get_path_dirs(prefix))) + return tuple(path_list) + + def _remove_prefix_from_path(self, prefix, starting_path_dirs=None): + return self._replace_prefix_in_path(prefix, None, starting_path_dirs) + + def _replace_prefix_in_path(self, old_prefix, new_prefix, starting_path_dirs=None): + old_prefix = self.path_conversion(old_prefix) + new_prefix = self.path_conversion(new_prefix) + if starting_path_dirs is None: + path_list = list(self.path_conversion(self._get_starting_path_list())) + else: + path_list = list(self.path_conversion(starting_path_dirs)) + + def index_of_path(paths, test_path): + for q, path in enumerate(paths): + if paths_equal(path, test_path): + return q + return None + + if old_prefix is not None: + prefix_dirs = tuple(self._get_path_dirs(old_prefix)) + first_idx = index_of_path(path_list, prefix_dirs[0]) + if first_idx is None: + first_idx = 0 + else: + prefix_dirs_idx = len(prefix_dirs) - 1 + last_idx = None + while last_idx is None and prefix_dirs_idx > -1: + last_idx = index_of_path(path_list, prefix_dirs[prefix_dirs_idx]) + if last_idx is None: + print( + f"Did not find path entry {prefix_dirs[prefix_dirs_idx]}", + file=sys.stderr, + ) + prefix_dirs_idx = prefix_dirs_idx - 1 + # this compensates for an extra Library/bin dir entry from the interpreter on + # windows. If that entry isn't being added, it should have no effect. + library_bin_dir = self.path_conversion( + self.sep.join((sys.prefix, "Library", "bin")) + ) + if path_list[last_idx + 1] == library_bin_dir: + last_idx += 1 + del path_list[first_idx : last_idx + 1] + else: + first_idx = 0 + + if new_prefix is not None: + path_list[first_idx:first_idx] = list(self._get_path_dirs(new_prefix)) + + return tuple(path_list) + + def _update_prompt(self, set_vars, conda_prompt_modifier): + pass + + def _default_env(self, prefix): + if paths_equal(prefix, context.root_prefix): + return "base" + return basename(prefix) if basename(dirname(prefix)) == "envs" else prefix + + def _prompt_modifier(self, prefix, conda_default_env): + if context.changeps1: + # Get current environment and prompt stack + env_stack = [] + prompt_stack = [] + old_shlvl = int(os.getenv("CONDA_SHLVL", "0").rstrip()) + for i in range(1, old_shlvl + 1): + if i == old_shlvl: + env_i = self._default_env(os.getenv("CONDA_PREFIX", "")) + else: + env_i = self._default_env( + os.getenv(f"CONDA_PREFIX_{i}", "").rstrip() + ) + stacked_i = bool(os.getenv(f"CONDA_STACKED_{i}", "").rstrip()) + env_stack.append(env_i) + if not stacked_i: + prompt_stack = prompt_stack[0:-1] + prompt_stack.append(env_i) + + # Modify prompt stack according to pending operation + deactivate = getattr(self, "_deactivate", False) + reactivate = getattr(self, "_reactivate", False) + if deactivate: + prompt_stack = prompt_stack[0:-1] + env_stack = env_stack[0:-1] + stacked = bool(os.getenv(f"CONDA_STACKED_{old_shlvl}", "").rstrip()) + if not stacked and env_stack: + prompt_stack.append(env_stack[-1]) + elif reactivate: + pass + else: + stack = getattr(self, "stack", False) + if not stack: + prompt_stack = prompt_stack[0:-1] + prompt_stack.append(conda_default_env) + + conda_stacked_env = ",".join(prompt_stack[::-1]) + + return context.env_prompt.format( + default_env=conda_default_env, + stacked_env=conda_stacked_env, + prefix=prefix, + name=basename(prefix), + ) + else: + return "" + + def _get_activate_scripts(self, prefix): + _script_extension = self.script_extension + se_len = -len(_script_extension) + try: + paths = ( + entry.path + for entry in os.scandir(join(prefix, "etc", "conda", "activate.d")) + ) + except OSError: + return () + return self.path_conversion( + sorted(p for p in paths if p[se_len:] == _script_extension) + ) + + def _get_deactivate_scripts(self, prefix): + _script_extension = self.script_extension + se_len = -len(_script_extension) + try: + paths = ( + entry.path + for entry in os.scandir(join(prefix, "etc", "conda", "deactivate.d")) + ) + except OSError: + return () + return self.path_conversion( + sorted((p for p in paths if p[se_len:] == _script_extension), reverse=True) + ) + + def _get_environment_env_vars(self, prefix): + env_vars_file = join(prefix, PREFIX_STATE_FILE) + pkg_env_var_dir = join(prefix, PACKAGE_ENV_VARS_DIR) + env_vars = {} + + # First get env vars from packages + if exists(pkg_env_var_dir): + for pkg_env_var_path in sorted( + entry.path for entry in os.scandir(pkg_env_var_dir) + ): + with open(pkg_env_var_path) as f: + env_vars.update(json.loads(f.read())) + + # Then get env vars from environment specification + if exists(env_vars_file): + with open(env_vars_file) as f: + prefix_state = json.loads(f.read()) + prefix_state_env_vars = prefix_state.get("env_vars", {}) + dup_vars = [ + ev for ev in env_vars.keys() if ev in prefix_state_env_vars.keys() + ] + for dup in dup_vars: + print( + "WARNING: duplicate env vars detected. Vars from the environment " + "will overwrite those from packages", + file=sys.stderr, + ) + print(f"variable {dup} duplicated", file=sys.stderr) + env_vars.update(prefix_state_env_vars) + + # Remove reserved environment variables and warn if they're being set + collect_reserved_vars = [] + for reserved in RESERVED_ENV_VARS: + if reserved in env_vars: + # Only warn if the variable is actually being set (not unset) + if env_vars[reserved] != CONDA_ENV_VARS_UNSET_VAR: + collect_reserved_vars.append(reserved) + # Remove from env_vars regardless + env_vars.pop(reserved) + + if collect_reserved_vars: + print_reserved_vars = ", ".join(collect_reserved_vars) + print( + f"WARNING: the configured environment variable(s) for prefix '{prefix}' " + f"are reserved and will be ignored: {print_reserved_vars}.\n\n" + f"Remove the invalid configuration with `conda env config vars unset " + f"-p {prefix} {' '.join(collect_reserved_vars)}`.\n", + file=sys.stderr, + ) + return env_vars + + +def expand(path): + return abspath(expanduser(expandvars(path))) + + +def backslash_to_forwardslash( + paths: str | Iterable[str] | None, +) -> str | tuple[str, ...] | None: + if paths is None: + return None + elif isinstance(paths, str): + return paths.replace("\\", "/") + else: + return tuple([path.replace("\\", "/") for path in paths]) + + +class PosixActivator(_Activator): + pathsep_join = ":".join + sep = "/" + path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) + script_extension = ".sh" + tempfile_extension = None # output to stdout + command_join = "\n" + needs_line_ending_fix = True + + # Using `unset %s` would cause issues for people running + # with shell flag -u set (error on unset). + unset_var_tmpl = "export %s=''" # unset %s + export_var_tmpl = "export %s='%s'" + path_var_tmpl = "export %s=\"$(cygpath '%s')\"" if on_win else export_var_tmpl + set_var_tmpl = "%s='%s'" + run_script_tmpl = ". \"`cygpath '%s'`\"" if on_win else '. "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "profile.d", + "conda.sh", + ) + inline_hook_source = True + + def _update_prompt(self, set_vars, conda_prompt_modifier): + ps1 = os.getenv("PS1", "") + if "POWERLINE_COMMAND" in ps1: + # Defer to powerline (https://github.com/powerline/powerline) if it's in use. + return + current_prompt_modifier = os.getenv("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + ps1 = re.sub(re.escape(current_prompt_modifier), r"", ps1) + # Because we're using single-quotes to set shell variables, we need to handle the + # proper escaping of single quotes that are already part of the string. + # Best solution appears to be https://stackoverflow.com/a/1250279 + ps1 = ps1.replace("'", "'\"'\"'") + set_vars.update( + { + "PS1": conda_prompt_modifier + ps1, + } + ) + + +class CshActivator(_Activator): + pathsep_join = ":".join + sep = "/" + path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) + script_extension = ".csh" + tempfile_extension = None # output to stdout + command_join = ";\n" + needs_line_ending_fix = True + + unset_var_tmpl = "unsetenv %s" + export_var_tmpl = 'setenv %s "%s"' + path_var_tmpl = "setenv %s \"`cygpath '%s'`\"" if on_win else export_var_tmpl + set_var_tmpl = "set %s='%s'" + run_script_tmpl = "source \"`cygpath '%s'`\"" if on_win else 'source "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "profile.d", + "conda.csh", + ) + # TCSH/CSH removes newlines when doing command substitution (see `man tcsh`), + # source conda.csh directly and use line terminators to separate commands + inline_hook_source = False + + def _update_prompt(self, set_vars, conda_prompt_modifier): + prompt = os.getenv("prompt", "") + current_prompt_modifier = os.getenv("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + prompt = re.sub(re.escape(current_prompt_modifier), r"", prompt) + set_vars.update( + { + "prompt": conda_prompt_modifier + prompt, + } + ) + + +class XonshActivator(_Activator): + pathsep_join = ";".join if on_win else ":".join + sep = "/" + path_conversion = staticmethod( + backslash_to_forwardslash if on_win else _path_identity + ) + # 'scripts' really refer to de/activation scripts, not scripts in the language per se + # xonsh can piggy-back activation scripts from other languages depending on the platform + script_extension = ".bat" if on_win else ".sh" + tempfile_extension = None # output to stdout + command_join = "\n" + needs_line_ending_fix = False + + unset_var_tmpl = "try:\n del $%s\nexcept KeyError:\n pass" + export_var_tmpl = "$%s = '%s'" + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + run_script_tmpl = ( + 'source-cmd --suppress-skip-message "%s"' + if on_win + else 'source-bash --suppress-skip-message -n "%s"' + ) + + hook_source_path = Path(CONDA_PACKAGE_ROOT, "shell", "conda.xsh") + inline_hook_source = True + + def template_path_var(self, key: str, value: str) -> str: + return self.path_var_tmpl % (key, self.path_conversion(value)) + + +class CmdExeActivator(_Activator): + pathsep_join = ";".join + sep = "\\" + path_conversion = staticmethod(_path_identity) + script_extension = ".bat" + tempfile_extension = ".env" + command_join = "\n" + needs_line_ending_fix = False + + # we are not generating a script to run but rather an INI style file + # with key=value pairs to set environment variables, key= to unset them, + # and _CONDA_SCRIPT=script pairs to run scripts + unset_var_tmpl = "%s=" + export_var_tmpl = "%s=%s" + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + run_script_tmpl = "_CONDA_SCRIPT=%s" + + hook_source_path = None + inline_hook_source = None + + def _update_prompt(self, set_vars, conda_prompt_modifier): + prompt = os.getenv("PROMPT", "") + current_prompt_modifier = os.getenv("CONDA_PROMPT_MODIFIER") + if current_prompt_modifier: + prompt = re.sub(re.escape(current_prompt_modifier), r"", prompt) + set_vars["PROMPT"] = conda_prompt_modifier + prompt + + def _hook_preamble(self) -> None: + # TODO: cmd.exe doesn't get a hook function? Or do we need to do something different? + # Like, for cmd.exe only, put a special directory containing only conda.bat on PATH? + pass + + +class CmdExeRunActivator(CmdExeActivator): + # CmdExeActivator writes an .env file by default; let's force in-memory output here + # so that we can embed the activation output directly into our wrapper script. + tempfile_extension = None + + unset_var_tmpl = 'SET "%s="' + export_var_tmpl = 'SET "%s=%s"' + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + # If any of these calls to the activation hook scripts fail, we want + # to exit the wrapper immediately and abort `conda run` right away. + run_script_tmpl = 'CALL "%s"\nIF %%ERRORLEVEL%% NEQ 0 EXIT /b %%ERRORLEVEL%%' + + +class FishActivator(_Activator): + pathsep_join = '" "'.join + sep = "/" + path_conversion = staticmethod(win_path_to_unix if on_win else _path_identity) + script_extension = ".fish" + tempfile_extension = None # output to stdout + command_join = ";\n" + needs_line_ending_fix = True + + unset_var_tmpl = "set -e %s || true" + export_var_tmpl = 'set -gx %s "%s"' + path_var_tmpl = 'set -gx %s (cygpath "%s")' if on_win else export_var_tmpl + set_var_tmpl = 'set -g %s "%s"' + run_script_tmpl = 'source "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "etc", + "fish", + "conf.d", + "conda.fish", + ) + inline_hook_source = True + + +class PowerShellActivator(_Activator): + pathsep_join = ";".join if on_win else ":".join + sep = "\\" if on_win else "/" + path_conversion = staticmethod(_path_identity) + script_extension = ".ps1" + tempfile_extension = None # output to stdout + command_join = "\n" + needs_line_ending_fix = False + + unset_var_tmpl = "$Env:%s = $null" + export_var_tmpl = '$Env:%s = "%s"' + path_var_tmpl = export_var_tmpl + set_var_tmpl = export_var_tmpl + run_script_tmpl = '. "%s"' + + hook_source_path = Path( + CONDA_PACKAGE_ROOT, + "shell", + "condabin", + "conda-hook.ps1", + ) + inline_hook_source = True + + def _hook_preamble(self) -> str: + module_args = f"$CondaModuleArgs = @{{ChangePs1 = ${context.changeps1}}}" + return super()._hook_preamble() + module_args + self.command_join + + def _hook_postamble(self) -> str: + return "Remove-Variable CondaModuleArgs" + + +class JSONFormatMixin(_Activator): + """Returns the necessary values for activation as JSON, so that tools can use them.""" + + pathsep_join = list + tempfile_extension = None # output to stdout + command_join = list + + def _hook_preamble(self): + return context.conda_exe_vars_dict + + def _finalize(self, commands, ext): + merged = {} + for _cmds in commands: + merged.update(_cmds) + + commands = merged + if ext is None: + return json.dumps(commands, indent=2) + elif ext: + with Utf8NamedTemporaryFile("w+", suffix=ext, delete=False) as tf: + # the default mode is 'w+b', and universal new lines don't work in that mode + # command_join should account for that + json.dump(commands, tf) + return tf.name + else: + raise NotImplementedError() + + def _yield_commands(self, cmds_dict): + # TODO: _Is_ defining our own object shape here any better than + # just dumping the `cmds_dict`? + path = cmds_dict.get("export_path", {}) + export_vars = cmds_dict.get("export_vars", {}) + # treat PATH specially + if "PATH" in export_vars: + new_path = path.get("PATH", []) + new_path.extend(export_vars.pop("PATH")) + path["PATH"] = new_path + + yield { + "path": path, + "vars": { + "export": export_vars, + "unset": cmds_dict.get("unset_vars", ()), + "set": cmds_dict.get("set_vars", {}), + }, + "scripts": { + "activate": cmds_dict.get("activate_scripts", ()), + "deactivate": cmds_dict.get("deactivate_scripts", ()), + }, + } + + +activator_map: dict[str, type[_Activator]] = { + "posix": PosixActivator, + "ash": PosixActivator, + "bash": PosixActivator, + "dash": PosixActivator, + "zsh": PosixActivator, + "csh": CshActivator, + "tcsh": CshActivator, + "xonsh": XonshActivator, + "cmd.exe": CmdExeActivator, + "cmd.exe.run": CmdExeRunActivator, + "fish": FishActivator, + "powershell": PowerShellActivator, +} + +formatter_map = { + "json": JSONFormatMixin, +} + + +def _build_activator_cls(shell): + """Dynamically construct the activator class. + + Detect the base activator and any number of formatters (appended using '+' to the base name). + For example, `posix+json` (as in `conda shell.posix+json activate`) would use the + `PosixActivator` base class and add the `JSONFormatMixin`. + """ + shell_etc = shell.split("+") + activator, formatters = shell_etc[0], shell_etc[1:] + + bases = [activator_map[activator]] + for f in formatters: + bases.append(formatter_map[f]) + + cls = type("Activator", tuple(reversed(bases)), {}) + return cls diff --git a/miniconda3/lib/python3.13/site-packages/conda/api.py b/miniconda3/lib/python3.13/site-packages/conda/api.py new file mode 100644 index 0000000000000000000000000000000000000000..34bd5cef7c037eaf40ba760c6f3fecc143315a67 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/api.py @@ -0,0 +1,501 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of conda's high-level APIs.""" + +from .base.constants import DepsModifier as _DepsModifier +from .base.constants import UpdateModifier as _UpdateModifier +from .base.context import context +from .common.constants import NULL +from .core.package_cache_data import PackageCacheData as _PackageCacheData +from .core.prefix_data import PrefixData as _PrefixData +from .core.subdir_data import SubdirData as _SubdirData +from .models.channel import Channel + +DepsModifier = _DepsModifier +"""Flags to enable alternate handling of dependencies.""" + +UpdateModifier = _UpdateModifier +"""Flags to enable alternate handling for updates of existing packages in the environment.""" + + +class Solver: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + A high-level API to conda's solving logic. Three public methods are provided to access a + solution in various forms. + + * :meth:`solve_final_state` + * :meth:`solve_for_diff` + * :meth:`solve_for_transaction` + + """ + + def __init__( + self, prefix, channels, subdirs=(), specs_to_add=(), specs_to_remove=() + ): + """ + **Beta** + + Args: + prefix (str): + The conda prefix / environment location for which the :class:`Solver` + is being instantiated. + channels (Sequence[:class:`Channel`]): + A prioritized list of channels to use for the solution. + subdirs (Sequence[str]): + A prioritized list of subdirs to use for the solution. + specs_to_add (set[:class:`MatchSpec`]): + The set of package specs to add to the prefix. + specs_to_remove (set[:class:`MatchSpec`]): + The set of package specs to remove from the prefix. + + """ + solver_backend = context.plugin_manager.get_cached_solver_backend() + self._internal = solver_backend( + prefix, channels, subdirs, specs_to_add, specs_to_remove + ) + + def solve_final_state( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives the final, solved state of the environment. + + Args: + deps_modifier (DepsModifier): + An optional flag indicating special solver handling for dependencies. The + default solver behavior is to be as conservative as possible with dependency + updates (in the case the dependency already exists in the environment), while + still ensuring all dependencies are satisfied. Options include + * NO_DEPS + * ONLY_DEPS + * UPDATE_DEPS + * UPDATE_DEPS_ONLY_DEPS + * FREEZE_INSTALLED + prune (bool): + If ``True``, the solution will not contain packages that were + previously brought into the environment as dependencies but are no longer + required as dependencies and are not user-requested. + ignore_pinned (bool): + If ``True``, the solution will ignore pinned package configuration + for the prefix. + force_remove (bool): + Forces removal of a package without removing packages that depend on it. + + Returns: + tuple[PackageRef]: + In sorted dependency order from roots to leaves, the package references for + the solved state of the environment. + + """ + return self._internal.solve_final_state( + update_modifier, deps_modifier, prune, ignore_pinned, force_remove + ) + + def solve_for_diff( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=False, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives the package references to remove from an environment, followed by + the package references to add to an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + For requested specs_to_add that are already satisfied in the environment, + instructs the solver to remove the package and spec from the environment, + and then add it back--possibly with the exact package instance modified, + depending on the spec exactness. + + Returns: + tuple[PackageRef], tuple[PackageRef]: + A two-tuple of PackageRef sequences. The first is the group of packages to + remove from the environment, in sorted dependency order from leaves to roots. + The second is the group of packages to add to the environment, in sorted + dependency order from roots to leaves. + + """ + return self._internal.solve_for_diff( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + force_reinstall, + ) + + def solve_for_transaction( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=False, + ): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Gives an UnlinkLinkTransaction instance that can be used to execute the solution + on an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + See :meth:`solve_for_diff`. + + Returns: + UnlinkLinkTransaction: + + """ + return self._internal.solve_for_transaction( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + force_reinstall, + ) + + +class SubdirData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of repodata.json for subdirs. + """ + + def __init__(self, channel): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + channel (str or Channel): + The target subdir for the instance. Must either be a url that includes a subdir + or a :obj:`Channel` that includes a subdir. e.g.: + * 'https://repo.anaconda.com/pkgs/main/linux-64' + * Channel('https://repo.anaconda.com/pkgs/main/linux-64') + * Channel('conda-forge/osx-64') + """ + channel = Channel(channel) + if not channel.subdir: + raise ValueError("SubdirData requires platform-aware Channel objects.") + self._internal = _SubdirData(channel) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific instance of repodata. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PackageRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + @staticmethod + def query_all(package_ref_or_match_spec, channels=None, subdirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against all repodata instances in channel/subdir matrix. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + channels (Iterable[Channel or str] or None): + An iterable of urls for channels or :obj:`Channel` objects. If None, will fall + back to context.channels. + subdirs (Iterable[str] or None): + If None, will fall back to context.subdirs. + + Returns: + tuple[PackageRecord] + + """ + return tuple( + _SubdirData.query_all(package_ref_or_match_spec, channels, subdirs) + ) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PackageRecord]: A generator over all records contained in the repodata.json + instance. Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. repodata.json) + is lazily downloaded/loaded on first use by the other methods of this class. You + should only use this method if you are *sure* you have outdated data. + + Returns: + SubdirData + + """ + self._internal = self._internal.reload() + return self + + +class PackageCacheData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of package caches. + """ + + def __init__(self, pkgs_dir): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + pkgs_dir (str): + """ + self._internal = _PackageCacheData(pkgs_dir) + + def get(self, package_ref, default=NULL): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + package_ref (PackageRef): + A :obj:`PackageRef` instance representing the key for the + :obj:`PackageCacheRecord` being sought. + default: The default value to return if the record does not exist. If not + specified and no record exists, :exc:`KeyError` is raised. + + Returns: + PackageCacheRecord + + """ + return self._internal.get(package_ref, default) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific package cache instance. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PackageCacheRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + @staticmethod + def query_all(package_ref_or_match_spec, pkgs_dirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against all package caches. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + pkgs_dirs (Iterable[str] or None): + If None, will fall back to context.pkgs_dirs. + + Returns: + tuple[PackageCacheRecord] + + """ + return tuple(_PackageCacheData.query_all(package_ref_or_match_spec, pkgs_dirs)) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PackageCacheRecord]: A generator over all records contained in the package + cache instance. Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + @property + def is_writable(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Indicates if the package cache location is writable or read-only. + + Returns: + bool + + """ + return self._internal.is_writable + + @staticmethod + def first_writable(pkgs_dirs=None): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Get an instance object for the first writable package cache. + + Args: + pkgs_dirs (Iterable[str]): + If None, will fall back to context.pkgs_dirs. + + Returns: + PackageCacheData: + An instance for the first writable package cache. + + """ + return PackageCacheData(_PackageCacheData.first_writable(pkgs_dirs).pkgs_dir) + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. contents of + the pkgs_dir) is lazily loaded on first use by the other methods of this class. You + should only use this method if you are *sure* you have outdated data. + + Returns: + PackageCacheData + + """ + self._internal = self._internal.reload() + return self + + +class PrefixData: + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + High-level management and usage of conda environment prefixes. + """ + + def __init__(self, prefix_path): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + prefix_path (str): + """ + self._internal = _PrefixData(prefix_path) + + def get(self, package_ref, default=NULL): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Args: + package_ref (PackageRef): + A :obj:`PackageRef` instance representing the key for the + :obj:`PrefixRecord` being sought. + default: The default value to return if the record does not exist. If not + specified and no record exists, :exc:`KeyError` is raised. + + Returns: + PrefixRecord + + """ + return self._internal.get(package_ref.name, default) + + def query(self, package_ref_or_match_spec): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Run a query against this specific prefix instance. + + Args: + package_ref_or_match_spec (PackageRef or MatchSpec or str): + Either an exact :obj:`PackageRef` to match against, or a :obj:`MatchSpec` + query object. A :obj:`str` will be turned into a :obj:`MatchSpec` automatically. + + Returns: + tuple[PrefixRecord] + + """ + return tuple(self._internal.query(package_ref_or_match_spec)) + + def iter_records(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Returns: + Iterable[PrefixRecord]: A generator over all records contained in the prefix. + Warning: this is a generator that is exhausted on first use. + + """ + return self._internal.iter_records() + + @property + def is_writable(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Indicates if the prefix is writable or read-only. + + Returns: + bool or None: + True if the prefix is writable. False if read-only. None if the prefix + does not exist as a conda environment. + + """ + return self._internal.is_writable + + def reload(self): + """ + **Beta** While in beta, expect both major and minor changes across minor releases. + + Update the instance with new information. Backing information (i.e. contents of + the conda-meta directory) is lazily loaded on first use by the other methods of this + class. You should only use this method if you are *sure* you have outdated data. + + Returns: + PrefixData + + """ + self._internal = self._internal.reload() + return self diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/LICENSE b/miniconda3/lib/python3.13/site-packages/conda/auxlib/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a8c7830ae0403396b45fb4fcfd0e6ca72789eaa4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/LICENSE @@ -0,0 +1,15 @@ +ISC License (https://en.wikipedia.org/wiki/ISC_license) + +Copyright (c) 2015, Kale Franz + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85dd85928ffe4a0a2a1a64bd696df6f3a67de4bb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/__init__.py @@ -0,0 +1,90 @@ +"""Auxlib is an auxiliary library to the python standard library. + +The aim is to provide core generic features for app development in python. Auxlib fills in some +python stdlib gaps much like `pytoolz `_ has for functional +programming, `pyrsistent `_ has for data structures, or +`boltons `_ has generally. + +Major areas addressed include: + - :ref:`packaging`: package versioning, with a clean and less invasive alternative to + versioneer + - :ref:`entity`: robust base class for type-enforced data models and transfer objects + - :ref:`type_coercion`: intelligent type coercion utilities + - :ref:`configuration`: a map implementation designed specifically to hold application + configuration and context information + - :ref:`factory`: factory pattern implementation + - :ref:`path`: file path utilities especially helpful when working with various python + package formats + - :ref:`logz`: logging initialization routines to simplify python logging setup + - :ref:`crypt`: simple, but correct, pycrypto wrapper + +[2021-11-09] Our version of auxlib has deviated from the upstream project by a significant amount +(especially compared with the other vendored packages). Further, the upstream project has low +popularity and is no longer actively maintained. Consequently it was decided to absorb, refactor, +and replace auxlib. As a first step of this process we moved conda._vendor.auxlib to conda.auxlib. +""" + +# don't mess up logging for library users +from logging import getLogger, Handler +class NullHandler(Handler): # NOQA + def emit(self, record): + pass + + +getLogger('auxlib').addHandler(NullHandler()) + +__all__ = [ + "__version__", "__author__", + "__email__", "__license__", "__copyright__", + "__summary__", "__url__", +] + +__version__ = "0.0.43" + +__author__ = 'Kale Franz' +__email__ = 'kale@franz.io' +__url__ = 'https://github.com/kalefranz/auxlib' +__license__ = "ISC" +__copyright__ = "(c) 2015 Kale Franz. All rights reserved." +__summary__ = """auxiliary library to the python standard library""" + + +class _Null: + """ + Examples: + >>> len(_Null()) + 0 + >>> bool(_Null()) + False + >>> _Null().__nonzero__() + False + """ + def __nonzero__(self): + return self.__bool__() + + def __bool__(self): + return False + + def __len__(self): + return 0 + + def __eq__(self, other): + return isinstance(other, _Null) + + def __hash__(self): + return hash(_Null) + + def __str__(self): + return 'Null' + + def __json__(self): + return 'null' + + to_json = __json__ + + +# Use this NULL object when needing to distinguish a value from None +# For example, when parsing json, you may need to determine if a json key was given and set +# to null, or the key didn't exist at all. There could be a bit of potential confusion here, +# because in python null == None, while here I'm defining NULL to mean 'not defined'. +NULL = _Null() diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/collection.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/collection.py new file mode 100644 index 0000000000000000000000000000000000000000..355166377ad697a03e9f85702aa5616df151feda --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/collection.py @@ -0,0 +1,62 @@ +"""Common collection classes.""" +from functools import reduce +from collections.abc import Mapping, Set + +from frozendict import frozendict + +from ..deprecations import deprecated +from ..common.compat import isiterable + + +# http://stackoverflow.com/a/14620633/2127762 +class AttrDict(dict): + """Sub-classes dict, and further allows attribute-like access to dictionary items. + + Examples: + >>> d = AttrDict({'a': 1}) + >>> d.a, d['a'], d.get('a') + (1, 1, 1) + >>> d.b = 2 + >>> d.b, d['b'] + (2, 2) + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.__dict__ = self + + +def first(seq, key=bool, default=None, apply=lambda x: x): + """Give the first value that satisfies the key test. + + Args: + seq (iterable): + key (callable): test for each element of iterable + default: returned when all elements fail test + apply (callable): applied to element before return, but not to default value + + Returns: first element in seq that passes key, mutated with optional apply + + Examples: + >>> first([0, False, None, [], (), 42]) + 42 + >>> first([0, False, None, [], ()]) is None + True + >>> first([0, False, None, [], ()], default='ohai') + 'ohai' + >>> import re + >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)']) + >>> m.group(1) + 'bc' + + The optional `key` argument specifies a one-argument predicate function + like that used for `filter()`. The `key` argument, if supplied, must be + in keyword form. For example: + >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0) + 4 + + """ + return next((apply(x) for x in seq if key(x)), default() if callable(default) else default) + + +def last(seq, key=bool, default=None, apply=lambda x: x): + return next((apply(x) for x in reversed(seq) if key(x)), default) diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/compat.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..66626d21cc51c461d59a6e2c66805197e26255b5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/compat.py @@ -0,0 +1,43 @@ +from collections import OrderedDict as odict # noqa: F401 +import os +from shlex import split + +from ..deprecations import deprecated + + +@deprecated("26.3", "26.9", addendum="Use `conda.common.compat.isiterable` instead.") +def isiterable(obj): + # and not a string + from collections.abc import Iterable + return not isinstance(obj, str) and isinstance(obj, Iterable) + + +# shlex.split() is a poor function to use for anything general purpose (like calling subprocess). +# It mishandles Unicode in Python 3 but all is not lost. We can escape it, then escape the escapes +# then call shlex.split() then un-escape that. +def shlex_split_unicode(to_split, posix=True): + # shlex.split does its own un-escaping that we must counter. + e_to_split = to_split.replace("\\", "\\\\") + return split(e_to_split, posix=posix) + + +def Utf8NamedTemporaryFile( + mode="w+b", buffering=-1, newline=None, suffix=None, prefix=None, dir=None, delete=True +): + from tempfile import NamedTemporaryFile + + if "CONDA_TEST_SAVE_TEMPS" in os.environ: + delete = False + encoding = None + if "b" not in mode: + encoding = "utf-8" + return NamedTemporaryFile( + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/decorators.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..c45121fd81d6d7372065417dd0a5b0b48165692f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/decorators.py @@ -0,0 +1,216 @@ +from collections.abc import Hashable +from types import GeneratorType + +from functools import wraps + + +# TODO: spend time filling out functionality and make these more robust + + +def memoizemethod(method): + """ + Decorator to cause a method to cache it's results in self for each + combination of inputs and return the cached result on subsequent calls. + Does not support named arguments or arg values that are not hashable. + + >>> class Foo (object): + ... @memoizemethod + ... def foo(self, x, y=0): + ... print('running method with', x, y) + ... return x + y + 3 + ... + >>> foo1 = Foo() + >>> foo2 = Foo() + >>> foo1.foo(10) + running method with 10 0 + 13 + >>> foo1.foo(10) + 13 + >>> foo2.foo(11, y=7) + running method with 11 7 + 21 + >>> foo2.foo(11) + running method with 11 0 + 14 + >>> foo2.foo(11, y=7) + 21 + >>> class Foo (object): + ... def __init__(self, lower): + ... self.lower = lower + ... @memoizemethod + ... def range_tuple(self, upper): + ... print('running function') + ... return tuple(i for i in range(self.lower, upper)) + ... @memoizemethod + ... def range_iter(self, upper): + ... print('running function') + ... return (i for i in range(self.lower, upper)) + ... + >>> foo = Foo(3) + >>> foo.range_tuple(6) + running function + (3, 4, 5) + >>> foo.range_tuple(7) + running function + (3, 4, 5, 6) + >>> foo.range_tuple(6) + (3, 4, 5) + >>> foo.range_iter(6) + Traceback (most recent call last): + TypeError: Can't memoize a generator or non-hashable object! + """ + + @wraps(method) + def _wrapper(self, *args, **kwargs): + # NOTE: a __dict__ check is performed here rather than using the + # built-in hasattr function because hasattr will look up to an object's + # class if the attr is not directly found in the object's dict. That's + # bad for this if the class itself has a memoized classmethod for + # example that has been called before the memoized instance method, + # then the instance method will use the class's result cache, causing + # its results to be globally stored rather than on a per instance + # basis. + if '_memoized_results' not in self.__dict__: + self._memoized_results = {} + memoized_results = self._memoized_results + + key = (method.__name__, args, tuple(sorted(kwargs.items()))) + if key in memoized_results: + return memoized_results[key] + else: + try: + result = method(self, *args, **kwargs) + except KeyError as e: + if '__wrapped__' in str(e): + result = None # is this the right thing to do? happened during py3 conversion + else: + raise + if isinstance(result, GeneratorType) or not isinstance(result, Hashable): + raise TypeError("Can't memoize a generator or non-hashable object!") + return memoized_results.setdefault(key, result) + + return _wrapper + + +def clear_memoized_methods(obj, *method_names): + """ + Clear the memoized method or @memoizedproperty results for the given + method names from the given object. + + >>> v = [0] + >>> def inc(): + ... v[0] += 1 + ... return v[0] + ... + >>> class Foo(object): + ... @memoizemethod + ... def foo(self): + ... return inc() + ... @memoizedproperty + ... def g(self): + ... return inc() + ... + >>> f = Foo() + >>> f.foo(), f.foo() + (1, 1) + >>> clear_memoized_methods(f, 'foo') + >>> (f.foo(), f.foo(), f.g, f.g) + (2, 2, 3, 3) + >>> (f.foo(), f.foo(), f.g, f.g) + (2, 2, 3, 3) + >>> clear_memoized_methods(f, 'g', 'no_problem_if_undefined') + >>> f.g, f.foo(), f.g + (4, 2, 4) + >>> f.foo() + 2 + """ + for key in list(getattr(obj, '_memoized_results', {}).keys()): + # key[0] is the method name + if key[0] in method_names: + del obj._memoized_results[key] + + property_dict = obj._cache_ + for prop in method_names: + inner_attname = '__%s' % prop + if inner_attname in property_dict: + del property_dict[inner_attname] + + +def memoizedproperty(func): + """ + Decorator to cause a method to cache it's results in self for each + combination of inputs and return the cached result on subsequent calls. + Does not support named arguments or arg values that are not hashable. + + >>> class Foo (object): + ... _x = 1 + ... @memoizedproperty + ... def foo(self): + ... self._x += 1 + ... print('updating and returning {0}'.format(self._x)) + ... return self._x + ... + >>> foo1 = Foo() + >>> foo2 = Foo() + >>> foo1.foo + updating and returning 2 + 2 + >>> foo1.foo + 2 + >>> foo2.foo + updating and returning 2 + 2 + >>> foo1.foo + 2 + """ + inner_attname = '__%s' % func.__name__ + + def new_fget(self): + if not hasattr(self, '_cache_'): + self._cache_ = {} + cache = self._cache_ + if inner_attname not in cache: + cache[inner_attname] = func(self) + return cache[inner_attname] + + return property(new_fget) + + +class classproperty: # pylint: disable=C0103 + # from celery.five + + def __init__(self, getter=None, setter=None): + if getter is not None and not isinstance(getter, classmethod): + getter = classmethod(getter) + if setter is not None and not isinstance(setter, classmethod): + setter = classmethod(setter) + self.__get = getter + self.__set = setter + + info = getter.__get__(object) # just need the info attrs. + self.__doc__ = info.__doc__ + self.__name__ = info.__name__ + self.__module__ = info.__module__ + + def __get__(self, obj, type_=None): + if obj and type_ is None: + type_ = obj.__class__ + return self.__get.__get__(obj, type_)() + + def __set__(self, obj, value): + if obj is None: + return self + return self.__set.__get__(obj)(value) + + def setter(self, setter): + return self.__class__(self.__get, setter) + +# memoize & clear: +# class method +# function +# classproperty +# property +# staticproperty? +# memoizefunction +# memoizemethod +# memoizedproperty diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/entity.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/entity.py new file mode 100644 index 0000000000000000000000000000000000000000..404adc6f8d120e4f811e59332fa21f8ad534e548 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/entity.py @@ -0,0 +1,982 @@ +""" +This module provides serializable, validatable, type-enforcing domain objects and data +transfer objects. It has many of the same motivations as the python +`Marshmallow `_ package. It is most +similar to `Schematics `_. + +======== +Tutorial +======== + +Chapter 1: Entity and Field Basics +---------------------------------- + + >>> class Color(Enum): + ... blue = 0 + ... black = 1 + ... red = 2 + >>> class Car(Entity): + ... weight = NumberField(required=False) + ... wheels = IntField(default=4, validation=lambda x: 3 <= x <= 4) + ... color = EnumField(Color) + + >>> # create a new car object + >>> car = Car(color=Color.blue, weight=4242.46) + >>> car + Car(weight=4242.46, color=0) + + >>> # it has 4 wheels, all by default + >>> car.wheels + 4 + + >>> # but a car can't have 5 wheels! + >>> # the `validation=` field is a simple callable that returns a + >>> # boolean based on validity + >>> car.wheels = 5 + Traceback (most recent call last): + ValidationError: Invalid value 5 for wheels + + >>> # we can call .dump() on car, and just get back a standard + >>> # python dict actually, it's an ordereddict to match attribute + >>> # declaration order + >>> type(car.dump()) + + >>> car.dump() + OrderedDict([('weight', 4242.46), ('wheels', 4), ('color', 0)]) + + >>> # and json too (note the order!) + >>> car.json() + '{"weight": 4242.46, "wheels": 4, "color": 0}' + + >>> # green cars aren't allowed + >>> car.color = "green" + Traceback (most recent call last): + ValidationError: 'green' is not a valid Color + + >>> # but black cars are! + >>> car.color = "black" + >>> car.color + + + >>> # car.color really is an enum, promise + >>> type(car.color) + + + >>> # enum assignment can be with any of (and preferentially) + >>> # (1) an enum literal, + >>> # (2) a valid enum value, or + >>> # (3) a valid enum name + >>> car.color = Color.blue; car.color.value + 0 + >>> car.color = 1; car.color.name + 'black' + + >>> # let's do a round-trip marshalling of this thing + >>> same_car = Car.from_json(car.json()) # or equally Car.from_json(json.dumps(car.dump())) + >>> same_car == car + True + + >>> # actually, they're two different instances + >>> same_car is not car + True + + >>> # this works too + >>> cloned_car = Car(**car.dump()) + >>> cloned_car == car + True + + >>> # while we're at it, these are all equivalent too + >>> car == Car.from_objects(car) + True + >>> car == Car.from_objects({"weight": 4242.46, "wheels": 4, "color": 1}) + True + >>> car == Car.from_json('{"weight": 4242.46, "color": 1}') + True + + >>> # .from_objects() even lets you stack and combine objects + >>> class DumbClass: + ... color = 0 + ... wheels = 3 + >>> Car.from_objects(DumbClass(), dict(weight=2222, color=1)) + Car(weight=2222, wheels=3, color=0) + >>> # and also pass kwargs that override properties pulled + >>> # off any objects + >>> Car.from_objects(DumbClass(), {'weight': 2222, 'color': 1}, color=2, weight=33) + Car(weight=33, wheels=3, color=2) + + +Chapter 2: Entity and Field Composition +--------------------------------------- + + >>> # now let's get fancy + >>> # a ComposableField "nests" another valid Entity + >>> # a ListField's first argument is a "generic" type, + >>> # which can be a valid Entity, any python primitive + >>> # type, or a list of Entities/types + >>> class Fleet(Entity): + ... boss_car = ComposableField(Car) + ... cars = ListField(Car) + + >>> # here's our fleet of company cars + >>> company_fleet = Fleet(boss_car=Car(color='red'), cars=[car, same_car, cloned_car]) + >>> company_fleet.pretty_json() #doctest: +SKIP + { + "boss_car": { + "wheels": 4 + "color": 2, + }, + "cars": [ + { + "weight": 4242.46, + "wheels": 4 + "color": 1, + }, + { + "weight": 4242.46, + "wheels": 4 + "color": 1, + }, + { + "weight": 4242.46, + "wheels": 4 + "color": 1, + } + ] + } + + >>> # the boss' car is red of course (and it's still an Enum) + >>> company_fleet.boss_car.color.name + 'red' + + >>> # and there are three cars left for the employees + >>> len(company_fleet.cars) + 3 + + +Chapter 3: Immutability +----------------------- + + >>> class ImmutableCar(ImmutableEntity): + ... wheels = IntField(default=4, validation=lambda x: 3 <= x <= 4) + ... color = EnumField(Color) + >>> icar = ImmutableCar.from_objects({'wheels': 3, 'color': 'blue'}) + >>> icar + ImmutableCar(wheels=3, color=0) + + >>> icar.wheels = 4 + Traceback (most recent call last): + AttributeError: Assignment not allowed. ImmutableCar is immutable. + + >>> class FixedWheelCar(Entity): + ... wheels = IntField(default=4, immutable=True) + ... color = EnumField(Color) + >>> fwcar = FixedWheelCar.from_objects(icar) + >>> fwcar.json() + '{"wheels": 3, "color": 0}' + + >>> # repainting the car is easy + >>> fwcar.color = Color.red + >>> fwcar.color.name + 'red' + + >>> # can't really change the number of wheels though + >>> fwcar.wheels = 18 + Traceback (most recent call last): + AttributeError: The wheels field is immutable. + + +Chapter X: The del and null Weeds +--------------------------------- + + >>> old_date = lambda: isoparse('1982-02-17') + >>> class CarBattery(Entity): + ... # NOTE: default value can be a callable! + ... first_charge = DateField(required=False) # default=None, nullable=False + ... latest_charge = DateField(default=old_date, nullable=True) # required=True + ... expiration = DateField(default=old_date, required=False, nullable=False) + + >>> # starting point + >>> battery = CarBattery() + >>> battery + CarBattery() + >>> battery.json() + '{"latest_charge": "1982-02-17T00:00:00", "expiration": "1982-02-17T00:00:00"}' + + >>> # first_charge is not assigned a default value. Once one is assigned, it can be deleted, + >>> # but it can't be made null. + >>> battery.first_charge = isoparse('2016-03-23') + >>> battery + CarBattery(first_charge=datetime.datetime(2016, 3, 23, 0, 0)) + >>> battery.first_charge = None + Traceback (most recent call last): + ValidationError: Value for first_charge not given or invalid. + >>> del battery.first_charge + >>> battery + CarBattery() + + >>> # latest_charge can be null, but it can't be deleted. The default value is a callable. + >>> del battery.latest_charge + Traceback (most recent call last): + AttributeError: The latest_charge field is required and cannot be deleted. + >>> battery.latest_charge = None + >>> battery.json() + '{"latest_charge": null, "expiration": "1982-02-17T00:00:00"}' + + >>> # expiration is assigned by default, can't be made null, but can be deleted. + >>> battery.expiration + datetime.datetime(1982, 2, 17, 0, 0) + >>> battery.expiration = None + Traceback (most recent call last): + ValidationError: Value for expiration not given or invalid. + >>> del battery.expiration + >>> battery.json() + '{"latest_charge": null}' + + +""" + +from collections.abc import Mapping, Sequence +from datetime import datetime +from enum import Enum +from functools import reduce +from logging import getLogger +from pathlib import Path + +from boltons.timeutils import isoparse +from frozendict import deepfreeze, frozendict +from frozendict import getFreezeConversionMap as _getFreezeConversionMap +from frozendict import register as _register + +from . import NULL +from .compat import odict +from ..common.compat import isiterable +from .collection import AttrDict +from .exceptions import Raise, ValidationError +from .ish import find_or_raise +from .type_coercion import maybecall +from ..common.serialize import json +from ..deprecations import deprecated + +if Enum not in _getFreezeConversionMap(): + # leave enums as is, deepfreeze will flatten it into a dict + # see https://github.com/Marco-Sulla/python-frozendict/issues/98 + _register(Enum, lambda x : x) + +del _getFreezeConversionMap +del _register + +log = getLogger(__name__) + +__all__ = [ + "Entity", "ImmutableEntity", "Field", + "BooleanField", "BoolField", "IntegerField", "IntField", + "NumberField", "StringField", "DateField", + "EnumField", "ListField", "MapField", "ComposableField", +] + +KEY_OVERRIDES_MAP = "__key_overrides__" + + +NOTES = """ + +Current deficiencies to schematics: + - no get_mock_object method + - no context-dependent serialization or MultilingualStringType + - name = StringType(serialized_name='person_name', alternate_names=['human_name']) + - name = StringType(serialize_when_none=False) + - more flexible validation error messages + - field validation can depend on other fields + - 'roles' containing denylists for .dump() and .json() + __roles__ = { + EntityRole.registered_name: Denylist('field1', 'field2'), + EntityRole.another_registered_name: Allowlist('field3', 'field4'), + } + + +TODO: + - alternate field names + - add dump_if_null field option + - add help/description parameter to Field + - consider leveraging slots + - collect all validation errors before raising + - Allow returning string error message for validation instead of False + - profile and optimize + - use boltons instead of dateutil + - correctly implement copy and deepcopy on fields and Entity, DictSafeMixin + http://stackoverflow.com/questions/1500718/what-is-the-right-way-to-override-the-copy-deepcopy-operations-on-an-object-in-p + + +Optional Field Properties: + - validation = None + - default = None + - required = True + - in_dump = True + - nullable = False + +Behaviors: + - Nullable is a "hard" setting, in that the value is either always or never allowed to be None. + - What happens then if required=False and nullable=False? + - The object can be init'd without a value (though not with a None value). + getattr throws AttributeError + - Any assignment must be not None. + + + - Setting a value to None doesn't "unset" a value. (That's what del is for.) And you can't + del a value if required=True, nullable=False, default=None. + + - If a field is not required, del does *not* "unmask" the default value. Instead, del + removes the value from the object entirely. To get back the default value, need to recreate + the object. Entity.from_objects(old_object) + + + - Disabling in_dump is a "hard" setting, in that with it disabled the field will never get + dumped. With it enabled, the field may or may not be dumped depending on its value and other + settings. + + - Required is a "hard" setting, in that if True, a valid value or default must be provided. None + is only a valid value or default if nullable is True. + + - In general, nullable means that None is a valid value. + - getattr returns None instead of raising Attribute error + - If in_dump, field is given with null value. + - If default is not None, assigning None clears a previous assignment. Future getattrs return + the default value. + - What does nullable mean with default=None and required=True? Does instantiation raise + an error if assignment not made on init? Can IntField(nullable=True) be init'd? + + - If required=False and nullable=False, field will only be in dump if field!=None. + Also, getattr raises AttributeError. + - If required=False and nullable=True, field will be in dump if field==None. + + - If in_dump is True, does default value get dumped: + - if no assignment, default exists + - if nullable, and assigned None + - How does optional validation work with nullable and assigning None? + - When does gettattr throw AttributeError, and when does it return None? + + + +""" + + +class Field: + """ + Fields are doing something very similar to boxing and unboxing + of c#/java primitives. __set__ should take a "primitive" or "raw" value and create a "boxed" + or "programmatically usable" value of it. While __get__ should return the boxed value, + dump in turn should unbox the value into a primitive or raw value. + + Arguments: + types_ (primitive literal or type or sequence of types): + default (any, callable, optional): If default is callable, it's guaranteed to return a + valid value at the time of Entity creation. + required (boolean, optional): + validation (callable, optional): + dump (boolean, optional): + """ + + # Used to track order of field declarations. Supporting python 2.7, so can't rely + # on __prepare__. Strategy lifted from http://stackoverflow.com/a/4460034/2127762 + _order_helper = 0 + + def __init__(self, default=NULL, required=True, validation=None, + in_dump=True, default_in_dump=True, nullable=False, immutable=False, aliases=()): + self._required = required + self._validation = validation + self._in_dump = in_dump + self._default_in_dump = default_in_dump + self._nullable = nullable + self._immutable = immutable + self._aliases = aliases + if default is NULL: + self._default = NULL + else: + self._default = default if callable(default) else self.box(None, None, default) + self.validate(None, self.box(None, None, maybecall(default))) + + self._order_helper = Field._order_helper + Field._order_helper += 1 + + @property + def name(self): + try: + return self._name + except AttributeError: + log.error("The name attribute has not been set for this field. " + "Call set_name at class creation time.") + raise + + def set_name(self, name): + self._name = name + return self + + def __get__(self, instance, instance_type): + try: + if instance is None: # if calling from the class object + val = getattr(instance_type, KEY_OVERRIDES_MAP)[self.name] + else: + val = instance.__dict__[self.name] + except AttributeError: + log.error("The name attribute has not been set for this field.") + raise AttributeError("The name attribute has not been set for this field.") + except KeyError: + if self.default is NULL: + raise AttributeError(f"A value for {self.name} has not been set") + else: + val = maybecall(self.default) # default *can* be a callable + if val is None and not self.nullable: + # means the "tricky edge case" was activated in __delete__ + raise AttributeError(f"The {self.name} field has been deleted.") + return self.unbox(instance, instance_type, val) + + def __set__(self, instance, val): + if self.immutable and instance._initd: + raise AttributeError(f"The {self.name} field is immutable.") + # validate will raise an exception if invalid + # validate will return False if the value should be removed + instance.__dict__[self.name] = self.validate( + instance, + self.box(instance, instance.__class__, val), + ) + + def __delete__(self, instance): + if self.immutable and instance._initd: + raise AttributeError(f"The {self.name} field is immutable.") + elif self.required: + raise AttributeError(f"The {self.name} field is required and cannot be deleted.") + elif not self.nullable: + # tricky edge case + # given a field Field(default='some value', required=False, nullable=False) + # works together with Entity.dump() logic for selecting fields to include in dump + # `if value is not None or field.nullable` + instance.__dict__[self.name] = None + else: + instance.__dict__.pop(self.name, None) + + def box(self, instance, instance_type, val): + return val + + def unbox(self, instance, instance_type, val): + return val + + def dump(self, instance, instance_type, val): + return val + + def validate(self, instance, val): + """ + + Returns: + True: if val is valid + + Raises: + ValidationError + """ + # note here calling, but not assigning; could lead to unexpected behavior + if isinstance(val, self._type) and (self._validation is None or self._validation(val)): + return val + elif val is NULL and not self.required: + return val + elif val is None and self.nullable: + return val + else: + raise ValidationError(getattr(self, 'name', 'undefined name'), val) + + @property + def required(self): + return self._required + + @property + def type(self): + return self._type + + @property + def default(self): + return self._default + + @property + def in_dump(self): + return self._in_dump + + @property + def default_in_dump(self): + return self._default_in_dump + + @property + def nullable(self): + return self.is_nullable + + @property + def is_nullable(self): + return self._nullable + + @property + def immutable(self): + return self._immutable + + +class BooleanField(Field): + _type = bool + + def box(self, instance, instance_type, val): + return None if val is None else bool(val) + + +BoolField = BooleanField + + +class IntegerField(Field): + _type = int + + +IntField = IntegerField + + +class NumberField(Field): + _type = (int, float, complex) + + +class StringField(Field): + _type = str + + def box(self, instance, instance_type, val): + return str(val) if isinstance(val, NumberField._type) else val + + +class DateField(Field): + _type = datetime + + def box(self, instance, instance_type, val): + try: + return isoparse(val) if isinstance(val, str) else val + except ValueError as e: + raise ValidationError(val, msg=e) + + def dump(self, instance, instance_type, val): + return None if val is None else val.isoformat() + + +class EnumField(Field): + + def __init__(self, enum_class, default=NULL, required=True, validation=None, + in_dump=True, default_in_dump=True, nullable=False, immutable=False, aliases=()): + if not issubclass(enum_class, Enum): + raise ValidationError(None, msg="enum_class must be an instance of Enum") + self._type = enum_class + super().__init__( + default, required, validation, in_dump, default_in_dump, nullable, immutable, aliases + ) + + def box(self, instance, instance_type, val): + if val is None: + # let the required/nullable logic handle validation for this case + return None + try: + # try to box using val as an Enum name + return self._type(val) + except ValueError as e1: + try: + # try to box using val as an Enum value + return self._type[val] + except KeyError: + raise ValidationError(val, msg=e1) + + def dump(self, instance, instance_type, val): + return None if val in (None, NULL) else val.value + + +class ListField(Field): + _type = tuple + + def __init__(self, element_type, default=NULL, required=True, validation=None, + in_dump=True, default_in_dump=True, nullable=False, immutable=False, aliases=()): + self._element_type = element_type + super().__init__( + default, required, validation, in_dump, default_in_dump, nullable, immutable, aliases + ) + + def box(self, instance, instance_type, val): + if val is None: + return None + elif isinstance(val, str): + raise ValidationError( + f"Attempted to assign a string to ListField {self.name}" + ) + elif isiterable(val): + et = self._element_type + if isinstance(et, type) and issubclass(et, Entity): + return self._type(v if isinstance(v, et) else et(**v) for v in val) + else: + return deepfreeze(val) if self.immutable else self._type(val) + else: + raise ValidationError( + val, msg=f"Cannot assign a non-iterable value to {self.name}" + ) + + def unbox(self, instance, instance_type, val): + return self._type() if val is None and not self.nullable else val + + def dump(self, instance, instance_type, val): + if isinstance(self._element_type, type) and issubclass(self._element_type, Entity): + return self._type(v.dump() for v in val) + else: + return val + + def validate(self, instance, val): + val = super().validate(instance, val) + if val: + et = self._element_type + self._type(Raise(ValidationError(self.name, el, et)) for el in val + if not isinstance(el, et)) + return val + + +class MutableListField(ListField): + _type = list + + +class MapField(Field): + _type = frozendict + + def __init__( + self, + default=NULL, + required=True, + validation=None, + in_dump=True, + default_in_dump=True, + nullable=False, + immutable=True, + aliases=(), + ): + super().__init__( + default, required, validation, in_dump, default_in_dump, nullable, immutable, aliases + ) + + def box(self, instance, instance_type, val): + # TODO: really need to make this recursive to make any lists or maps immutable + if val is None: + return self._type() + elif isiterable(val): + val = deepfreeze(val) + if not isinstance(val, Mapping): + raise ValidationError( + val, msg=f"Cannot assign a non-iterable value to {self.name}" + ) + return val + else: + raise ValidationError( + val, msg=f"Cannot assign a non-iterable value to {self.name}" + ) + + +class ComposableField(Field): + + def __init__(self, field_class, default=NULL, required=True, validation=None, + in_dump=True, default_in_dump=True, nullable=False, immutable=False, aliases=()): + self._type = field_class + super().__init__( + default, required, validation, in_dump, default_in_dump, nullable, immutable, aliases + ) + + def box(self, instance, instance_type, val): + if val is None: + return None + if isinstance(val, self._type): + return val + else: + # assuming val is a dict now + try: + # if there is a key named 'self', have to rename it + if hasattr(val, 'pop'): + val['slf'] = val.pop('self') + except KeyError: + pass # no key of 'self', so no worries + if isinstance(val, self._type): + return val if isinstance(val, self._type) else self._type(**val) + elif isinstance(val, Mapping): + return self._type(**val) + elif isinstance(val, Sequence) and not isinstance(val, str): + return self._type(*val) + else: + return self._type(val) + + def dump(self, instance, instance_type, val): + return None if val is None else val.dump() + + +class EntityType(type): + + @staticmethod + def __get_entity_subclasses(bases): + try: + return [base for base in bases if issubclass(base, Entity) and base is not Entity] + except NameError: + # NameError: global name 'Entity' is not defined + return () + + def __new__(mcs, name, bases, dct): + # if we're about to mask a field that's already been created with something that's + # not a field, then assign it to an alternate variable name + non_field_keys = ( + key + for key, value in dct.items() + if not isinstance(value, Field) and not key.startswith("__") + ) + entity_subclasses = EntityType.__get_entity_subclasses(bases) + if entity_subclasses: + keys_to_override = [key for key in non_field_keys + if any(isinstance(base.__dict__.get(key), Field) + for base in entity_subclasses)] + dct[KEY_OVERRIDES_MAP] = {key: dct.pop(key) for key in keys_to_override} + else: + dct[KEY_OVERRIDES_MAP] = {} + + return super().__new__(mcs, name, bases, dct) + + def __init__(cls, name, bases, attr): + super().__init__(name, bases, attr) + + fields = odict() + _field_sort_key = lambda x: x[1]._order_helper + for clz in reversed(type.mro(cls)): + clz_fields = ( + (name, field.set_name(name)) + for name, field in clz.__dict__.items() + if isinstance(field, Field) + ) + fields.update(sorted(clz_fields, key=_field_sort_key)) + + cls.__fields__ = frozendict(fields) + if hasattr(cls, '__register__'): + cls.__register__() + + def __call__(cls, *args, **kwargs): + instance = super().__call__(*args, **kwargs) + setattr(instance, f"_{cls.__name__}__initd", True) + return instance + + @property + def fields(cls): + return cls.__fields__.keys() + + +class Entity(metaclass=EntityType): + __fields__ = odict() + _lazy_validate = False + + def __init__(self, **kwargs): + for key, field in self.__fields__.items(): + try: + setattr(self, key, kwargs[key]) + except KeyError: + alias = next((ls for ls in field._aliases if ls in kwargs), None) + if alias is not None: + setattr(self, key, kwargs[alias]) + elif key in getattr(self, KEY_OVERRIDES_MAP): + # handle case of fields inherited from subclass but overrode on class object + setattr(self, key, getattr(self, KEY_OVERRIDES_MAP)[key]) + elif field.required and field.default is NULL: + raise ValidationError( + key, + msg="{} requires a {} field. Instantiated with " + "{}".format(self.__class__.__name__, key, kwargs), + ) + except ValidationError: + if kwargs[key] is not None or field.required: + raise + if not self._lazy_validate: + self.validate() + + @classmethod + def from_objects(cls, *objects, **override_fields): + """Construct a new object of type ``cls`` from existing objects or dicts. + + Allows the creation of new objects of concrete :class:`Entity` subclasses by + combining information from several sources. This can be any combination of + objects and dictionaries passed in as positional arguments. When looking for + the value of the fields of the :class:`Entity` subclass, the first object + that provides an attribute (or, in the case of a dict an entry) that has the + name of the field or one of its aliases will take precedence. Any keyword + arguments passed in will override this and take precedence. + + Args: + cls(:class:`Entity` subclass): The class to create, usually determined by call, e.g. ``PrefixRecord.from_objects(...)``. + *objects(tuple(object or dict)): Any combination of objects and dicts in order of decending precedence. + **override_fields(dict(str, object)): Any individual fields overriding possible contents from ``*objects``. + """ + init_vars = {} + search_maps = tuple(AttrDict(o) if isinstance(o, dict) else o + for o in ((override_fields,) + objects)) + for key, field in cls.__fields__.items(): + try: + init_vars[key] = find_or_raise(key, search_maps, field._aliases) + except AttributeError: + pass + + return cls(**init_vars) + + @classmethod + def from_json(cls, json_str): + return cls(**json.loads(json_str)) + + @classmethod + def load(cls, data_dict): + return cls(**data_dict) + + def validate(self): + # TODO: here, validate should only have to determine if the required keys are set + try: + reduce( + lambda _, name: getattr(self, name), + (name for name, field in self.__fields__.items() if field.required), + ) + except TypeError as e: + if str(e) == "reduce() of empty sequence with no initial value": + pass + except AttributeError as e: + raise ValidationError(None, msg=e) + + def __repr__(self): + def _valid(key): + # TODO: re-enable once aliases are implemented + # if key.startswith('_'): + # return False + if '__' in key: + return False + try: + getattr(self, key) + return True + except AttributeError: + return False + + def _val(key): + val = getattr(self, key) + return repr(val.value) if isinstance(val, Enum) else repr(val) + + def _sort_helper(key): + field = self.__fields__.get(key) + return field._order_helper if field is not None else -1 + + kwarg_str = ", ".join( + f"{key}={_val(key)}" for key in sorted(self.__dict__, key=_sort_helper) if _valid(key) + ) + return f"{self.__class__.__name__}({kwarg_str})" + + @classmethod + def __register__(cls): + pass + + def json(self, indent=None, separators=None, **kwargs): + return json.dumps(self, indent=indent, separators=separators, **kwargs) + + def pretty_json(self, indent=2, separators=(',', ': '), **kwargs): + return json.dumps(self, indent=indent, separators=separators, **kwargs) + + def dump(self): + return odict((field.name, field.dump(self, self.__class__, value)) + for field, value in ((field, getattr(self, field.name, NULL)) + for field in self.__dump_fields()) + if value is not NULL and not (value is field.default + and not field.default_in_dump)) + + @classmethod + def __dump_fields(cls): + if "__dump_fields_cache" not in cls.__dict__: + cls.__dump_fields_cache = tuple( + field for field in cls.__fields__.values() if field.in_dump + ) + return cls.__dump_fields_cache + + def __eq__(self, other): + if self.__class__ != other.__class__: + return False + rando_default = 19274656290 # need an arbitrary but definite value if field does not exist + return all(getattr(self, field, rando_default) == getattr(other, field, rando_default) + for field in self.__fields__) + + def __hash__(self): + return sum(hash(getattr(self, field, None)) for field in self.__fields__) + + @property + def _initd(self): + return getattr(self, f"_{self.__class__.__name__}__initd", None) + + +class ImmutableEntity(Entity): + + def __setattr__(self, attribute, value): + if self._initd: + raise AttributeError( + f"Assignment not allowed. {self.__class__.__name__} is immutable." + ) + super().__setattr__(attribute, value) + + def __delattr__(self, item): + if self._initd: + raise AttributeError(f"Deletion not allowed. {self.__class__.__name__} is immutable.") + super().__delattr__(item) + + +class DictSafeMixin: + + def __getitem__(self, item): + return getattr(self, item) + + def __setitem__(self, key, value): + setattr(self, key, value) + + def __delitem__(self, key): + delattr(self, key) + + def get(self, item, default=None): + return getattr(self, item, default) + + def __contains__(self, item): + value = getattr(self, item, None) + if value is None: + return False + field = self.__fields__[item] + if isinstance(field, (MapField, ListField)): + return len(value) > 0 + return True + + def __iter__(self): + for key in self.__fields__: + if key in self: + yield key + + def items(self): + for key in self.__fields__: + if key in self: + yield key, getattr(self, key) + + def copy(self): + return self.__class__(**self.dump()) + + def setdefault(self, key, default_value): + if key not in self: + setattr(self, key, default_value) + + def update(self, E=None, **F): + # D.update([E, ]**F) -> None. Update D from dict/iterable E and F. + # If E present and has a .keys() method, does: for k in E: D[k] = E[k] + # If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v + # In either case, this is followed by: for k in F: D[k] = F[k] + if E is not None: + try: + for k, v in E.items(): + self[k] = v + except AttributeError: + for k, v in E: + self[k] = v + for k in F: + self[k] = F[k] + + +deprecated.constant( + "26.3", + "26.9", + "EntityEncoder", + json.CondaJSONEncoder, + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", +) diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/exceptions.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..71822c8e3c9aac17b3bd81eccb2651b2988187bb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/exceptions.py @@ -0,0 +1,32 @@ +from logging import getLogger +from ..deprecations import deprecated + +log = getLogger(__name__) + + +def Raise(exception): # NOQA + raise exception + + +class AuxlibError: + """Mixin to identify exceptions associated with the auxlib package.""" + + +class ValidationError(AuxlibError, TypeError): + + def __init__(self, key, value=None, valid_types=None, msg=None): + self.__cause__ = None # in python3 don't chain ValidationError exceptions + if msg is not None: + super().__init__(msg) + elif value is None: + super().__init__(f"Value for {key} cannot be None.") + elif valid_types is None: + super().__init__(f"Invalid value {value} for {key}") + else: + super().__init__( + f"{key} must be of type {valid_types}, not {value!r}" + ) + + +class ThisShouldNeverHappenError(AuxlibError, AttributeError): + pass diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/ish.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/ish.py new file mode 100644 index 0000000000000000000000000000000000000000..1c2ed900cb40e32618f42d48e5e34802fa08e3db --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/ish.py @@ -0,0 +1,65 @@ +from logging import getLogger +from textwrap import dedent + +log = getLogger(__name__) + + +def dals(string): + """dedent and left-strip""" + return dedent(string).lstrip() + + +def _get_attr(obj, attr_name, aliases=()): + try: + return getattr(obj, attr_name) + except AttributeError: + for alias in aliases: + try: + return getattr(obj, alias) + except AttributeError: + continue + else: + raise + + +def find_or_none(key, search_maps, aliases=(), _map_index=0): + """Return the value of the first key found in the list of search_maps, + otherwise return None. + + Examples: + >>> from .collection import AttrDict + >>> d1 = AttrDict({'a': 1, 'b': 2, 'c': 3, 'e': None}) + >>> d2 = AttrDict({'b': 5, 'e': 6, 'f': 7}) + >>> find_or_none('c', (d1, d2)) + 3 + >>> find_or_none('f', (d1, d2)) + 7 + >>> find_or_none('b', (d1, d2)) + 2 + >>> print(find_or_none('g', (d1, d2))) + None + >>> find_or_none('e', (d1, d2)) + 6 + + """ + try: + attr = _get_attr(search_maps[_map_index], key, aliases) + return attr if attr is not None else find_or_none(key, search_maps[1:], aliases) + except AttributeError: + # not found in current map object, so go to next + return find_or_none(key, search_maps, aliases, _map_index+1) + except IndexError: + # ran out of map objects to search + return None + + +def find_or_raise(key, search_maps, aliases=(), _map_index=0): + try: + attr = _get_attr(search_maps[_map_index], key, aliases) + return attr if attr is not None else find_or_raise(key, search_maps[1:], aliases) + except AttributeError: + # not found in current map object, so go to next + return find_or_raise(key, search_maps, aliases, _map_index+1) + except IndexError: + # ran out of map objects to search + raise AttributeError() diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/logz.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/logz.py new file mode 100644 index 0000000000000000000000000000000000000000..669d5da05f42480e3450822b5164258baad53a37 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/logz.py @@ -0,0 +1,187 @@ +from itertools import islice +from logging import getLogger, INFO, Formatter, StreamHandler, DEBUG +from sys import stderr + +from . import NullHandler +from ..common.serialize import json +from ..deprecations import deprecated + +log = getLogger(__name__) +root_log = getLogger() + +NullHandler = NullHandler + +DEBUG_FORMATTER = Formatter( + "[%(levelname)s] [%(asctime)s.%(msecs)03d] %(process)d %(name)s:%(funcName)s(%(lineno)d):\n" + "%(message)s\n", + "%Y-%m-%d %H:%M:%S") + +INFO_FORMATTER = Formatter( + "[%(levelname)s] [%(asctime)s.%(msecs)03d] %(process)d %(name)s(%(lineno)d): %(message)s\n", + "%Y-%m-%d %H:%M:%S") + + +def set_root_level(level=INFO): + root_log.setLevel(level) + + +def attach_stderr(level=INFO): + has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers) + if not has_stderr_handler: + handler = StreamHandler(stderr) + handler.name = 'stderr' + if level is not None: + handler.setLevel(level) + handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER) + root_log.addHandler(handler) + return True + else: + return False + + +def detach_stderr(): + for handler in root_log.handlers: + if handler.name == 'stderr': + root_log.removeHandler(handler) + return True + return False + + +def initialize_logging(level=INFO): + attach_stderr(level) + + +deprecated.constant( + "26.3", + "26.9", + "DumpEncoder", + json.CondaJSONEncoder, + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", +) +_DUMPS = json.CondaJSONEncoder(indent=2, ensure_ascii=False, sort_keys=True).encode +deprecated.constant( + "26.3", + "26.9", + "_DUMPS", + _DUMPS, + addendum="Use `conda.common.serialize.json.CondaJSONEncoder(sort_keys=True).encode` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "jsondumps", + _DUMPS, + addendum="Use `conda.common.serialize.json.CondaJSONEncoder(sort_keys=True).encode` instead.", +) +del _DUMPS + + + +def fullname(obj): + try: + return obj.__module__ + "." + obj.__class__.__name__ + except AttributeError: + return obj.__class__.__name__ + + +request_header_sort_dict = { + 'Host': '\x00\x00', + 'User-Agent': '\x00\x01', +} +def request_header_sort_key(item): + return request_header_sort_dict.get(item[0], item[0].lower()) + + +response_header_sort_dict = { + 'Content-Length': '\x7e\x7e\x61', + 'Connection': '\x7e\x7e\x62', +} +def response_header_sort_key(item): + return response_header_sort_dict.get(item[0], item[0].lower()) + + +def stringify(obj, content_max_len=0): + def bottle_builder(builder, bottle_object): + builder.append( + "{} {}{} {}".format( + bottle_object.method, + bottle_object.path, + bottle_object.environ.get("QUERY_STRING", ""), + bottle_object.get("SERVER_PROTOCOL"), + ) + ) + builder += [f"{key}: {value}" for key, value in bottle_object.headers.items()] + builder.append('') + body = bottle_object.body.read().strip() + if body: + builder.append(body) + + def requests_models_PreparedRequest_builder(builder, request_object): + builder.append( + ">>{} {} {}".format( + request_object.method, + request_object.path_url, + request_object.url.split(":", 1)[0].upper(), + ) + ) + builder.extend( + f"> {key}: {value}" + for key, value in sorted(request_object.headers.items(), key=request_header_sort_key) + ) + builder.append("") + if request_object.body: + builder.append(request_object.body) + + def requests_models_Response_builder(builder, response_object): + builder.append( + "<<{} {} {}".format( + response_object.url.split(":", 1)[0].upper(), + response_object.status_code, + response_object.reason, + ) + ) + builder.extend( + f"< {key}: {value}" + for key, value in sorted(response_object.headers.items(), key=response_header_sort_key) + ) + elapsed = str(response_object.elapsed).split(":", 1)[-1] + builder.append(f"< Elapsed: {elapsed}") + if content_max_len: + builder.append('') + content_type = response_object.headers.get('Content-Type') + if content_type == 'application/json': + text = response_object.text + if len(text) > content_max_len: + content = text + else: + resp = json.loads(text) + resp = dict(islice(resp.items(), content_max_len)) + content = json.dumps(resp) + content = content[:content_max_len] if len(content) > content_max_len else content + builder.append(content) + builder.append('') + elif content_type is not None and (content_type.startswith('text/') + or content_type == 'application/xml'): + text = response_object.text + content = text[:content_max_len] if len(text) > content_max_len else text + builder.append(content) + + try: + name = fullname(obj) + builder = [''] # start with new line + if name.startswith('bottle.'): + bottle_builder(builder, obj) + elif name.endswith('requests.models.PreparedRequest'): + requests_models_PreparedRequest_builder(builder, obj) + elif name.endswith('requests.models.Response'): + if getattr(obj, 'request'): + requests_models_PreparedRequest_builder(builder, obj.request) + else: + log.info("request is 'None' for Response object with url %s", obj.url) + requests_models_Response_builder(builder, obj) + else: + return None + builder.append('') # end with new line + return "\n".join(builder) + except Exception as e: + log.exception(e) diff --git a/miniconda3/lib/python3.13/site-packages/conda/auxlib/type_coercion.py b/miniconda3/lib/python3.13/site-packages/conda/auxlib/type_coercion.py new file mode 100644 index 0000000000000000000000000000000000000000..5a9958890f5f28b753ea74dc28f1dae41bafe435 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/auxlib/type_coercion.py @@ -0,0 +1,272 @@ +"""Collection of functions to coerce conversion of types with an intelligent guess.""" + +from __future__ import annotations + +from collections.abc import Mapping +from enum import Enum +from itertools import chain +from re import IGNORECASE, compile +from typing import TYPE_CHECKING + +from ..deprecations import deprecated +from ..common.compat import isiterable +from .decorators import memoizedproperty +from .exceptions import AuxlibError + +if TYPE_CHECKING: + from typing import Callable, TypeVar + + T = TypeVar("T") + +__all__ = ["boolify", "typify", "maybecall", "numberify"] + +BOOLISH_TRUE = ("true", "yes", "on", "y") +BOOLISH_FALSE = ("false", "off", "n", "no", "non", "none", "") +NULL_STRINGS = ("none", "~", "null", "\0") +BOOL_COERCEABLE_TYPES = (int, bool, float, complex, list, set, dict, tuple) +NUMBER_TYPES = (int, float, complex) +NUMBER_TYPES_SET = {*NUMBER_TYPES} +STRING_TYPES_SET = {str} + +NO_MATCH = object() + + +class TypeCoercionError(AuxlibError, ValueError): + + def __init__(self, value, msg, *args, **kwargs): + self.value = value + super().__init__(msg, *args, **kwargs) + + +class _Regex: + + @memoizedproperty + def BOOLEAN_TRUE(self): + return compile(r'^true$|^yes$|^on$', IGNORECASE), True + + @memoizedproperty + def BOOLEAN_FALSE(self): + return compile(r'^false$|^no$|^off$', IGNORECASE), False + + @memoizedproperty + def NONE(self): + return compile(r'^none$|^null$', IGNORECASE), None + + @memoizedproperty + def INT(self): + return compile(r'^[-+]?\d+$'), int + + @memoizedproperty + def BIN(self): + return compile(r'^[-+]?0[bB][01]+$'), bin + + @memoizedproperty + def OCT(self): + return compile(r'^[-+]?0[oO][0-7]+$'), oct + + @memoizedproperty + def HEX(self): + return compile(r'^[-+]?0[xX][0-9a-fA-F]+$'), hex + + @memoizedproperty + def FLOAT(self): + return compile(r'^[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?$'), float + + @memoizedproperty + def COMPLEX(self): + return (compile(r'^(?:[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)?' # maybe first float + r'[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?j$'), # second float with j + complex) + + @property + def numbers(self): + yield self.INT + yield self.FLOAT + yield self.BIN + yield self.OCT + yield self.HEX + yield self.COMPLEX + + @property + def boolean(self): + yield self.BOOLEAN_TRUE + yield self.BOOLEAN_FALSE + + @property + def none(self): + yield self.NONE + + def convert_number(self, value_string): + return self._convert(value_string, (self.numbers, )) + + def convert(self, value_string): + return self._convert(value_string, (self.boolean, self.none, self.numbers, )) + + def _convert(self, value_string, type_list): + return next((typish(value_string) if callable(typish) else typish + for regex, typish in chain.from_iterable(type_list) + if regex.match(value_string)), + NO_MATCH) + + +_REGEX = _Regex() + + +def numberify(value): + """ + + Examples: + >>> [numberify(x) for x in ('1234', 1234, '0755', 0o0755, False, 0, '0', True, 1, '1')] + [1234, 1234, 755, 493, 0, 0, 0, 1, 1, 1] + >>> [numberify(x) for x in ('12.34', 12.34, 1.2+3.5j, '1.2+3.5j')] + [12.34, 12.34, (1.2+3.5j), (1.2+3.5j)] + + """ + if isinstance(value, bool): + return int(value) + if isinstance(value, NUMBER_TYPES): + return value + candidate = _REGEX.convert_number(value) + if candidate is not NO_MATCH: + return candidate + raise TypeCoercionError(value, f"Cannot convert {value} to a number.") + + +def boolify(value, nullable=False, return_string=False): + """Convert a number, string, or sequence type into a pure boolean. + + Args: + value (number, string, sequence): pretty much anything + + Returns: + bool: boolean representation of the given value + + Examples: + >>> [boolify(x) for x in ('yes', 'no')] + [True, False] + >>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')] + [True, False, True, False, False, True, True] + >>> [boolify(x) for x in ("true", "yes", "on", "y")] + [True, True, True, True] + >>> [boolify(x) for x in ("no", "non", "none", "off", "")] + [False, False, False, False, False] + >>> [boolify(x) for x in ([], set(), dict(), tuple())] + [False, False, False, False] + >>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))] + [True, True, True, True] + + """ + # cast number types naturally + if isinstance(value, BOOL_COERCEABLE_TYPES): + return bool(value) + # try to coerce string into number + val = str(value).strip().lower().replace(".", "", 1) + if val.isnumeric(): + return bool(float(val)) + elif val in BOOLISH_TRUE: + return True + elif nullable and val in NULL_STRINGS: + return None + elif val in BOOLISH_FALSE: + return False + else: # must be False + try: + return bool(complex(val)) + except ValueError: + if isinstance(value, str) and return_string: + return value + raise TypeCoercionError(value, "The value %r cannot be boolified." % value) + + +def typify_str_no_hint(value): + candidate = _REGEX.convert(value) + return candidate if candidate is not NO_MATCH else value + + +def typify(value, type_hint=None): + """Take a primitive value, usually a string, and try to make a more relevant type out of it. + An optional type_hint will try to coerce the value to that type. + + Args: + value (Any): Usually a string, not a sequence + type_hint (type or tuple[type]): + + Examples: + >>> typify('32') + 32 + >>> typify('32', float) + 32.0 + >>> typify('32.0') + 32.0 + >>> typify('32.0.0') + '32.0.0' + >>> [typify(x) for x in ('true', 'yes', 'on')] + [True, True, True] + >>> [typify(x) for x in ('no', 'FALSe', 'off')] + [False, False, False] + >>> [typify(x) for x in ('none', 'None', None)] + [None, None, None] + + """ + # value must be a string, or there at least needs to be a type hint + if isinstance(value, str): + value = value.strip() + elif type_hint is None: + # can't do anything because value isn't a string and there's no type hint + return value + + # now we either have a stripped string, a type hint, or both + # use the hint if it exists + if isiterable(type_hint): + if isinstance(type_hint, type) and issubclass(type_hint, Enum): + try: + return type_hint(value) + except ValueError as e: + try: + return type_hint[value] + except KeyError: + raise TypeCoercionError(value, str(e)) + type_hint = set(type_hint) + if not (type_hint - NUMBER_TYPES_SET): + return numberify(value) + elif not (type_hint - STRING_TYPES_SET): + return str(value) + elif not (type_hint - {bool, type(None)}): + return boolify(value, nullable=True) + elif not (type_hint - (STRING_TYPES_SET | {bool})): + return boolify(value, return_string=True) + elif not (type_hint - (STRING_TYPES_SET | {type(None)})): + value = str(value) + return None if value.lower() == 'none' else value + elif not (type_hint - {bool, int}): + return typify_str_no_hint(str(value)) + else: + raise NotImplementedError() + elif type_hint is not None: + # coerce using the type hint, or use boolify for bool + try: + return boolify(value) if type_hint == bool else type_hint(value) + except ValueError as e: + # ValueError: invalid literal for int() with base 10: 'nope' + raise TypeCoercionError(value, str(e)) + else: + # no type hint, but we know value is a string, so try to match with the regex patterns + # if there's still no match, `typify_str_no_hint` will return `value` + return typify_str_no_hint(value) + + +def typify_data_structure(value, type_hint=None): + if isinstance(value, Mapping): + return type(value)((k, typify(v, type_hint)) for k, v in value.items()) + elif isiterable(value): + return type(value)(typify(v, type_hint) for v in value) + elif isinstance(value, str) and isinstance(type_hint, type) and issubclass(type_hint, str): + # This block is necessary because if we fall through to typify(), we end up calling + # .strip() on the str, when sometimes we want to preserve preceding and trailing + # whitespace. + return type_hint(value) + else: + return typify(value, type_hint) + +def maybecall(value: Callable[[], T] | T) -> T: + return value() if callable(value) else value diff --git a/miniconda3/lib/python3.13/site-packages/conda/base/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff1b814060d62a0c1fb293b8f3dcd664f9320c5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/base/__init__.py @@ -0,0 +1,18 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Code in ``conda.base`` is the lowest level of the application stack. It is loaded and executed +virtually every time the application is executed. Any code within, and any of its imports, must +be highly performant. + +Conda modules importable from ``conda.base`` are + +- ``conda.base`` +- ``conda.common`` + +Modules prohibited from importing ``conda.base`` are: + +- ``conda.common`` + +All other ``conda`` modules may import from ``conda.base``. +""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/base/constants.py b/miniconda3/lib/python3.13/site-packages/conda/base/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..7ca908d37e917a3377e7a3c015800a00f352dc17 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/base/constants.py @@ -0,0 +1,432 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This file should hold most string literals and magic numbers used throughout the code base. +The exception is if a literal is specifically meant to be private to and isolated within a module. +Think of this as a "more static" source of configuration information. + +Another important source of "static" configuration is conda/models/enums.py. +""" + +from __future__ import annotations + +import struct +from enum import Enum, EnumMeta +from os.path import join +from typing import TYPE_CHECKING + +from ..common.compat import on_win +from ..deprecations import deprecated + +if TYPE_CHECKING: + from typing import Final + + from ..common.path import PathType + +PREFIX_PLACEHOLDER: Final = ( + "/opt/anaconda1anaconda2" + # this is intentionally split into parts, such that running + # this program on itself will leave it unchanged + "anaconda3" +) + +machine_bits: Final = 8 * struct.calcsize("P") + +APP_NAME: Final = "conda" + +SEARCH_PATH: tuple[str, ...] + +if on_win: # pragma: no cover + SEARCH_PATH = ( + "C:/ProgramData/conda/.condarc", + "C:/ProgramData/conda/condarc", + "C:/ProgramData/conda/condarc.d", + ) +else: + SEARCH_PATH = ( + "/etc/conda/.condarc", + "/etc/conda/condarc", + "/etc/conda/condarc.d/", + "/var/lib/conda/.condarc", + "/var/lib/conda/condarc", + "/var/lib/conda/condarc.d/", + ) + +SEARCH_PATH += ( + "$CONDA_ROOT/.condarc", + "$CONDA_ROOT/condarc", + "$CONDA_ROOT/condarc.d/", + "$XDG_CONFIG_HOME/conda/.condarc", + "$XDG_CONFIG_HOME/conda/condarc", + "$XDG_CONFIG_HOME/conda/condarc.d/", + "~/.config/conda/.condarc", + "~/.config/conda/condarc", + "~/.config/conda/condarc.d/", + "~/.conda/.condarc", + "~/.conda/condarc", + "~/.conda/condarc.d/", + "~/.condarc", + "$CONDA_PREFIX/.condarc", + "$CONDA_PREFIX/condarc", + "$CONDA_PREFIX/condarc.d/", + "$CONDARC", +) + +DEFAULT_CHANNEL_ALIAS: Final = "https://conda.anaconda.org" +CONDA_HOMEPAGE_URL: Final = "https://conda.io" + +deprecated.constant( + "26.9", + "27.3", + "ERROR_UPLOAD_URL", + "https://conda.io/conda-post/unexpected-error", +) + +DEFAULTS_CHANNEL_NAME: Final = "defaults" + +PLATFORMS: Final = ( + "emscripten-wasm32", + "wasi-wasm32", + "freebsd-64", + "linux-32", + "linux-64", + "linux-aarch64", + "linux-armv6l", + "linux-armv7l", + "linux-ppc64", + "linux-ppc64le", + "linux-riscv64", + "linux-s390x", + "osx-64", + "osx-arm64", + "win-32", + "win-64", + "win-arm64", + "zos-z", +) +KNOWN_SUBDIRS: Final = ("noarch", *PLATFORMS) +PLATFORM_DIRECTORIES = KNOWN_SUBDIRS + +RECOGNIZED_URL_SCHEMES: Final = ("http", "https", "ftp", "s3", "file") + + +DEFAULT_CHANNELS_UNIX: Final = ( + "https://repo.anaconda.com/pkgs/main", + "https://repo.anaconda.com/pkgs/r", +) + +DEFAULT_CHANNELS_WIN: Final = ( + "https://repo.anaconda.com/pkgs/main", + "https://repo.anaconda.com/pkgs/r", + "https://repo.anaconda.com/pkgs/msys2", +) + +DEFAULT_CUSTOM_CHANNELS: Final = { + "pkgs/pro": "https://repo.anaconda.com", +} + +DEFAULT_CHANNELS: Final = DEFAULT_CHANNELS_WIN if on_win else DEFAULT_CHANNELS_UNIX + +ROOT_ENV_NAME: Final = "base" +RESERVED_ENV_NAMES: Final = ( + ROOT_ENV_NAME, + "root", +) +UNUSED_ENV_NAME: Final = "unused-env-name" + +ROOT_NO_RM: Final = ( + "python", + "pycosat", + "ruamel.yaml", + "conda", + "openssl", + "requests", +) + +DEFAULT_AGGRESSIVE_UPDATE_PACKAGES: Final = ( + "ca-certificates", + "certifi", + "openssl", +) + +COMPATIBLE_SHELLS: tuple[str, ...] + +if on_win: # pragma: no cover + COMPATIBLE_SHELLS = ( + "bash", + "cmd.exe", + "fish", + "tcsh", + "xonsh", + "zsh", + "powershell", + ) +else: + COMPATIBLE_SHELLS = ( + "bash", + "fish", + "tcsh", + "xonsh", + "zsh", + "powershell", + ) + + +# Maximum priority, reserved for packages we really want to remove +MAX_CHANNEL_PRIORITY: Final = 10000 + +CONDA_PACKAGE_EXTENSION_V1: Final = ".tar.bz2" +CONDA_PACKAGE_EXTENSION_V2: Final = ".conda" + +PARTIAL_EXTENSION: Final = ".partial" +"""Suffix appended to package filenames during incomplete downloads.""" + +deprecated.constant( + "26.9", + "27.3", + "CONDA_PACKAGE_EXTENSIONS", + (CONDA_PACKAGE_EXTENSION_V2, CONDA_PACKAGE_EXTENSION_V1), + addendum="Use `conda.base.context.context.plugin_manager.get_package_extractors()` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "CONDA_PACKAGE_PARTS", + (f"{CONDA_PACKAGE_EXTENSION_V2}.part", f"{CONDA_PACKAGE_EXTENSION_V1}.part"), + addendum=( + "The `.part` suffix has not been used since 2014; use " + "`conda.base.constants.PARTIAL_EXTENSION` (`.partial`) with " + "`str.removesuffix()` instead." + ), +) + +# legacy support for conda-build +CONDA_TARBALL_EXTENSION: Final = CONDA_PACKAGE_EXTENSION_V1 +CONDA_TEMP_EXTENSION: Final = ".c~" +CONDA_TEMP_EXTENSIONS: Final = (CONDA_TEMP_EXTENSION, ".trash") +CONDA_LOGS_DIR: Final = ".logs" + +UNKNOWN_CHANNEL: Final = "" +REPODATA_FN: Final = "repodata.json" + +NOTICES_FN: Final = "notices.json" +"""Default name of the notices file on the server we look for.""" + +NOTICES_CACHE_FN: Final = "notices.cache" +"""Name of cache file where read notice IDs are stored.""" + +NOTICES_CACHE_SUBDIR: Final = "notices" +"""Determines the subdir for notices cache.""" + +NOTICES_DECORATOR_DISPLAY_INTERVAL: Final = 86400 # in seconds +"""Determines how often notices are displayed while running commands.""" + +DRY_RUN_PREFIX: Final = "Dry run action:" +PREFIX_NAME_DISALLOWED_CHARS: Final = {"/", " ", ":", "#"} + + +class SafetyChecks(Enum): + disabled = "disabled" + warn = "warn" + enabled = "enabled" + + def __str__(self) -> str: + return self.value + + +class PathConflict(Enum): + clobber = "clobber" + warn = "warn" + prevent = "prevent" + + def __str__(self) -> str: + return self.value + + +class DepsModifier(Enum): + """Flags to enable alternate handling of dependencies.""" + + NOT_SET = "not_set" # default + NO_DEPS = "no_deps" + ONLY_DEPS = "only_deps" + + def __str__(self) -> str: + return self.value + + +class UpdateModifier(Enum): + SPECS_SATISFIED_SKIP_SOLVE = "specs_satisfied_skip_solve" + FREEZE_INSTALLED = ( + "freeze_installed" # freeze is a better name for --no-update-deps + ) + UPDATE_DEPS = "update_deps" + UPDATE_SPECS = "update_specs" # default + UPDATE_ALL = "update_all" + # TODO: add REINSTALL_ALL, see https://github.com/conda/conda/issues/6247 and https://github.com/conda/conda/issues/3149 + + def __str__(self) -> str: + return self.value + + +class ChannelPriorityMeta(EnumMeta): + def __call__(cls, value, *args, **kwargs): + try: + return super().__call__(value, *args, **kwargs) + except ValueError: + if isinstance(value, str): + from ..auxlib.type_coercion import typify + + value = typify(value) + if value is True: + value = "flexible" + elif value is False: + value = cls.DISABLED + return super().__call__(value, *args, **kwargs) + + +class ValueEnum(Enum): + """Subclass of enum that returns the value of the enum as its str representation""" + + def __str__(self) -> str: + return f"{self.value}" + + +class ChannelPriority(ValueEnum, metaclass=ChannelPriorityMeta): + __name__ = "ChannelPriority" + + STRICT = "strict" + # STRICT_OR_FLEXIBLE = 'strict_or_flexible' # TODO: consider implementing if needed + FLEXIBLE = "flexible" + DISABLED = "disabled" + + +class SatSolverChoice(ValueEnum): + PYCOSAT = "pycosat" + PYCRYPTOSAT = "pycryptosat" + PYSAT = "pysat" + + +DEFAULT_SOLVER: Final = "libmamba" +"""The name of the default solver, currently "libmamba".""" + +CLASSIC_SOLVER: Final = "classic" + +DEFAULT_JSON_REPORTER_BACKEND: Final = "json" +"""The name of the default json reporter backend.""" + +DEFAULT_CONSOLE_REPORTER_BACKEND: Final = "classic" +"""The name of the default console reporter backend.""" + +DEFAULT_CONDA_LIST_FIELDS: Final = ("name", "version", "build", "channel_name") +"""The default ``conda list`` columns.""" +CONDA_LIST_FIELDS: Final = { + # Keys MUST be valid attributes in conda.core.records.PrefixRecords + # Values are the displayed column title + "arch": "Arch", + "build": "Build", + "build_number": "Build number", + "channel": "Channel URL", + "channel_name": "Channel", + "constrains": "Constraints", + "depends": "Dependencies", + "dist_str": "Dist", + "features": "Features", + "fn": "Filename", + "license": "License", + "license_family": "License family", + "md5": "MD5", + "name": "Name", + "noarch": "Noarch", + "package_type": "Package type", + "requested_spec": "Requested", + "sha256": "SHA256", + "size": "Size", + "subdir": "Subdir", + "timestamp": "Timestamp", + "track_features": "Track features", + "url": "URL", + "version": "Version", +} + + +class NoticeLevel(ValueEnum): + CRITICAL = "critical" + WARNING = "warning" + INFO = "info" + + +# Magic files for permissions determination +PACKAGE_CACHE_MAGIC_FILE: Final[PathType] = "urls.txt" +PREFIX_MAGIC_FILE: Final[PathType] = join("conda-meta", "history") +PREFIX_FROZEN_FILE: Final[PathType] = join("conda-meta", "frozen") +PREFIX_CREATION_TIMESTAMP_FILE: Final[PathType] = join("conda-meta", "created_at") + +PREFIX_STATE_FILE: Final[PathType] = join("conda-meta", "state") +PREFIX_PINNED_FILE: Final[PathType] = join("conda-meta", "pinned") +PACKAGE_ENV_VARS_DIR: Final[PathType] = join("etc", "conda", "env_vars.d") +CONDA_ENV_VARS_UNSET_VAR: Final = "***unset***" +RESERVED_ENV_VARS: Final = ("PATH",) + +# TODO: should be frozendict(), but I don't want to import frozendict from auxlib here. +NAMESPACES_MAP: Final = { # base package name, namespace + "python": "python", + "r": "r", + "r-base": "r", + "mro-base": "r", + "erlang": "erlang", + "java": "java", + "openjdk": "java", + "julia": "julia", + "latex": "latex", + "lua": "lua", + "nodejs": "js", + "perl": "perl", + "php": "php", + "ruby": "ruby", + "m2-base": "m2", + "msys2-conda-epoch": "m2w64", +} + +NAMESPACE_PACKAGE_NAMES: Final = frozenset(NAMESPACES_MAP) +NAMESPACES: Final = frozenset(NAMESPACES_MAP.values()) + +# Namespace arbiters of uniqueness +# global: some repository established by Anaconda, Inc. and conda-forge +# python: https://pypi.org/simple +# r: https://cran.r-project.org/web/packages/available_packages_by_name.html +# erlang: https://hex.pm/packages +# java: https://repo1.maven.org/maven2/ +# julia: https://pkg.julialang.org/ +# latex: https://ctan.org/pkg +# lua: https://luarocks.org/m/root +# js: https://docs.npmjs.com/misc/registry +# pascal: ??? +# perl: https://www.cpan.org/modules/01modules.index.html +# php: https://packagist.org/ +# ruby: https://rubygems.org/gems +# clojure: https://clojars.org/ + + +# Not all python namespace packages are registered on PyPI. If a package +# contains files in site-packages, it probably belongs in the python namespace. + + +# Indicates whether or not external plugins (i.e., plugins that aren't shipped +# with conda) are enabled +NO_PLUGINS: Final = False + +# When this string is present in an environment file, it indicates that the file +# describes an explicit environment spec. +EXPLICIT_MARKER: Final = "@EXPLICIT" + +# Status marks for health check output +OK_MARK: Final = "✅" +X_MARK: Final = "❌" + +# These variables describe the various sources for config that are supported by conda. +# In addition to these sources, conda also supports configuration from condarc config +# files (these are referred to in the context object by their full path as a pathlib.Path). +CMD_LINE_SOURCE: Final = "cmd_line" +ENV_VARS_SOURCE: Final = "envvars" +CONFIGURATION_SOURCES: Final = (CMD_LINE_SOURCE, ENV_VARS_SOURCE) diff --git a/miniconda3/lib/python3.13/site-packages/conda/base/context.py b/miniconda3/lib/python3.13/site-packages/conda/base/context.py new file mode 100644 index 0000000000000000000000000000000000000000..df6b0b97e6cc77846411d7a6065ff05cc9693179 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/base/context.py @@ -0,0 +1,2417 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda's global configuration object. + +The context aggregates all configuration files, environment variables, and command line arguments +into one global stateful object to be used across all of conda. +""" + +from __future__ import annotations + +import logging +import os +import platform +import struct +import sys +import warnings +from contextlib import contextmanager, suppress +from errno import ENOENT +from functools import cache, cached_property +from itertools import chain +from os.path import abspath, exists, expanduser, isdir, isfile, join +from os.path import split as path_split +from pathlib import Path +from typing import TYPE_CHECKING + +from frozendict import frozendict + +from .. import CONDA_SOURCE_ROOT +from .. import __version__ as CONDA_VERSION +from ..auxlib.decorators import memoizedproperty +from ..auxlib.ish import dals +from ..common._os.linux import linux_get_libc_version +from ..common._os.osx import mac_ver +from ..common.compat import NoneType, on_win +from ..common.configuration import ( + DEFAULT_CONDARC_FILENAME, + Configuration, + ConfigurationLoadError, + MapParameter, + ParameterLoader, + PrimitiveParameter, + SequenceParameter, + ValidationError, + YamlRawParameter, +) +from ..common.constants import TRACE +from ..common.iterators import groupby_to_dict, unique +from ..common.path import BIN_DIRECTORY, expand, paths_equal +from ..common.url import has_scheme, path_to_url, split_scheme_auth_token +from ..deprecations import deprecated +from .constants import ( + APP_NAME, + CMD_LINE_SOURCE, + CONDA_LIST_FIELDS, + DEFAULT_AGGRESSIVE_UPDATE_PACKAGES, + DEFAULT_CHANNEL_ALIAS, + DEFAULT_CHANNELS, + DEFAULT_CHANNELS_UNIX, + DEFAULT_CHANNELS_WIN, + DEFAULT_CONDA_LIST_FIELDS, + DEFAULT_CONSOLE_REPORTER_BACKEND, + DEFAULT_CUSTOM_CHANNELS, + DEFAULT_JSON_REPORTER_BACKEND, + DEFAULT_SOLVER, + DEFAULTS_CHANNEL_NAME, + ENV_VARS_SOURCE, + KNOWN_SUBDIRS, + NO_PLUGINS, + PREFIX_MAGIC_FILE, + PREFIX_NAME_DISALLOWED_CHARS, + REPODATA_FN, + RESERVED_ENV_NAMES, + ROOT_ENV_NAME, + SEARCH_PATH, + UNKNOWN_CHANNEL, + ChannelPriority, + DepsModifier, + PathConflict, + SafetyChecks, + SatSolverChoice, + UpdateModifier, +) + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Iterable, Iterator + from typing import Any, Literal + + from ..common.configuration import Parameter, RawParameter + from ..common.path import PathsType, PathType + from ..models.channel import Channel + from ..models.match_spec import MatchSpec + from ..plugins.config import PluginConfig + from ..plugins.manager import CondaPluginManager + +try: + os.getcwd() +except OSError as e: + if e.errno == ENOENT: + # FileNotFoundError can occur when cwd has been deleted out from underneath the process. + # To resolve #6584, let's go with setting cwd to sys.prefix, and see how far we get. + os.chdir(sys.prefix) + else: + raise + +log = logging.getLogger(__name__) + +_platform_map = { + "freebsd13": "freebsd", + "linux2": "linux", + "linux": "linux", + "darwin": "osx", + "win32": "win", + "zos": "zos", +} +non_x86_machines = { + "armv6l", + "armv7l", + "aarch64", + "arm64", + "ppc64", + "ppc64le", + "riscv64", + "s390x", +} +_arch_names = { + 32: "x86", + 64: "x86_64", +} + +user_rc_path: PathType = abspath(expanduser(f"~/{DEFAULT_CONDARC_FILENAME}")) +sys_rc_path: PathType = join(sys.prefix, DEFAULT_CONDARC_FILENAME) + + +def user_data_dir( # noqa: F811 + appname: str | None = None, + appauthor: str | None | Literal[False] = None, + version: str | None = None, + roaming: bool = False, +) -> PathType: + # Defer platformdirs import to reduce import time for conda activate. + global user_data_dir + from platformdirs import user_data_dir + + return user_data_dir(appname, appauthor=appauthor, version=version, roaming=roaming) + + +def mockable_context_envs_dirs( + root_writable: bool, root_prefix: PathType, _envs_dirs: PathsType +) -> tuple[PathType, ...]: + if root_writable: + fixed_dirs = [ + join(root_prefix, "envs"), + join("~", ".conda", "envs"), + ] + else: + fixed_dirs = [ + join("~", ".conda", "envs"), + join(root_prefix, "envs"), + ] + if on_win: + fixed_dirs.append(join(user_data_dir(APP_NAME, APP_NAME), "envs")) + return tuple(dict.fromkeys(expand(path) for path in (*_envs_dirs, *fixed_dirs))) + + +def channel_alias_validation(value: str) -> str | Literal[True]: + if value and not has_scheme(value): + return f"channel_alias value '{value}' must have scheme/protocol." + return True + + +def default_python_default() -> str: + ver = sys.version_info + return "%d.%d" % (ver.major, ver.minor) + + +def default_python_validation(value: str) -> str | Literal[True]: + if value: + if len(value) >= 3 and value[1] == ".": + try: + value = float(value) + if 2.0 <= value < 4.0: + return True + except ValueError: # pragma: no cover + pass + else: + # Set to None or '' meaning no python pinning + return True + + return f"default_python value '{value}' not of the form '[23].[0-9][0-9]?' or ''" + + +def list_fields_validation(value: Iterable[str]) -> str | Literal[True]: + if invalid := set(value).difference(CONDA_LIST_FIELDS): + return ( + f"Invalid value(s): {sorted(invalid)}. " + f"Valid values are: {sorted(CONDA_LIST_FIELDS)}" + ) + return True + + +def ssl_verify_validation(value: str) -> str | Literal[True]: + if isinstance(value, str): + if sys.version_info < (3, 10) and value == "truststore": + return "`ssl_verify: truststore` is only supported on Python 3.10 or later" + elif value != "truststore" and not exists(value): + return ( + f"ssl_verify value '{value}' must be a boolean, a path to a " + "certificate bundle file, a path to a directory containing " + "certificates of trusted CAs, or 'truststore' to use the " + "operating system certificate store." + ) + return True + + +class Context(Configuration): + add_pip_as_python_dependency = ParameterLoader(PrimitiveParameter(True)) + allow_conda_downgrades = ParameterLoader(PrimitiveParameter(False)) + # allow cyclical dependencies, or raise + allow_cycles = ParameterLoader(PrimitiveParameter(True)) + allow_softlinks = ParameterLoader(PrimitiveParameter(False)) + auto_update_conda = ParameterLoader( + PrimitiveParameter(True), aliases=("self_update",) + ) + auto_activate = ParameterLoader( + PrimitiveParameter(True), aliases=("auto_activate_base",) + ) + _default_activation_env = ParameterLoader( + PrimitiveParameter(ROOT_ENV_NAME), aliases=("default_activation_env",) + ) + auto_stack = ParameterLoader(PrimitiveParameter(0)) + notify_outdated_conda = ParameterLoader(PrimitiveParameter(True)) + clobber = ParameterLoader(PrimitiveParameter(False)) + changeps1 = ParameterLoader(PrimitiveParameter(True)) + env_prompt = ParameterLoader(PrimitiveParameter("({default_env}) ")) + + # environment_specifier is an EXPERIMENTAL config parameter + environment_specifier = ParameterLoader( + PrimitiveParameter(None, element_type=(str, NoneType)), aliases=("env_spec",) + ) + + _create_default_packages = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str)), + aliases=("create_default_packages",), + ) + register_envs = ParameterLoader(PrimitiveParameter(True)) + protect_frozen_envs = ParameterLoader(PrimitiveParameter(True)) + default_python = ParameterLoader( + PrimitiveParameter( + default_python_default(), + element_type=(str, NoneType), + validation=default_python_validation, + ) + ) + download_only = ParameterLoader(PrimitiveParameter(False)) + enable_private_envs = ParameterLoader(PrimitiveParameter(False)) + force_32bit = ParameterLoader(PrimitiveParameter(False)) + non_admin_enabled = ParameterLoader(PrimitiveParameter(True)) + prefix_data_interoperability = ParameterLoader( + PrimitiveParameter(False), aliases=("pip_interop_enabled",) + ) + + @property + @deprecated("25.9", "26.3", addendum="Use 'Context.prefix_data_interoperability'.") + def pip_interop_enabled(self): + return self.prefix_data_interoperability + + # multithreading in various places + _default_threads = ParameterLoader( + PrimitiveParameter(0, element_type=int), aliases=("default_threads",) + ) + # download repodata + _repodata_threads = ParameterLoader( + PrimitiveParameter(0, element_type=int), aliases=("repodata_threads",) + ) + # download packages + _fetch_threads = ParameterLoader( + PrimitiveParameter(0, element_type=int), aliases=("fetch_threads",) + ) + _verify_threads = ParameterLoader( + PrimitiveParameter(0, element_type=int), aliases=("verify_threads",) + ) + # this one actually defaults to 1 - that is handled in the property below + _execute_threads = ParameterLoader( + PrimitiveParameter(0, element_type=int), aliases=("execute_threads",) + ) + + # Safety & Security + _aggressive_update_packages = ParameterLoader( + SequenceParameter( + PrimitiveParameter("", element_type=str), DEFAULT_AGGRESSIVE_UPDATE_PACKAGES + ), + aliases=("aggressive_update_packages",), + ) + safety_checks = ParameterLoader(PrimitiveParameter(SafetyChecks.warn)) + extra_safety_checks = ParameterLoader(PrimitiveParameter(False)) + _signing_metadata_url_base = ParameterLoader( + PrimitiveParameter(None, element_type=(str, NoneType)), + aliases=("signing_metadata_url_base",), + ) + path_conflict = ParameterLoader(PrimitiveParameter(PathConflict.clobber)) + + pinned_packages = ParameterLoader( + SequenceParameter( + PrimitiveParameter("", element_type=str), string_delimiter="&" + ) + ) # TODO: consider a different string delimiter + disallowed_packages = ParameterLoader( + SequenceParameter( + PrimitiveParameter("", element_type=str), string_delimiter="&" + ), + aliases=("disallow",), + ) + rollback_enabled = ParameterLoader(PrimitiveParameter(True)) + track_features = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str)) + ) + use_index_cache = ParameterLoader(PrimitiveParameter(False)) + + separate_format_cache = ParameterLoader(PrimitiveParameter(False)) + + _root_prefix = ParameterLoader( + PrimitiveParameter(""), aliases=("root_dir", "root_prefix") + ) + _envs_dirs = ParameterLoader( + SequenceParameter( + PrimitiveParameter("", element_type=str), string_delimiter=os.pathsep + ), + aliases=("envs_dirs", "envs_path"), + expandvars=True, + ) + _pkgs_dirs = ParameterLoader( + SequenceParameter(PrimitiveParameter("", str)), + aliases=("pkgs_dirs",), + expandvars=True, + ) + _subdir = ParameterLoader(PrimitiveParameter(""), aliases=("subdir",)) + _subdirs = ParameterLoader( + SequenceParameter(PrimitiveParameter("", str)), aliases=("subdirs",) + ) + _export_platforms = ParameterLoader( + SequenceParameter(PrimitiveParameter("", str)), + aliases=("export_platforms", "extra_platforms"), + ) + + local_repodata_ttl = ParameterLoader( + PrimitiveParameter(1, element_type=(bool, int)) + ) + # number of seconds to cache repodata locally + # True/1: respect Cache-Control max-age header + # False/0: always fetch remote repodata (HTTP 304 responses respected) + + # remote connection details + ssl_verify = ParameterLoader( + PrimitiveParameter( + True, element_type=(str, bool), validation=ssl_verify_validation + ), + aliases=("verify_ssl",), + expandvars=True, + ) + client_ssl_cert = ParameterLoader( + PrimitiveParameter(None, element_type=(str, NoneType)), + aliases=("client_cert",), + expandvars=True, + ) + client_ssl_cert_key = ParameterLoader( + PrimitiveParameter(None, element_type=(str, NoneType)), + aliases=("client_cert_key",), + expandvars=True, + ) + proxy_servers = ParameterLoader( + MapParameter(PrimitiveParameter(None, (str, NoneType))), expandvars=True + ) + remote_connect_timeout_secs = ParameterLoader(PrimitiveParameter(9.15)) + remote_read_timeout_secs = ParameterLoader(PrimitiveParameter(60.0)) + remote_max_retries = ParameterLoader(PrimitiveParameter(3)) + remote_backoff_factor = ParameterLoader(PrimitiveParameter(1)) + + add_anaconda_token = ParameterLoader( + PrimitiveParameter(True), aliases=("add_binstar_token",) + ) + + #################################################### + # Channel Configuration # + #################################################### + allow_non_channel_urls = ParameterLoader(PrimitiveParameter(False)) + _channel_alias = ParameterLoader( + PrimitiveParameter(DEFAULT_CHANNEL_ALIAS, validation=channel_alias_validation), + aliases=("channel_alias",), + expandvars=True, + ) + channel_priority = ParameterLoader(PrimitiveParameter(ChannelPriority.FLEXIBLE)) + _channels = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str), default=()), + aliases=( + "channels", + "channel", + ), + expandvars=True, + ) # channel for args.channel + channel_settings = ParameterLoader( + SequenceParameter(MapParameter(PrimitiveParameter("", element_type=str))) + ) + _custom_channels = ParameterLoader( + MapParameter(PrimitiveParameter("", element_type=str), DEFAULT_CUSTOM_CHANNELS), + aliases=("custom_channels",), + expandvars=True, + ) + _custom_multichannels = ParameterLoader( + MapParameter(SequenceParameter(PrimitiveParameter("", element_type=str))), + aliases=("custom_multichannels",), + expandvars=True, + ) + _default_channels = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str), DEFAULT_CHANNELS), + aliases=("default_channels",), + expandvars=True, + ) + _migrated_channel_aliases = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str)), + aliases=("migrated_channel_aliases",), + ) + migrated_custom_channels = ParameterLoader( + MapParameter(PrimitiveParameter("", element_type=str)), expandvars=True + ) # TODO: also take a list of strings + override_channels_enabled = ParameterLoader(PrimitiveParameter(True)) + show_channel_urls = ParameterLoader( + PrimitiveParameter(None, element_type=(bool, NoneType)) + ) + use_local = ParameterLoader(PrimitiveParameter(False)) + allowlist_channels = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str)), + aliases=("whitelist_channels",), + expandvars=True, + ) + denylist_channels = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str)), + expandvars=True, + ) + repodata_fns = ParameterLoader( + SequenceParameter( + PrimitiveParameter("", element_type=str), + ("current_repodata.json", REPODATA_FN), + ) + ) + _use_only_tar_bz2 = ParameterLoader( + PrimitiveParameter(None, element_type=(bool, NoneType)), + aliases=("use_only_tar_bz2",), + ) + + always_softlink = ParameterLoader(PrimitiveParameter(False), aliases=("softlink",)) + always_copy = ParameterLoader(PrimitiveParameter(False), aliases=("copy",)) + always_yes = ParameterLoader( + PrimitiveParameter(None, element_type=(bool, NoneType)), aliases=("yes",) + ) + _debug = ParameterLoader(PrimitiveParameter(False), aliases=["debug"]) + _trace = ParameterLoader(PrimitiveParameter(False), aliases=["trace"]) + dev = ParameterLoader(PrimitiveParameter(False)) + dry_run = ParameterLoader(PrimitiveParameter(False)) + _error_upload_url = ParameterLoader( + PrimitiveParameter("https://conda.io/conda-post/unexpected-error"), + aliases=("error_upload_url",), + ) + force = ParameterLoader(PrimitiveParameter(False)) + json = ParameterLoader(PrimitiveParameter(False)) + _console = ParameterLoader( + PrimitiveParameter(DEFAULT_CONSOLE_REPORTER_BACKEND, element_type=str), + aliases=["console"], + ) + list_fields = ParameterLoader( + SequenceParameter( + PrimitiveParameter("", element_type=str), + default=DEFAULT_CONDA_LIST_FIELDS, + validation=list_fields_validation, + ) + ) + offline = ParameterLoader(PrimitiveParameter(False)) + quiet = ParameterLoader(PrimitiveParameter(False)) + ignore_pinned = ParameterLoader(PrimitiveParameter(False)) + _report_errors = ParameterLoader( + PrimitiveParameter(None, element_type=(bool, NoneType)), + aliases=("report_errors",), + ) + shortcuts = ParameterLoader(PrimitiveParameter(True)) + number_channel_notices = ParameterLoader(PrimitiveParameter(5, element_type=int)) + shortcuts = ParameterLoader(PrimitiveParameter(True)) + shortcuts_only = ParameterLoader( + SequenceParameter(PrimitiveParameter("", element_type=str)), expandvars=True + ) + _verbosity = ParameterLoader( + PrimitiveParameter(0, element_type=int), aliases=("verbose", "verbosity") + ) + experimental = ParameterLoader(SequenceParameter(PrimitiveParameter("", str))) + no_lock = ParameterLoader(PrimitiveParameter(False)) + repodata_use_zst = ParameterLoader(PrimitiveParameter(True)) + envvars_force_uppercase = ParameterLoader(PrimitiveParameter(True)) + + #################################################### + # Solver Configuration # + #################################################### + deps_modifier = ParameterLoader(PrimitiveParameter(DepsModifier.NOT_SET)) + update_modifier = ParameterLoader(PrimitiveParameter(UpdateModifier.UPDATE_SPECS)) + sat_solver = ParameterLoader(PrimitiveParameter(SatSolverChoice.PYCOSAT)) + solver_ignore_timestamps = ParameterLoader(PrimitiveParameter(False)) + solver = ParameterLoader( + PrimitiveParameter(DEFAULT_SOLVER), + aliases=("experimental_solver",), + ) + + # # CLI-only + # no_deps = ParameterLoader(PrimitiveParameter(NULL, element_type=(type(NULL), bool))) + # # CLI-only + # only_deps = ParameterLoader(PrimitiveParameter(NULL, element_type=(type(NULL), bool))) + # + # freeze_installed = ParameterLoader(PrimitiveParameter(False)) + # update_deps = ParameterLoader(PrimitiveParameter(False), aliases=('update_dependencies',)) + # update_specs = ParameterLoader(PrimitiveParameter(False)) + # update_all = ParameterLoader(PrimitiveParameter(False)) + + force_remove = ParameterLoader(PrimitiveParameter(False)) + force_reinstall = ParameterLoader(PrimitiveParameter(False)) + + target_prefix_override = ParameterLoader(PrimitiveParameter("")) + + unsatisfiable_hints = ParameterLoader(PrimitiveParameter(True)) + unsatisfiable_hints_check_depth = ParameterLoader(PrimitiveParameter(2)) + + # conda_build + bld_path = ParameterLoader(PrimitiveParameter("")) + anaconda_upload = ParameterLoader( + PrimitiveParameter(None, element_type=(bool, NoneType)), + aliases=("binstar_upload",), + ) + _croot = ParameterLoader(PrimitiveParameter(""), aliases=("croot",)) + _conda_build = ParameterLoader( + MapParameter(PrimitiveParameter("", element_type=str)), + aliases=("conda-build", "conda_build"), + ) + + _override_virtual_packages = ParameterLoader( + MapParameter(PrimitiveParameter(None, element_type=(str, NoneType))), + aliases=("virtual_packages", "override_virtual_packages"), + ) + + #################################################### + # Plugin Configuration # + #################################################### + + no_plugins = ParameterLoader(PrimitiveParameter(NO_PLUGINS)) + + def __init__( + self, + search_path: PathsType | None = None, + argparse_args: Namespace | None = None, + **kwargs, + ): + super().__init__(argparse_args=argparse_args) + + self._set_search_path( + SEARCH_PATH if search_path is None else search_path, + # for proper search_path templating when --name/--prefix is used + CONDA_PREFIX=determine_target_prefix(self, argparse_args), + ) + self._set_env_vars(APP_NAME) + self._set_argparse_args(argparse_args) + + def post_build_validation(self) -> list[ValidationError]: + errors = [] + if self.client_ssl_cert_key and not self.client_ssl_cert: + error = ValidationError( + "client_ssl_cert", + self.client_ssl_cert, + "<>", + "'client_ssl_cert' is required when 'client_ssl_cert_key' is defined", + ) + errors.append(error) + if self.always_copy and self.always_softlink: + error = ValidationError( + "always_copy", + self.always_copy, + "<>", + "'always_copy' and 'always_softlink' are mutually exclusive. " + "Only one can be set to 'True'.", + ) + errors.append(error) + return errors + + @property + def plugin_manager(self) -> CondaPluginManager: + """ + This is the preferred way of accessing the ``PluginManager`` object for this application + and is located here to avoid problems with cyclical imports elsewhere in the code. + """ + from ..plugins.manager import get_plugin_manager + + return get_plugin_manager() + + @cached_property + def plugins(self) -> PluginConfig: + """ + Preferred way of accessing settings introduced by the settings plugin hook + """ + self.plugin_manager.load_settings() + return self.plugin_manager.get_config(self.raw_data) + + @property + @deprecated( + "26.9", + "27.3", + ) + def error_upload_url(self) -> str: + return self._error_upload_url + + @property + @deprecated( + "26.9", + "27.3", + ) + def report_errors(self) -> str: + return self._report_errors + + @property + def conda_build_local_paths(self) -> tuple[PathType, ...]: + # does file system reads to make sure paths actually exist + return tuple( + unique( + full_path + for full_path in ( + expand(d) + for d in ( + self._croot, + self.bld_path, + self.conda_build.get("root-dir"), + join(self.root_prefix, "conda-bld"), + "~/conda-bld", + ) + if d + ) + if isdir(full_path) + ) + ) + + @property + def conda_build_local_urls(self) -> tuple[str, ...]: + return tuple(path_to_url(p) for p in self.conda_build_local_paths) + + @property + def croot(self) -> PathType: + """This is where source caches and work folders live""" + if self._croot: + return abspath(expanduser(self._croot)) + elif self.bld_path: + return abspath(expanduser(self.bld_path)) + elif "root-dir" in self.conda_build: + return abspath(expanduser(self.conda_build["root-dir"])) + elif self.root_writable: + return join(self.root_prefix, "conda-bld") + else: + return expand("~/conda-bld") + + @property + def local_build_root(self) -> PathType: + return self.croot + + @property + def conda_build(self) -> dict[str, Any]: + # conda-build needs its config map to be mutable + try: + return self.__conda_build + except AttributeError: + self.__conda_build = __conda_build = dict(self._conda_build) + return __conda_build + + @property + def arch_name(self) -> str: + m = platform.machine() + if m in non_x86_machines: + return m + else: + return _arch_names[self.bits] + + @property + def platform(self) -> str: + return _platform_map.get(sys.platform, "unknown") + + @property + def default_threads(self) -> int | None: + return self._default_threads or None + + @property + def repodata_threads(self) -> int | None: + return self._repodata_threads or self.default_threads + + @property + def fetch_threads(self) -> int | None: + """ + If both are not overriden (0), return experimentally-determined value of 5 + """ + if self._fetch_threads == 0 and self._default_threads == 0: + return 5 + return self._fetch_threads or self.default_threads + + @property + def verify_threads(self) -> int | None: + if self._verify_threads: + threads = self._verify_threads + elif self.default_threads: + threads = self.default_threads + else: + threads = 1 + return threads + + @property + def execute_threads(self) -> int | None: + if self._execute_threads: + threads = self._execute_threads + elif self.default_threads: + threads = self.default_threads + else: + threads = 1 + return threads + + @property + def subdir(self) -> str: # TODO: Make KNOWN_SUBDIRS an Enum + if self._subdir: + return self._subdir + return self._native_subdir() + + @cache + def _native_subdir(self) -> str: + m = platform.machine() + if m in non_x86_machines: + return f"{self.platform}-{m}" + elif self.platform == "zos": + return "zos-z" + else: + return "%s-%d" % (self.platform, self.bits) + + @property + def subdirs(self) -> tuple[str, str]: + return self._subdirs or (self.subdir, "noarch") + + @memoizedproperty + def known_subdirs(self) -> frozenset[str]: + return frozenset((*KNOWN_SUBDIRS, *self.subdirs)) + + @property + def export_platforms(self) -> tuple[str, ...]: + # detect if platforms are overridden by the user + argparse_args = dict(getattr(self, "_argparse_args", {}) or {}) + if argparse_args.get("override_platforms"): + platforms = argparse_args.get("export_platforms") or () + else: + platforms = self._export_platforms + + # default to the current platform if no platforms are provided + return tuple(unique(platforms)) or (self.subdir,) + + @property + def bits(self) -> int: + if self.force_32bit: + return 32 + else: + return 8 * struct.calcsize("P") + + @property + def root_writable(self) -> bool: + # rather than using conda.gateways.disk.test.prefix_is_writable + # let's shortcut and assume the root prefix exists + path = join(self.root_prefix, PREFIX_MAGIC_FILE) + if isfile(path): + try: + fh = open(path, "a+") + except OSError as e: + log.debug(e) + return False + else: + fh.close() + return True + return False + + @property + def envs_dirs(self) -> tuple[PathType, ...]: + return mockable_context_envs_dirs( + self.root_writable, self.root_prefix, self._envs_dirs + ) + + @property + def pkgs_dirs(self) -> tuple[PathType, ...]: + if self._pkgs_dirs: + return tuple(dict.fromkeys(expand(p) for p in self._pkgs_dirs)) + else: + cache_dir_name = "pkgs32" if context.force_32bit else "pkgs" + fixed_dirs = ( + self.root_prefix, + join("~", ".conda"), + ) + if on_win: + fixed_dirs += (user_data_dir(APP_NAME, APP_NAME),) + return tuple( + dict.fromkeys(expand(join(p, cache_dir_name)) for p in (fixed_dirs)) + ) + + @memoizedproperty + def trash_dir(self) -> PathType: + # TODO: this inline import can be cleaned up by moving pkgs_dir write detection logic + from ..core.package_cache_data import PackageCacheData + + pkgs_dir = PackageCacheData.first_writable().pkgs_dir + trash_dir = join(pkgs_dir, ".trash") + from ..gateways.disk.create import mkdir_p + + mkdir_p(trash_dir) + return trash_dir + + @property + def default_prefix(self) -> PathType: + if self.active_prefix: + return self.active_prefix + _default_env = os.getenv("CONDA_DEFAULT_ENV") + if _default_env in (None, *RESERVED_ENV_NAMES): + return self.root_prefix + elif os.sep in _default_env: + return abspath(_default_env) + else: + for envs_dir in self.envs_dirs: + default_prefix = join(envs_dir, _default_env) + if isdir(default_prefix): + return default_prefix + return join(self.envs_dirs[0], _default_env) + + @property + def active_prefix(self) -> PathType: + return os.getenv("CONDA_PREFIX") + + @property + def shlvl(self) -> int: + return int(os.getenv("CONDA_SHLVL", -1)) + + @property + def aggressive_update_packages(self) -> tuple[MatchSpec, ...]: + from ..models.match_spec import MatchSpec + + return tuple(MatchSpec(s) for s in self._aggressive_update_packages) + + @property + def target_prefix(self) -> PathType: + # used for the prefix that is the target of the command currently being executed + # different from the active prefix, which is sometimes given by -p or -n command line flags + return determine_target_prefix(self) + + @memoizedproperty + def root_prefix(self) -> PathType: + if self._root_prefix: + return abspath(expanduser(self._root_prefix)) + else: + return self.conda_prefix + + @property + def conda_prefix(self) -> PathType: + return abspath(sys.prefix) + + @property + @deprecated( + "23.9", + "26.3", + addendum="Please use `conda.base.context.context.conda_exe_vars_dict` instead", + ) + def conda_exe(self) -> PathType: + exe = "conda.exe" if on_win else "conda" + return join(self.conda_prefix, BIN_DIRECTORY, exe) + + @property + def av_data_dir(self) -> PathType: + """Where critical artifact verification data (e.g., various public keys) can be found.""" + # TODO (AV): Find ways to make this user configurable? + return join(self.conda_prefix, "etc", "conda") + + @property + def signing_metadata_url_base(self) -> str | None: + """Base URL for artifact verification signing metadata (*.root.json, key_mgr.json).""" + if self._signing_metadata_url_base: + return self._signing_metadata_url_base + else: + return None + + @property + def conda_exe_vars_dict(self) -> dict[str, str | None]: + """ + The vars can refer to each other if necessary since the dict is ordered. + None means unset it. + """ + if context.dev: + if pythonpath := os.environ.get("PYTHONPATH", ""): + pythonpath = os.pathsep.join((CONDA_SOURCE_ROOT, pythonpath)) + else: + pythonpath = CONDA_SOURCE_ROOT + return { + "CONDA_EXE": sys.executable, + "_CONDA_EXE": sys.executable, + # do not confuse with os.path.join, we are joining paths with ; or : delimiters + "PYTHONPATH": pythonpath, + "_CE_M": "-m", + "_CE_CONDA": "conda", + "CONDA_PYTHON_EXE": sys.executable, + "_CONDA_ROOT": self.conda_prefix, + } + else: + exe = os.path.join( + self.conda_prefix, + BIN_DIRECTORY, + "conda.exe" if on_win else "conda", + ) + return { + "CONDA_EXE": exe, + "_CONDA_EXE": exe, + "_CE_M": None, + "_CE_CONDA": None, + "CONDA_PYTHON_EXE": sys.executable, + "_CONDA_ROOT": self.conda_prefix, + } + + @memoizedproperty + def channel_alias(self) -> Channel: + from ..models.channel import Channel + + location, scheme, auth, token = split_scheme_auth_token(self._channel_alias) + return Channel(scheme=scheme, auth=auth, location=location, token=token) + + @property + def migrated_channel_aliases(self) -> tuple[Channel, ...]: + from ..models.channel import Channel + + return tuple( + Channel(scheme=scheme, auth=auth, location=location, token=token) + for location, scheme, auth, token in ( + split_scheme_auth_token(c) for c in self._migrated_channel_aliases + ) + ) + + @property + def prefix_specified(self) -> bool: + return ( + self._argparse_args.get("prefix") is not None + or self._argparse_args.get("name") is not None + ) + + @memoizedproperty + def default_channels(self) -> list[Channel]: + # the format for 'default_channels' is a list of strings that either + # - start with a scheme + # - are meant to be prepended with channel_alias + return self.custom_multichannels[DEFAULTS_CHANNEL_NAME] + + @memoizedproperty + def custom_multichannels(self) -> dict[str, tuple[Channel, ...]]: + from ..models.channel import Channel + + if ( + not on_win + and self.subdir.startswith("win-") + and self._default_channels == DEFAULT_CHANNELS_UNIX + ): + default_channels = list(DEFAULT_CHANNELS_WIN) + else: + default_channels = list(self._default_channels) + + return { + name: tuple( + Channel.make_simple_channel(self.channel_alias, url) for url in urls + ) + for name, urls in { + # order matters + DEFAULTS_CHANNEL_NAME: default_channels, # default_channels is a legacy keyword + **self._custom_multichannels, # custom_multichannels.defaults overrides default_channels + "local": self.conda_build_local_urls, # always last, local is a reserved name and cannot be overridden + }.items() + } + + @memoizedproperty + def custom_channels(self) -> dict[str, Channel]: + from ..models.channel import Channel + + return { + channel.name: channel + for channel in ( + *chain.from_iterable( + channel for channel in self.custom_multichannels.values() + ), + *( + Channel.make_simple_channel(self.channel_alias, url, name) + for name, url in self._custom_channels.items() + ), + ) + } + + @property + def channels(self) -> tuple[str, ...]: + local_channels = ("local",) if self.use_local else () + argparse_args = dict(getattr(self, "_argparse_args", {}) or {}) + # TODO: it's args.channel right now, not channels + cli_channels = argparse_args.get("channel") or () + + if argparse_args.get("override_channels"): + if not self.override_channels_enabled: + from ..exceptions import OperationNotAllowed + + raise OperationNotAllowed("Overriding channels has been disabled.") + + if cli_channels: + return validate_channels((*local_channels, *cli_channels)) + else: + from ..exceptions import ArgumentError + + raise ArgumentError( + "At least one -c / --channel flag must be supplied when using " + "--override-channels." + ) + + return validate_channels((*local_channels, *self._channels)) + + @property + def config_files(self) -> tuple[PathType, ...]: + return tuple( + path + for path in context.collect_all() + if path not in (ENV_VARS_SOURCE, CMD_LINE_SOURCE) + ) + + @property + def use_only_tar_bz2(self) -> bool: + # we avoid importing this at the top to avoid PATH issues. Ensure that this + # is only called when use_only_tar_bz2 is first called. + import conda_package_handling.api + + return ( + not conda_package_handling.api.libarchive_enabled + ) or self._use_only_tar_bz2 + + @property + def binstar_upload(self) -> bool | None: + # backward compatibility for conda-build + return self.anaconda_upload + + @property + def trace(self) -> bool: + """Alias for context.verbosity >=4.""" + return self.verbosity >= 4 + + @property + def debug(self) -> bool: + """Alias for context.verbosity >=3.""" + return self.verbosity >= 3 + + @property + def info(self) -> bool: + """Alias for context.verbosity >=2.""" + return self.verbosity >= 2 + + @property + def verbose(self) -> bool: + """Alias for context.verbosity >=1.""" + return self.verbosity >= 1 + + @property + def verbosity(self) -> int: + """Verbosity level. + + For cleaner and readable code it is preferable to use the following alias properties: + context.trace + context.debug + context.info + context.verbose + context.log_level + """ + # 0 → logging.WARNING, standard output + # -v = 1 → logging.WARNING, detailed output + # -vv = 2 → logging.INFO + # --debug = -vvv = 3 → logging.DEBUG + # --trace = -vvvv = 4 → conda.gateways.logging.TRACE + if self._trace: + return 4 + elif self._debug: + return 3 + else: + return self._verbosity + + @property + def log_level(self) -> int: + """Map context.verbosity to logging level.""" + if 4 < self.verbosity: + return logging.NOTSET # 0 + elif 3 < self.verbosity <= 4: + return TRACE # 5 + elif 2 < self.verbosity <= 3: + return logging.DEBUG # 10 + elif 1 < self.verbosity <= 2: + return logging.INFO # 20 + else: + return logging.WARNING # 30 + + @property + def override_virtual_packages(self) -> dict[str, str | None]: + """Remove any dunders in the virtual_package name keys""" + return { + name.removeprefix("__"): value + for name, value in self._override_virtual_packages.items() + } + + def solver_user_agent(self) -> str: + user_agent = f"solver/{self.solver}" + try: + solver_backend = self.plugin_manager.get_cached_solver_backend() + # Solver.user_agent has to be a static or class method + user_agent += f" {solver_backend.user_agent()}" + except Exception as exc: + log.debug( + "User agent could not be fetched from solver class '%s'.", + self.solver, + exc_info=exc, + ) + return user_agent + + @memoizedproperty + def user_agent(self) -> str: + builder = [f"conda/{CONDA_VERSION} requests/{self.requests_version}"] + builder.append("{}/{}".format(*self.python_implementation_name_version)) + builder.append("{}/{}".format(*self.platform_system_release)) + builder.append("{}/{}".format(*self.os_distribution_name_version)) + if self.libc_family_version[0]: + builder.append("{}/{}".format(*self.libc_family_version)) + if self.solver != "classic": + builder.append(self.solver_user_agent()) + return " ".join(builder) + + @contextmanager + def _override(self, key: str, value: Any) -> Iterator[None]: + """ + TODO: This might be broken in some ways. Unsure what happens if the `old` + value is a property and gets set to a new value. Or if the new value + overrides the validation logic on the underlying ParameterLoader instance. + + Investigate and implement in a safer way. + """ + old = getattr(self, key) + setattr(self, key, value) + try: + yield + finally: + setattr(self, key, old) + + @memoizedproperty + def requests_version(self) -> str: + # used in User-Agent as "requests/" + # if unable to detect a version we expect "requests/unknown" + try: + from requests import __version__ as requests_version + except ImportError as err: + # ImportError: requests is not installed + log.error("Unable to import requests: %s", err) + requests_version = "unknown" + except Exception as err: + log.error("Error importing requests: %s", err) + requests_version = "unknown" + return requests_version + + @memoizedproperty + def python_implementation_name_version(self) -> tuple[str, str]: + # CPython, Jython + # '2.7.14' + return platform.python_implementation(), platform.python_version() + + @memoizedproperty + def platform_system_release(self) -> tuple[str, str]: + # tuple of system name and release version + # + # `uname -s` Linux, Windows, Darwin, Java + # + # `uname -r` + # '17.4.0' for macOS + # '10' or 'NT' for Windows + return platform.system(), platform.release() + + @memoizedproperty + def os_distribution_name_version(self) -> tuple[str, str]: + # tuple of os distribution name and version + # e.g. + # 'debian', '9' + # 'OSX', '10.13.6' + # 'Windows', '10.0.17134' + platform_name = self.platform_system_release[0] + if platform_name == "Linux": + try: + import distro + + distinfo = distro.id(), distro.version(best=True) + except Exception as e: + log.debug("%r", e, exc_info=True) + distinfo = ("Linux", "unknown") + distribution_name, distribution_version = distinfo[0], distinfo[1] + elif platform_name == "Darwin": + distribution_name = "OSX" + distribution_version = mac_ver() + else: + distribution_name = platform_name + distribution_version = platform.version() + return distribution_name, distribution_version + + @memoizedproperty + def libc_family_version(self) -> tuple[str | None, str | None]: + # tuple of lic_family and libc_version + # None, None if not on Linux + libc_family, libc_version = linux_get_libc_version() + return libc_family, libc_version + + @property + def console(self) -> str: + if self.json: + return DEFAULT_JSON_REPORTER_BACKEND + return self._console + + @property + @deprecated( + "25.9", + "26.3", + addendum="Please use `conda.base.context.context.auto_activate` instead", + ) + def auto_activate_base(self) -> bool: + return self.auto_activate + + @property + def default_activation_env(self) -> str: + return self._default_activation_env or ROOT_ENV_NAME + + @property + def create_default_packages(self) -> tuple[str, ...]: + """Returns a list of `create_default_packages`, removing any explicit packages.""" + from ..common.io import dashlist + + grouped_packages = groupby_to_dict( + lambda x: "explicit" + if context.plugin_manager.has_package_extension(x) + else "spec", + sequence=self._create_default_packages, + ) + + if grouped_packages.get("explicit", None): + warnings.warn( + f"Ignoring invalid packages in `create_default_packages`: {dashlist(grouped_packages.get('explicit'))}\n" + f"\n" + f"Explicit package are not allowed, use package names like 'numpy' or specs like 'numpy>=1.20' instead.\n" + f"Try using the command `conda config --show-sources` to verify your conda configuration.\n", + UserWarning, + ) + return tuple(grouped_packages.get("spec", [])) + + @property + def default_activation_prefix(self) -> Path: + """Return the prefix of the default_activation_env. + + If the default_activation_env is an environment name, get the corresponding + prefix; otherwise it is already a prefix, so just return it. + + :return: Prefix of the default_activation_env + """ + from ..exceptions import EnvironmentNameNotFound + + try: + return Path(locate_prefix_by_name(self.default_activation_env)) + except EnvironmentNameNotFound: + return Path(self.default_activation_env) + + @property + def environment_context_keys(self) -> list[str]: + return [ + "aggressive_update_packages", + "channel_priority", + "channels", + "channel_settings", + "custom_channels", + "custom_multichannels", + "deps_modifier", + "disallowed_packages", + "pinned_packages", + "repodata_fns", + "sat_solver", + "solver", + "track_features", + "update_modifier", + "use_only_tar_bz2", + ] + + @property + def environment_settings(self) -> dict[str, Any]: + """Returns a dict of environment related settings""" + return {key: getattr(self, key) for key in self.environment_context_keys} + + @property + def category_map(self) -> dict[str, tuple[str, ...]]: + return { + "Channel Configuration": ( + "channels", + "channel_alias", + "channel_settings", + "default_channels", + "override_channels_enabled", + "allowlist_channels", + "denylist_channels", + "custom_channels", + "custom_multichannels", + "migrated_channel_aliases", + "migrated_custom_channels", + "add_anaconda_token", + "allow_non_channel_urls", + "repodata_fns", + "use_only_tar_bz2", + "repodata_threads", + "fetch_threads", + "experimental", + "no_lock", + "repodata_use_zst", + ), + "Basic Conda Configuration": ( # TODO: Is there a better category name here? + "envs_dirs", + "pkgs_dirs", + "default_threads", + ), + "Network Configuration": ( + "client_ssl_cert", + "client_ssl_cert_key", + "local_repodata_ttl", + "offline", + "proxy_servers", + "remote_connect_timeout_secs", + "remote_max_retries", + "remote_backoff_factor", + "remote_read_timeout_secs", + "ssl_verify", + ), + "Solver Configuration": ( + "aggressive_update_packages", + "auto_update_conda", + "channel_priority", + "create_default_packages", + "disallowed_packages", + "force_reinstall", + "pinned_packages", + "prefix_data_interoperability", + "track_features", + "solver", + ), + "Package Linking and Install-time Configuration": ( + "allow_softlinks", + "always_copy", + "always_softlink", + "path_conflict", + "rollback_enabled", + "safety_checks", + "extra_safety_checks", + "signing_metadata_url_base", + "shortcuts", + "shortcuts_only", + "non_admin_enabled", + "separate_format_cache", + "verify_threads", + "execute_threads", + ), + "Conda-build Configuration": ( + "bld_path", + "croot", + "anaconda_upload", + "conda_build", + ), + "Output, Prompt, and Flow Control Configuration": ( + "always_yes", + "auto_activate", + "default_activation_env", + "auto_stack", + "changeps1", + "env_prompt", + "json", + "console", + "notify_outdated_conda", + "quiet", + "report_errors", + "show_channel_urls", + "list_fields", + "verbosity", + "unsatisfiable_hints", + "unsatisfiable_hints_check_depth", + "number_channel_notices", + "envvars_force_uppercase", + "export_platforms", + "override_virtual_packages", + ), + "CLI-only": ( + "deps_modifier", + "update_modifier", + "force", + "force_remove", + "clobber", + "dry_run", + "download_only", + "ignore_pinned", + "use_index_cache", + "use_local", + ), + "Hidden and Undocumented": ( + "allow_cycles", # allow cyclical dependencies, or raise + "allow_conda_downgrades", + "add_pip_as_python_dependency", + "debug", + "trace", + "dev", + "default_python", + "enable_private_envs", + "error_upload_url", # TODO: Remove after deprecation ended + "force_32bit", + "root_prefix", + "sat_solver", + "solver_ignore_timestamps", + "subdir", + "subdirs", + # https://conda.io/docs/config.html#disable-updating-of-dependencies-update-dependencies + # I don't think this documentation is correct any longer. + "target_prefix_override", + # used to override prefix rewriting, for e.g. building docker containers or RPMs + "register_envs", + # whether to add the newly created prefix to ~/.conda/environments.txt + "protect_frozen_envs", + # prevent modifications to envs marked with conda-meta/frozen + ), + "Plugin Configuration": ("no_plugins",), + "Experimental": ("environment_specifier",), + } + + def get_descriptions(self) -> dict[str, str]: + return self.description_map + + @memoizedproperty + def description_map(self) -> dict[str, str]: + return frozendict( + add_anaconda_token=dals( + """ + In conjunction with the anaconda command-line client (installed with + `conda install anaconda-client`), and following logging into an Anaconda + Server API site using `anaconda login`, automatically apply a matching + private token to enable access to private packages and channels. + """ + ), + # add_pip_as_python_dependency=dals( + # """ + # Add pip, wheel and setuptools as dependencies of python. This ensures pip, + # wheel and setuptools will always be installed any time python is installed. + # """ + # ), + aggressive_update_packages=dals( + """ + A list of packages that, if installed, are always updated to the latest possible + version. + """ + ), + allow_non_channel_urls=dals( + """ + Warn, but do not fail, when conda detects a channel url is not a valid channel. + """ + ), + allow_softlinks=dals( + """ + When allow_softlinks is True, conda uses hard-links when possible, and soft-links + (symlinks) when hard-links are not possible, such as when installing on a + different filesystem than the one that the package cache is on. When + allow_softlinks is False, conda still uses hard-links when possible, but when it + is not possible, conda copies files. Individual packages can override + this setting, specifying that certain files should never be soft-linked (see the + no_link option in the build recipe documentation). + """ + ), + always_copy=dals( + """ + Register a preference that files be copied into a prefix during install rather + than hard-linked. + """ + ), + always_softlink=dals( + """ + Register a preference that files be soft-linked (symlinked) into a prefix during + install rather than hard-linked. The link source is the 'pkgs_dir' package cache + from where the package is being linked. WARNING: Using this option can result in + corruption of long-lived conda environments. Package caches are *caches*, which + means there is some churn and invalidation. With this option, the contents of + environments can be switched out (or erased) via operations on other environments. + """ + ), + always_yes=dals( + """ + Automatically choose the 'yes' option whenever asked to proceed with a conda + operation, such as when running `conda install`. + """ + ), + anaconda_upload=dals( + """ + Automatically upload packages built with conda build to anaconda.org. + """ + ), + auto_activate=dals( + """ + Automatically activate the environment given at 'default_activation_env' + during shell initialization. + """ + ), + auto_update_conda=dals( + """ + Automatically update conda when a newer or higher priority version is detected. + """ + ), + auto_stack=dals( + """ + Implicitly use --stack when using activate if current level of nesting + (as indicated by CONDA_SHLVL environment variable) is less than or equal to + specified value. 0 or false disables automatic stacking, 1 or true enables + it for one level. + """ + ), + bld_path=dals( + """ + The location where conda-build will put built packages. Same as 'croot', but + 'croot' takes precedence when both are defined. Also used in construction of the + 'local' multichannel. + """ + ), + changeps1=dals( + """ + When using activate, change the command prompt ($PS1) to include the + activated environment. + """ + ), + channel_alias=dals( + """ + The prepended url location to associate with channel names. + """ + ), + channel_priority=dals( + """ + Accepts values of 'strict', 'flexible', and 'disabled'. The default value + is 'flexible'. With strict channel priority, packages in lower priority channels + are not considered if a package with the same name appears in a higher + priority channel. With flexible channel priority, the solver may reach into + lower priority channels to fulfill dependencies, rather than raising an + unsatisfiable error. With channel priority disabled, package version takes + precedence, and the configured priority of channels is used only to break ties. + In previous versions of conda, this parameter was configured as either True or + False. True is now an alias to 'flexible'. + """ + ), + channels=dals( + """ + The list of conda channels to include for relevant operations. + """ + ), + channel_settings=dals( + """ + A list of mappings that allows overriding certain settings for a single channel. + Each list item should include at least the "channel" key and the setting you would + like to override. + """ + ), + client_ssl_cert=dals( + """ + A path to a single file containing a private key and certificate (e.g. .pem + file). Alternately, use client_ssl_cert_key in conjunction with client_ssl_cert + for individual files. + """ + ), + client_ssl_cert_key=dals( + """ + Used in conjunction with client_ssl_cert for a matching key file. + """ + ), + # clobber=dals( + # """ + # Allow clobbering of overlapping file paths within packages, and suppress + # related warnings. Overrides the path_conflict configuration value when + # set to 'warn' or 'prevent'. + # """ + # ), + # TODO: add shortened link to docs for conda_build at See https://conda.io/docs/user-guide/configuration/use-condarc.html#conda-build-configuration + conda_build=dals( + """ + General configuration parameters for conda-build. + """ + ), + # TODO: This is a bad parameter name. Consider an alternate. + create_default_packages=dals( + """ + Packages that are by default added to a newly created environments. + """ + ), + croot=dals( + """ + The location where conda-build will put built packages. Same as 'bld_path', but + 'croot' takes precedence when both are defined. Also used in construction of the + 'local' multichannel. + """ + ), + custom_channels=dals( + """ + A map of key-value pairs where the key is a channel name and the value is + a channel location. Channels defined here override the default + 'channel_alias' value. The channel name (key) is not included in the channel + location (value). For example, to override the location of the 'conda-forge' + channel where the url to repodata is + https://anaconda-repo.dev/packages/conda-forge/linux-64/repodata.json, add an + entry 'conda-forge: https://anaconda-repo.dev/packages'. + """ + ), + custom_multichannels=dals( + """ + A multichannel is a metachannel composed of multiple channels. The only reserved + multichannel is 'local', which is a list of file:// channel locations where + conda-build stashes successfully-built packages and cannot be overridden. + Other multichannels, including 'defaults', can be defined or customized with + custom_multichannels, where the key is the multichannel name and the value is + a list of channel names and/or channel urls. The 'defaults' multichannel can + also be customized using the 'default_channels' parameter (a historical setting + from when 'defaults' was reserved). If both are defined, + 'custom_multichannels.defaults' takes precedence. + """ + ), + default_activation_env=dals( + """ + The environment to be automatically activated on startup if 'auto_activate' + is True. Also sets the default environment to activate when 'conda activate' + receives no arguments. + """ + ), + default_channels=dals( + """ + The list of channel names and/or urls used for the 'defaults' multichannel. + Can be overridden by 'custom_multichannels.defaults'. + """ + ), + # default_python=dals( + # """ + # specifies the default major & minor version of Python to be used when + # building packages with conda-build. Also used to determine the major + # version of Python (2/3) to be used in new environments. Defaults to + # the version used by conda itself. + # """ + # ), + default_threads=dals( + """ + Threads to use by default for parallel operations. Default is None, + which allows operations to choose themselves. For more specific + control, see the other *_threads parameters: + * repodata_threads - for fetching/loading repodata + * verify_threads - for verifying package contents in transactions + * execute_threads - for carrying out the unlinking and linking steps + """ + ), + disallowed_packages=dals( + """ + Package specifications to disallow installing. The default is to allow + all packages. + """ + ), + download_only=dals( + """ + Solve an environment and ensure package caches are populated, but exit + prior to unlinking and linking packages into the prefix + """ + ), + envs_dirs=dals( + """ + The list of directories to search for named environments. When creating a new + named environment, the environment will be placed in the first writable + location. + """ + ), + env_prompt=dals( + """ + Template for prompt modification based on the active environment. Currently + supported template variables are '{prefix}', '{name}', and '{default_env}'. + '{prefix}' is the absolute path to the active environment. '{name}' is the + basename of the active environment prefix. '{default_env}' holds the value + of '{name}' if the active environment is a conda named environment ('-n' + flag), or otherwise holds the value of '{prefix}'. Templating uses python's + str.format() method. + """ + ), + environment_specifier=dals( + """ + **EXPERIMENTAL** While experimental, expect both major and minor changes across minor releases. + + The name of the environment specifier plugin that should be used for this context. + If not specified, the plugin manager will try to detect the plugin to use. + """ + ), + execute_threads=dals( + """ + Threads to use when performing the unlink/link transaction. When not set, + defaults to 1. This step is pretty strongly I/O limited, and you may not + see much benefit here. + """ + ), + export_platforms=dals( + """ + Additional platform(s)/subdir(s) for export (e.g., linux-64, osx-64, win-64), current + platform is always included. + """ + ), + fetch_threads=dals( + """ + Threads to use when downloading packages. When not set, + defaults to None, which uses the default ThreadPoolExecutor behavior. + """ + ), + force_reinstall=dals( + """ + Ensure that any user-requested package for the current operation is uninstalled + and reinstalled, even if that package already exists in the environment. + """ + ), + # force=dals( + # """ + # Override any of conda's objections and safeguards for installing packages and + # potentially breaking environments. Also re-installs the package, even if the + # package is already installed. Implies --no-deps. + # """ + # ), + # force_32bit=dals( + # """ + # CONDA_FORCE_32BIT should only be used when running conda-build (in order + # to build 32-bit packages on a 64-bit system). We don't want to mention it + # in the documentation, because it can mess up a lot of things. + # """ + # ), + json=dals( + """ + Ensure all output written to stdout is structured json. + """ + ), + list_fields=dals( + """ + Default fields to report as columns in the output of `conda list`. + """ + ), + local_repodata_ttl=dals( + """ + For a value of False or 0, always fetch remote repodata (HTTP 304 responses + respected). For a value of True or 1, respect the HTTP Cache-Control max-age + header. Any other positive integer values is the number of seconds to locally + cache repodata before checking the remote server for an update. + """ + ), + migrated_channel_aliases=dals( + """ + A list of previously-used channel_alias values. Useful when switching between + different Anaconda Repository instances. + """ + ), + migrated_custom_channels=dals( + """ + A map of key-value pairs where the key is a channel name and the value is + the previous location of the channel. + """ + ), + # no_deps=dals( + # """ + # Do not install, update, remove, or change dependencies. This WILL lead to broken + # environments and inconsistent behavior. Use at your own risk. + # """ + # ), + no_plugins=dals( + """ + Disable all currently-registered plugins, except built-in conda plugins. + """ + ), + non_admin_enabled=dals( + """ + Allows completion of conda's create, install, update, and remove operations, for + non-privileged (non-root or non-administrator) users. + """ + ), + notify_outdated_conda=dals( + """ + Notify if a newer version of conda is detected during a create, install, update, + or remove operation. + """ + ), + offline=dals( + """ + Restrict conda to cached download content and file:// based urls. + """ + ), + override_channels_enabled=dals( + """ + Permit use of the --override-channels command-line flag. + """ + ), + path_conflict=dals( + """ + The method by which conda handle's conflicting/overlapping paths during a + create, install, or update operation. The value must be one of 'clobber', + 'warn', or 'prevent'. The '--clobber' command-line flag or clobber + configuration parameter overrides path_conflict set to 'prevent'. + """ + ), + pinned_packages=dals( + """ + A list of package specs to pin for every environment resolution. + This parameter is in BETA, and its behavior may change in a future release. + """ + ), + prefix_data_interoperability=dals( + """ + Enable plugins to allow conda to interact with non-conda-installed packages. + """ + ), + pkgs_dirs=dals( + """ + The list of directories where locally-available packages are linked from at + install time. Packages not locally available are downloaded and extracted + into the first writable directory. + """ + ), + proxy_servers=dals( + """ + A mapping to enable proxy settings. Keys can be either (1) a scheme://hostname + form, which will match any request to the given scheme and exact hostname, or + (2) just a scheme, which will match requests to that scheme. Values are are + the actual proxy server, and are of the form + 'scheme://[user:password@]host[:port]'. The optional 'user:password' inclusion + enables HTTP Basic Auth with your proxy. + """ + ), + quiet=dals( + """ + Disable progress bar display and other output. + """ + ), + remote_connect_timeout_secs=dals( + """ + The number seconds conda will wait for your client to establish a connection + to a remote url resource. + """ + ), + remote_max_retries=dals( + """ + The maximum number of retries each HTTP connection should attempt. + """ + ), + remote_backoff_factor=dals( + """ + The factor determines the time HTTP connection should wait for attempt. + """ + ), + remote_read_timeout_secs=dals( + """ + Once conda has connected to a remote resource and sent an HTTP request, the + read timeout is the number of seconds conda will wait for the server to send + a response. + """ + ), + repodata_threads=dals( + """ + Threads to use when downloading and reading repodata. When not set, + defaults to None, which uses the default ThreadPoolExecutor behavior. + """ + ), + report_errors=dals( + """ + Opt in, or opt out, of automatic error reporting to core maintainers. Error + reports are anonymous, with only the error stack trace and information given + by `conda info` being sent. + """ + ), + rollback_enabled=dals( + """ + Should any error occur during an unlink/link transaction, revert any disk + mutations made to that point in the transaction. + """ + ), + safety_checks=dals( + """ + Enforce available safety guarantees during package installation. + The value must be one of 'enabled', 'warn', or 'disabled'. + """ + ), + separate_format_cache=dals( + """ + Treat .tar.bz2 files as different from .conda packages when + filenames are otherwise similar. This defaults to False, so + that your package cache doesn't churn when rolling out the new + package format. If you'd rather not assume that a .tar.bz2 and + .conda from the same place represent the same content, set this + to True. + """ + ), + extra_safety_checks=dals( + """ + Spend extra time validating package contents. Currently, runs sha256 verification + on every file within each package during installation. + """ + ), + signing_metadata_url_base=dals( + """ + Base URL for obtaining trust metadata updates (i.e., the `*.root.json` and + `key_mgr.json` files) used to verify metadata and (eventually) package signatures. + """ + ), + shortcuts=dals( + """ + Allow packages to create OS-specific shortcuts (e.g. in the Windows Start + Menu) at install time. + """ + ), + shortcuts_only=dals( + """ + Create shortcuts only for the specified package names. + """ + ), + show_channel_urls=dals( + """ + Show channel URLs when displaying what is going to be downloaded. + """ + ), + ssl_verify=dals( + """ + Conda verifies SSL certificates for HTTPS requests, just like a web + browser. By default, SSL verification is enabled, and conda operations will + fail if a required url's certificate cannot be verified. Setting ssl_verify to + False disables certification verification. The value for ssl_verify can also + be (1) a path to a CA bundle file, (2) a path to a directory containing + certificates of trusted CA, or (3) 'truststore' to use the + operating system certificate store. + """ + ), + track_features=dals( + """ + A list of features that are tracked by default. An entry here is similar to + adding an entry to the create_default_packages list. + """ + ), + repodata_fns=dals( + """ + Specify filenames for repodata fetching. The default is ('current_repodata.json', + 'repodata.json'), which tries a subset of the full index containing only the + latest version for each package, then falls back to repodata.json. You may + want to specify something else to use an alternate index that has been reduced + somehow. + """ + ), + use_index_cache=dals( + """ + Use cache of channel index files, even if it has expired. + """ + ), + use_only_tar_bz2=dals( + """ + A boolean indicating that only .tar.bz2 conda packages should be downloaded. + This is forced to True if conda-build is installed and older than 3.18.3, + because older versions of conda break when conda feeds it the new file format. + """ + ), + verbosity=dals( + """ + Sets output log level. 0 is warn. 1 is info. 2 is debug. 3 is trace. + """ + ), + verify_threads=dals( + """ + Threads to use when performing the transaction verification step. When not set, + defaults to 1. + """ + ), + allowlist_channels=dals( + """ + The exclusive list of channels allowed to be used on the system. Use of any + other channels will result in an error. If conda-build channels are to be + allowed, along with the --use-local command line flag, be sure to include the + 'local' channel in the list. If the list is empty or left undefined, no + channel exclusions will be enforced. + """ + ), + denylist_channels=dals( + """ + The list of channels that are denied to be used on the system. Use of any + of these channels will result in an error. If conda-build channels are to be + allowed, along with the --use-local command line flag, be sure to not include + the 'local' channel in the list. If the list is empty or left undefined, no + channel exclusions will be enforced. + """ + ), + unsatisfiable_hints=dals( + """ + A boolean to determine if conda should find conflicting packages in the case + of a failed install. + """ + ), + unsatisfiable_hints_check_depth=dals( + """ + An integer that specifies how many levels deep to search for unsatisfiable + dependencies. If this number is 1 it will complete the unsatisfiable hints + fastest (but perhaps not the most complete). The higher this number, the + longer the generation of the unsat hint will take. Defaults to 3. + """ + ), + solver=dals( + """ + A string to choose between the different solver logics implemented in + conda. A solver logic takes care of turning your requested packages into a + list of specs to add and/or remove from a given environment, based on their + dependencies and specified constraints. + """ + ), + number_channel_notices=dals( + """ + Sets the number of channel notices to be displayed when running commands + the "install", "create", "update", "env create", and "env update" . Defaults + to 5. In order to completely suppress channel notices, set this to 0. + """ + ), + experimental=dals( + """ + List of experimental features to enable. + """ + ), + no_lock=dals( + """ + Disable index cache lock (defaults to enabled). + """ + ), + repodata_use_zst=dals( + """ + Disable check for `repodata.json.zst`; use `repodata.json` only. + """ + ), + envvars_force_uppercase=dals( + """ + Force uppercase for new environment variable names. Defaults to True. + """ + ), + console=dals( + f""" + Configure different backends to be used while rendering normal console output. + Defaults to "{DEFAULT_CONSOLE_REPORTER_BACKEND}". + """ + ), + override_virtual_packages=dals( + """ + Set override values for virtual packages. + """ + ), + ) + + +def reset_context( + search_path: PathsType = SEARCH_PATH, + argparse_args: Namespace | None = None, +) -> Context: + global context + + # remove plugin config params + from ..plugins.config import PluginConfig + + PluginConfig.remove_all_plugin_settings() + + YamlRawParameter.cache_clear() + context.__init__(search_path, argparse_args) + context.__dict__.pop("_Context__conda_build", None) + from ..models.channel import Channel + + Channel._reset_state() + + # need to import here to avoid circular dependency + + # clear function cache + from ..reporters import _get_render_func + + # reload plugin config params + with suppress(AttributeError): + del context.plugins + + _get_render_func.cache_clear() + + return context + + +@contextmanager +def fresh_context( + env: dict[str, str] | None = None, + search_path: PathsType = SEARCH_PATH, + argparse_args: Namespace | None = None, + **kwargs, +) -> Iterator[Context]: + if env or kwargs: + old_env = os.environ.copy() + os.environ.update(env or {}) + os.environ.update(kwargs) + yield reset_context(search_path=search_path, argparse_args=argparse_args) + if env or kwargs: + os.environ.clear() + os.environ.update(old_env) + reset_context() + + +class ContextStackObject: + def __init__( + self, + search_path: PathsType = SEARCH_PATH, + argparse_args: Namespace | None = None, + ): + self.set_value(search_path, argparse_args) + + def set_value( + self, + search_path: PathsType = SEARCH_PATH, + argparse_args: Namespace | None = None, + ) -> None: + self.search_path = search_path + self.argparse_args = argparse_args + + def apply(self): + reset_context(self.search_path, self.argparse_args) + + +class ContextStack: + def __init__(self): + self._stack = [ContextStackObject() for _ in range(3)] + self._stack_idx = 0 + self._last_search_path = None + self._last_argparse_args = None + + def push(self, search_path: PathsType, argparse_args: Namespace | None) -> None: + self._stack_idx += 1 + old_len = len(self._stack) + if self._stack_idx >= old_len: + self._stack.extend([ContextStackObject() for _ in range(old_len)]) + self._stack[self._stack_idx].set_value(search_path, argparse_args) + self.apply() + + def apply(self): + if ( + self._last_search_path != self._stack[self._stack_idx].search_path + or self._last_argparse_args != self._stack[self._stack_idx].argparse_args + ): + # Expensive: + self._stack[self._stack_idx].apply() + self._last_search_path = self._stack[self._stack_idx].search_path + self._last_argparse_args = self._stack[self._stack_idx].argparse_args + + def pop(self): + self._stack_idx -= 1 + self._stack[self._stack_idx].apply() + + def replace(self, search_path: PathsType, argparse_args: Namespace | None) -> None: + self._stack[self._stack_idx].set_value(search_path, argparse_args) + self._stack[self._stack_idx].apply() + + +context_stack = ContextStack() + + +def stack_context( + pushing: bool, + search_path: PathsType = SEARCH_PATH, + argparse_args: Namespace | None = None, +) -> None: + if pushing: + # Fast + context_stack.push(search_path, argparse_args) + else: + # Slow + context_stack.pop() + + +# Default means "The configuration when there are no condarc files present". It is +# all the settings and defaults that are built in to the code and *not* the default +# value of search_path=SEARCH_PATH. It means search_path=(). +def stack_context_default( + pushing: bool, + argparse_args: Namespace | None = None, +) -> None: + return stack_context(pushing, search_path=(), argparse_args=argparse_args) + + +def replace_context( + pushing: bool | None = None, + search_path: Iterable[str] = SEARCH_PATH, + argparse_args: Namespace | None = None, +) -> None: + # pushing arg intentionally not used here, but kept for API compatibility + return context_stack.replace(search_path, argparse_args) + + +def replace_context_default( + pushing: bool | None = None, + argparse_args: Namespace | None = None, +) -> None: + # pushing arg intentionally not used here, but kept for API compatibility + return context_stack.replace(search_path=(), argparse_args=argparse_args) + + +# Tests that want to only declare 'I support the project-wide default for how to +# manage stacking of contexts'. Tests that are known to be careful with context +# can use `replace_context_default` which might be faster, though it should +# be a stated goal to set conda_tests_ctxt_mgmt_def_pol to replace_context_default +# and not to stack_context_default. +conda_tests_ctxt_mgmt_def_pol = replace_context_default + + +def env_name(prefix: PathType) -> PathType | str | None: + # counter part to `locate_prefix_by_name()` below + if not prefix: + return None + if paths_equal(prefix, context.root_prefix): + return ROOT_ENV_NAME + maybe_envs_dir, maybe_name = path_split(prefix) + for envs_dir in context.envs_dirs: + if paths_equal(envs_dir, maybe_envs_dir): + return maybe_name + return prefix + + +def locate_prefix_by_name(name: str, envs_dirs: PathsType | None = None) -> PathType: + """Find the location of a prefix given a conda env name. If the location does not exist, an + error is raised. If the prefix is the base or root env, the root prefix is returned. + """ + if not name: + raise ValueError("'name' cannot be empty.") + if name in RESERVED_ENV_NAMES: + return context.root_prefix + if envs_dirs is None: + envs_dirs = context.envs_dirs + for envs_dir in envs_dirs: + if not isdir(envs_dir): + continue + prefix = join(envs_dir, name) + if isdir(prefix): + return abspath(prefix) + + from ..exceptions import EnvironmentNameNotFound + + raise EnvironmentNameNotFound(name) + + +def validate_channels(channels: Iterator[str]) -> tuple[str, ...]: + """ + Validate if the given channel URLs are allowed based on the context's allowlist + and denylist configurations. + + :param channels: A list of channels (either URLs or names) to validate. + :raises ChannelNotAllowed: If any URL is not in the allowlist. + :raises ChannelDenied: If any URL is in the denylist. + """ + from ..exceptions import ChannelDenied, ChannelNotAllowed + from ..models.channel import Channel + + allowlist = [ + url + for channel in context.allowlist_channels + for url in Channel(channel).base_urls + ] + denylist = [ + url + for channel in context.denylist_channels + for url in Channel(channel).base_urls + ] + if allowlist or denylist: + for channel in map(Channel, channels): + for url in channel.base_urls: + if url in denylist: + raise ChannelDenied(channel) + if allowlist and url not in allowlist: + raise ChannelNotAllowed(channel) + + return tuple( + channel + for channel in dict.fromkeys(channels) + if Channel(channel).canonical_name != UNKNOWN_CHANNEL + ) + + +@deprecated( + "25.9", "26.3", addendum="Use PrefixData.validate_name() + PrefixData.from_name()" +) +def validate_prefix_name( + prefix_name: str, ctx: Context, allow_base: bool = True +) -> PathType: + """Run various validations to make sure prefix_name is valid""" + from ..exceptions import CondaValueError + + if PREFIX_NAME_DISALLOWED_CHARS.intersection(prefix_name): + raise CondaValueError( + dals( + f""" + Invalid environment name: {prefix_name!r} + Characters not allowed: {PREFIX_NAME_DISALLOWED_CHARS} + If you are specifying a path to an environment, the `-p` + flag should be used instead. + """ + ) + ) + + if prefix_name in RESERVED_ENV_NAMES: + if allow_base: + return ctx.root_prefix + else: + raise CondaValueError( + "Use of 'base' as environment name is not allowed here." + ) + + else: + from ..exceptions import EnvironmentNameNotFound + from ..gateways.disk.create import first_writable_envs_dir + + try: + return locate_prefix_by_name(prefix_name) + except EnvironmentNameNotFound: + return join(first_writable_envs_dir(), prefix_name) + + +def determine_target_prefix(ctx: Context, args: Namespace | None = None) -> PathType: + """Get the prefix to operate in. The prefix may not yet exist. + + Args: + ctx: the context of conda + args: the argparse args from the command line + + Returns: the prefix + Raises: CondaEnvironmentNotFoundError if the prefix is invalid + """ + argparse_args = args or ctx._argparse_args + try: + prefix_name = argparse_args.name + except AttributeError: + prefix_name = None + try: + prefix_path = argparse_args.prefix + except AttributeError: + prefix_path = None + + if prefix_name is not None and not prefix_name.strip(): # pragma: no cover + from ..exceptions import ArgumentError + + raise ArgumentError("Argument --name requires a value.") + + if prefix_path is not None and not prefix_path.strip(): # pragma: no cover + from ..exceptions import ArgumentError + + raise ArgumentError("Argument --prefix requires a value.") + + if prefix_name is None and prefix_path is None: + return ctx.default_prefix + elif prefix_path is not None: + return expand(prefix_path) + else: + from ..core.prefix_data import PrefixData + + return str(PrefixData.from_name(prefix_name).prefix_path) + + +@deprecated( + "25.9", "26.3", addendum="Use conda.gateways.disk.create.first_writable_envs_dir" +) +def _first_writable_envs_dir() -> PathType: + from conda.gateways.disk.create import first_writable_envs_dir + + return first_writable_envs_dir() + + +@deprecated( + "25.9", + "26.3", + addendum="Use `conda.base.context.context.plugins.raw_data` instead.", +) +def get_plugin_config_data( + data: dict[Path, dict[str, RawParameter]], +) -> dict[Path, dict[str, RawParameter]]: + from ..plugins.config import PluginConfig + + return PluginConfig(data).raw_data + + +@deprecated( + "25.9", + "26.3", + addendum="Use `conda.plugins.config.PluginConfig.add_plugin_setting` instead.", +) +def add_plugin_setting( + name: str, + parameter: Parameter, + aliases: tuple[str, ...] = (), +) -> None: + from ..plugins.config import PluginConfig + + return PluginConfig.add_plugin_setting(name, parameter, aliases) + + +@deprecated( + "25.9", + "26.3", + addendum="Use `conda.plugins.config.PluginConfig.remove_all_plugin_settings` instead.", +) +def remove_all_plugin_settings() -> None: + from ..plugins.config import PluginConfig + + return PluginConfig.remove_all_plugin_settings() + + +try: + context = Context((), None) +except ConfigurationLoadError as e: # pragma: no cover + print(repr(e), file=sys.stderr) + # Exception handler isn't loaded so use sys.exit + sys.exit(1) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ffb1380eaac4e96adba38d5a2fe72eea24bfa3aa --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/__init__.py @@ -0,0 +1,3 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from .main import main # NOQA diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/actions.py b/miniconda3/lib/python3.13/site-packages/conda/cli/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..b10dbec41e2946e5c14f583e35b7f334fa2d4c20 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/actions.py @@ -0,0 +1,62 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Collection of custom argparse actions. +""" + +from argparse import Action, _CountAction + +from ..common.constants import NULL +from ..deprecations import deprecated + + +class NullCountAction(_CountAction): + @staticmethod + @deprecated("26.9", "27.3") + def _ensure_value(namespace, name, value): + if getattr(namespace, name, NULL) in (NULL, None): + setattr(namespace, name, value) + return getattr(namespace, name) + + def __call__(self, parser, namespace, values, option_string=None): + count = getattr(namespace, self.dest, NULL) + if not isinstance(count, int): + count = 0 + setattr(namespace, self.dest, count + 1) + + +class ExtendConstAction(Action): + """ + A derivative of _AppendConstAction and Python 3.8's _ExtendAction + """ + + def __init__( + self, + option_strings, + dest, + const, + default=None, + type=None, + choices=None, + required=False, + help=None, + metavar=None, + ): + super().__init__( + option_strings=option_strings, + dest=dest, + nargs="*", + const=const, + default=default, + type=type, + choices=choices, + required=required, + help=help, + metavar=metavar, + ) + + def __call__(self, parser, namespace, values, option_string=None): + items = getattr(namespace, self.dest, None) + items = [] if items is None else items[:] + items.extend(values or [self.const]) + setattr(namespace, self.dest, items) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/common.py b/miniconda3/lib/python3.13/site-packages/conda/cli/common.py new file mode 100644 index 0000000000000000000000000000000000000000..2ce6d8092815c8e37508139f3d232c38f26dda89 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/common.py @@ -0,0 +1,359 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common utilities for conda command line tools.""" + +from __future__ import annotations + +import re +from logging import getLogger +from os.path import ( + dirname, + exists, + isdir, + isfile, + join, + normcase, +) +from typing import TYPE_CHECKING + +from ..auxlib.ish import dals +from ..base.constants import ( + CMD_LINE_SOURCE, + CONFIGURATION_SOURCES, + ENV_VARS_SOURCE, + EXPLICIT_MARKER, + PREFIX_MAGIC_FILE, +) +from ..base.context import context, env_name +from ..common.io import swallow_broken_pipe +from ..common.path import expand, paths_equal +from ..deprecations import deprecated +from ..exceptions import ( + DirectoryNotACondaEnvironmentError, + EnvironmentFileNotFound, + EnvironmentFileTypeMismatchError, + EnvironmentLocationNotFound, + EnvironmentNotWritableError, + InvalidSpec, + OperationNotAllowed, +) +from ..gateways.connection.session import CONDA_SESSION_SCHEMES +from ..gateways.disk.test import file_path_is_writable +from ..models.match_spec import MatchSpec +from ..reporters import render + +if TYPE_CHECKING: + from collections.abc import Iterable + +log = getLogger(__name__) + + +def is_active_prefix(prefix: str) -> bool: + """ + Determines whether the args we pass in are pointing to the active prefix. + Can be used a validation step to make sure operations are not being + performed on the active prefix. + """ + if context.active_prefix is None: + return False + return ( + paths_equal(prefix, context.active_prefix) + # normcasing our prefix check for Windows, for case insensitivity + or normcase(prefix) == normcase(env_name(context.active_prefix)) + ) + + +@deprecated( + "26.3", + "26.9", + addendum="Use `spec = str(MatchSpec(arg))` instead", +) +def arg2spec(arg: str, update: bool = False) -> str: + try: + spec = MatchSpec(arg) + except: + from ..exceptions import CondaValueError + + raise CondaValueError(f"invalid package specification: {arg}") + + name = spec.name + if not spec._is_simple() and update: + from ..exceptions import CondaValueError + + raise CondaValueError( + "version specifications not allowed with 'update'; use\n" + f" conda update {name:<{len(arg)}} or\n" + f" conda install {arg:<{len(name)}}" + ) + + return str(spec) + + +@deprecated.argument("26.3", "26.9", "json") +def specs_from_args(args: Iterable[str]) -> list[str]: + return [str(MatchSpec(arg)) for arg in args] + + +spec_pat = re.compile( + r""" + (?P[^=<>!\s]+) # package name + \s* # ignore spaces + ( + (?P=[^=]+(=[^=]+)?) # conda constraint + | + (?P(?:[=!]=|[><]=?|~=).+) # new pip-style constraints + )?$ + """, + re.VERBOSE, +) + + +def strip_comment(line: str) -> str: + return line.split("#")[0].rstrip() + + +def spec_from_line(line: str) -> str: + m = spec_pat.match(strip_comment(line)) + if m is None: + return None + name, cc, pc = (m.group("name").lower(), m.group("cc"), m.group("pc")) + if cc: + return name + cc.replace("=", " ") + elif pc: + if pc.startswith("~= "): + if pc.count("~=") > 1: + raise InvalidSpec( + f"Overly complex 'Compatible release' spec not handled {line}." + ) + if not pc.count("."): + raise InvalidSpec(f"No '.' in 'Compatible release' version {line}") + ver = pc.replace("~= ", "") + ver2 = ".".join(ver.split(".")[:-1]) + ".*" + return name + " >=" + ver + ",==" + ver2 + else: + return name + " " + pc.replace(" ", "") + else: + return name + + +@deprecated.argument("26.3", "26.9", "json") +def specs_from_url(url: str) -> list[str]: + from ..gateways.connection.download import TmpDownload + + explicit = False + with TmpDownload(url, verbose=False) as path: + specs = [] + try: + for line in open(path): + line = line.strip() + if not line or line.startswith("#"): + continue + if line == EXPLICIT_MARKER: + explicit = True + if explicit: + specs.append(line) + continue + spec = spec_from_line(line) + if spec is None: + from ..exceptions import CondaValueError + + raise CondaValueError(f"could not parse '{line}' in: {url}") + specs.append(spec) + except OSError as e: + from ..exceptions import CondaFileIOError + + raise CondaFileIOError(path, e) + return specs + + +def names_in_specs(names, specs): + return any(spec.split()[0] in names for spec in specs) + + +def disp_features(features): + if features: + return "[{}]".format(" ".join(features)) + else: + return "" + + +@swallow_broken_pipe +def stdout_json(d): + render(d) + + +def stdout_json_success(success=True, **kwargs): + result = {"success": success} + actions = kwargs.pop("actions", None) + if actions: + if "LINK" in actions: + actions["LINK"] = [prec.dist_fields_dump() for prec in actions["LINK"]] + if "UNLINK" in actions: + actions["UNLINK"] = [prec.dist_fields_dump() for prec in actions["UNLINK"]] + result["actions"] = actions + result.update(kwargs) + stdout_json(result) + + +def check_non_admin(): + from ..common._os import is_admin + + if not context.non_admin_enabled and not is_admin(): + from ..exceptions import OperationNotAllowed + + raise OperationNotAllowed( + dals( + """ + The create, install, update, and remove operations have been disabled + on your system for non-privileged users. + """ + ) + ) + + +@deprecated("25.9", "26.3", addendum="Use PrefixData.assert_environment()") +def validate_prefix(prefix) -> str: + """Verifies the prefix is a valid conda environment. + + :raises EnvironmentLocationNotFound: Non-existent path or not a directory. + :raises DirectoryNotACondaEnvironmentError: Directory is not a conda environment. + :returns: Valid prefix. + :rtype: str + """ + if isdir(prefix): + if not isfile(join(prefix, PREFIX_MAGIC_FILE)): + raise DirectoryNotACondaEnvironmentError(prefix) + else: + raise EnvironmentLocationNotFound(prefix) + + return prefix + + +@deprecated("25.9", "26.3", addendum="Use PrefixData.assert_writable()") +def validate_prefix_is_writable(prefix: str) -> str: + """Verifies the environment directory is writable by trying to access + the conda-meta/history file. If this file is not writable then we assume + the whole prefix is not writable and raise an exception. + + :raises EnvironmentNotWritableError: Conda does not have permission to write to the prefix + :returns: Valid prefix. + :rtype: str + """ + test_path = join(prefix, PREFIX_MAGIC_FILE) + if isdir(dirname(test_path)) and file_path_is_writable(test_path): + return prefix + raise EnvironmentNotWritableError(prefix) + + +def validate_subdir_config(): + """Validates that the configured subdir is ok. A subdir that is different from + the native system is only allowed if it comes from the global configuration, or + from an environment variable. + + :raises OperationNotAllowed: Active environment is not allowed to request + non-native platform packages + """ + if context.subdir != context._native_subdir(): + # We will only allow a different subdir if it's specified by global + # configuration, environment variable or command line argument. IOW, + # prevent a non-base env configured for a non-native subdir from leaking + # its subdir to a newer env. + context_sources = context.collect_all() + if context_sources.get(CMD_LINE_SOURCE, {}).get("subdir") == context.subdir: + pass # this is ok + elif context_sources.get(ENV_VARS_SOURCE, {}).get("subdir") == context.subdir: + pass # this is ok too + # config does not come from envvars or cmd_line, it must be a file + # that's ok as long as it's a base env or a global file + elif not paths_equal(context.active_prefix, context.root_prefix): + # this is only ok as long as it's NOT base environment + active_env_config = next( + ( + config + for path, config in context_sources.items() + if path not in CONFIGURATION_SOURCES + and paths_equal(context.active_prefix, path.parent) + ), + {}, + ) + if active_env_config.get("subdir") == context.subdir: + # In practice this never happens; the subdir info is not even + # loaded from the active env for conda create :shrug: + msg = dals( + f""" + Active environment configuration ({context.active_prefix}) is + implicitly requesting a non-native platform ({context.subdir}). + Please deactivate first or explicitly request the platform via + the --platform=[value] command line flag. + """ + ) + raise OperationNotAllowed(msg) + + +def print_activate(env_name_or_prefix): + if not context.quiet and not context.json: + if " " in env_name_or_prefix: + env_name_or_prefix = f'"{env_name_or_prefix}"' + message = dals( + f""" + # + # To activate this environment, use + # + # $ conda activate {env_name_or_prefix} + # + # To deactivate an active environment, use + # + # $ conda deactivate + """ + ) + print(message) # TODO: use logger + + +def validate_environment_files_consistency(files: list[str]) -> None: + """Validates that all the provided environment files are of the same format type. + + This function checks if all provided environment files are of the same format type + using the conda plugin system's environment specifiers. It prevents mixing different + environment file formats (e.g., YAML, explicit package lists, requirements.txt). + + :raises EnvironmentFileTypeMismatchError: When files with different formats are found + """ + if not files or len(files) <= 1: + return # Nothing to validate if there are 0 or 1 files + + # Get types for all files using the plugin manager + file_types = { + file: context.plugin_manager.get_environment_specifier(file).name + for file in files + } + # If there's more than one unique type, raise an error + if len(set(file_types.values())) > 1: + raise EnvironmentFileTypeMismatchError(file_types) + + +def validate_file_exists(filename: str): + """ + Validate the existence of an environment file. + + This function checks if the given ``filename`` exists as an environment file. + If the `filename` has a URL scheme supported by ``CONDA_SESSION_SCHEMES``, + it assumes the file is accessible and returns without further validation. + Otherwise, it expands the given path and verifies its existence. If the file + does not exist, an ``EnvironmentFileNotFound`` exception is raised. + + Parameters: + filename (str): The path or URL of the environment file to validate. + + Raises: + EnvironmentFileNotFound: If the file does not exist and is not a valid URL. + """ + url_scheme = filename.split("://", 1)[0] + if url_scheme == "file": + filename = expand(filename.split("://", 1)[-1]) + elif url_scheme not in CONDA_SESSION_SCHEMES: + filename = expand(filename) + else: + return + + if not exists(filename): + raise EnvironmentFileNotFound(filename=filename) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/conda_argparse.py b/miniconda3/lib/python3.13/site-packages/conda/cli/conda_argparse.py new file mode 100644 index 0000000000000000000000000000000000000000..0901361c0855542341c7ebcf2896be99651f5f33 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/conda_argparse.py @@ -0,0 +1,373 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda command line interface parsers.""" + +from __future__ import annotations + +import argparse +import os +import sys +from argparse import ( + SUPPRESS, + RawDescriptionHelpFormatter, +) +from argparse import ArgumentParser as ArgumentParserBase +from importlib import import_module +from logging import getLogger +from subprocess import Popen + +from .. import __version__ +from ..auxlib.ish import dals +from ..base.context import context, sys_rc_path, user_rc_path +from ..common.compat import isiterable, on_win +from ..common.constants import NULL +from ..deprecations import deprecated +from .actions import ExtendConstAction, NullCountAction # noqa: F401 +from .find_commands import find_commands, find_executable +from .helpers import ( # noqa: F401 + add_output_and_prompt_options, + add_parser_channels, + add_parser_create_install_update, + add_parser_default_packages, + add_parser_help, + add_parser_json, + add_parser_known, + add_parser_networking, + add_parser_package_install_options, + add_parser_platform, + add_parser_prefix, + add_parser_prefix_to_group, + add_parser_prune, + add_parser_pscheck, + add_parser_show_channel_urls, + add_parser_solver, + add_parser_solver_mode, + add_parser_update_modifiers, + add_parser_verbose, +) +from .main_clean import configure_parser as configure_parser_clean +from .main_commands import configure_parser as configure_parser_commands +from .main_compare import configure_parser as configure_parser_compare +from .main_config import configure_parser as configure_parser_config +from .main_create import configure_parser as configure_parser_create +from .main_env import configure_parser as configure_parser_env +from .main_export import configure_parser as configure_parser_export +from .main_info import configure_parser as configure_parser_info +from .main_init import configure_parser as configure_parser_init +from .main_install import configure_parser as configure_parser_install +from .main_list import configure_parser as configure_parser_list +from .main_mock_activate import configure_parser as configure_parser_activate +from .main_mock_deactivate import configure_parser as configure_parser_deactivate +from .main_notices import configure_parser as configure_parser_notices +from .main_package import configure_parser as configure_parser_package +from .main_remove import configure_parser as configure_parser_remove +from .main_rename import configure_parser as configure_parser_rename +from .main_run import configure_parser as configure_parser_run +from .main_search import configure_parser as configure_parser_search +from .main_update import configure_parser as configure_parser_update + +log = getLogger(__name__) + +escaped_user_rc_path = user_rc_path.replace("%", "%%") +escaped_sys_rc_path = sys_rc_path.replace("%", "%%") + +BUILTIN_COMMANDS = { + "activate", # Mock entry for shell command + "clean", + "commands", + "compare", + "config", + "create", + "deactivate", # Mock entry for shell command + "env", + "export", + "info", + "init", + "install", + "list", + "notices", + "package", + "remove", + "rename", + "run", + "search", + "uninstall", # remove alias + "update", + "upgrade", # update alias +} +"""List of built-in commands; these cannot be overridden by plugin subcommands.""" + + +def generate_pre_parser(**kwargs) -> ArgumentParser: + pre_parser = ArgumentParser( + description="conda is a tool for managing and deploying applications," + " environments and packages.", + **kwargs, + ) + + add_parser_verbose(pre_parser) + pre_parser.add_argument( + "--json", + action="store_true", + default=NULL, + help=SUPPRESS, + ) + pre_parser.add_argument( + "--no-plugins", + action="store_true", + default=NULL, + help="Disable all plugins that are not built into conda.", + ) + + return pre_parser + + +def generate_parser(**kwargs) -> ArgumentParser: + parser = generate_pre_parser(**kwargs) + + parser.add_argument( + "-V", + "--version", + action="version", + version=f"conda {__version__}", + help="Show the conda version number and exit.", + ) + + sub_parsers = parser.add_subparsers( + metavar="COMMAND", + title="commands", + description="The following built-in and plugins subcommands are available.", + dest="cmd", + action=_GreedySubParsersAction, + required=True, + ) + + configure_parser_activate(sub_parsers) + configure_parser_clean(sub_parsers) + configure_parser_commands(sub_parsers) + configure_parser_compare(sub_parsers) + configure_parser_config(sub_parsers) + configure_parser_create(sub_parsers) + configure_parser_deactivate(sub_parsers) + configure_parser_env(sub_parsers) + configure_parser_export(sub_parsers) + configure_parser_info(sub_parsers) + configure_parser_init(sub_parsers) + configure_parser_install(sub_parsers) + configure_parser_list(sub_parsers) + configure_parser_notices(sub_parsers) + configure_parser_package(sub_parsers) + configure_parser_plugins(sub_parsers) + configure_parser_remove(sub_parsers, aliases=["uninstall"]) + configure_parser_rename(sub_parsers) + configure_parser_run(sub_parsers) + configure_parser_search(sub_parsers) + configure_parser_update(sub_parsers, aliases=["upgrade"]) + + return parser + + +def do_call(args: argparse.Namespace, parser: ArgumentParser): + """ + Serves as the primary entry point for commands referred to in this file and for + all registered plugin subcommands. + """ + # let's see if during the parsing phase it was discovered that the + # called command was in fact a plugin subcommand + if plugin_subcommand := getattr(args, "_plugin_subcommand", None): + # pass on the rest of the plugin specific args or fall back to + # the whole discovered arguments + context.plugin_manager.invoke_pre_commands(plugin_subcommand.name) + result = plugin_subcommand.action(getattr(args, "_args", args)) + context.plugin_manager.invoke_post_commands(plugin_subcommand.name) + elif name := getattr(args, "_executable", None): + # run the subcommand from executables; legacy path + deprecated.topic( + "23.3", + "26.3", + topic="Loading conda subcommands via executables", + addendum="Use the plugin system instead.", + ) + executable = find_executable(f"conda-{name}") + if not executable: + from ..exceptions import CommandNotFoundError + + raise CommandNotFoundError(name) + return _exec([executable, *args._args], os.environ) + else: + # let's call the subcommand the old-fashioned way via the assigned func.. + module_name, func_name = args.func.rsplit(".", 1) + # func_name should always be 'execute' + module = import_module(module_name) + command = module_name.split(".")[-1].replace("main_", "") + + context.plugin_manager.invoke_pre_commands(command) + result = getattr(module, func_name)(args, parser) + context.plugin_manager.invoke_post_commands(command) + return result + + +def find_builtin_commands(parser): + # ArgumentParser doesn't have an API for getting back what subparsers + # exist, so we need to use internal properties to do so. + return tuple(parser._subparsers._group_actions[0].choices.keys()) + + +class ArgumentParser(ArgumentParserBase): + def __init__(self, *args, add_help=True, **kwargs): + kwargs.setdefault("formatter_class", RawDescriptionHelpFormatter) + super().__init__(*args, add_help=False, **kwargs) + + if add_help: + add_parser_help(self) + + def _check_value(self, action, value): + # For our greedy subparsers, sort the choices by their repr for stable output + if isinstance(action, _GreedySubParsersAction) and isinstance( + action.choices, dict + ): + action.choices = dict(sorted(action.choices.items())) + # extend to properly handle when we accept multiple choices and the default is a list + if action.choices is not None and isiterable(value): + for element in value: + super()._check_value(action, element) + else: + super()._check_value(action, value) + + def parse_args(self, *args, override_args=None, **kwargs): + parsed_args = super().parse_args(*args, **kwargs) + for name, value in (override_args or {}).items(): + if value is not NULL and getattr(parsed_args, name, NULL) is NULL: + setattr(parsed_args, name, value) + return parsed_args + + +class _GreedySubParsersAction(argparse._SubParsersAction): + """A custom subparser action to conditionally act as a greedy consumer. + + This is a workaround since argparse.REMAINDER does not work as expected, + see https://github.com/python/cpython/issues/61252. + """ + + def __call__(self, parser, namespace, values, option_string=None): + super().__call__(parser, namespace, values, option_string) + + parser = self._name_parser_map[values[0]] + + # if the parser has a greedy=True attribute we want to consume all arguments + # i.e. all unknown args should be passed to the subcommand as is + if getattr(parser, "greedy", False): + try: + unknown = getattr(namespace, argparse._UNRECOGNIZED_ARGS_ATTR) + delattr(namespace, argparse._UNRECOGNIZED_ARGS_ATTR) + except AttributeError: + unknown = () + + # underscore prefixed indicating this is not a normal argparse argument + namespace._args = tuple(unknown) + + def _get_subactions(self): + """Sort actions for subcommands to appear alphabetically in help blurb.""" + return sorted(self._choices_actions, key=lambda action: action.dest) + + +def _exec(executable_args, env_vars): + return (_exec_win if on_win else _exec_unix)(executable_args, env_vars) + + +def _exec_win(executable_args, env_vars): + p = Popen(executable_args, env=env_vars) + try: + p.communicate() + except KeyboardInterrupt: + p.wait() + finally: + sys.exit(p.returncode) + + +def _exec_unix(executable_args, env_vars): + os.execvpe(executable_args[0], executable_args, env_vars) + + +def configure_parser_plugins(sub_parsers) -> None: + """ + For each of the provided plugin-based subcommands, we'll create + a new subparser for an improved help printout and calling the + :meth:`~conda.plugins.types.CondaSubcommand.configure_parser` + with the newly created subcommand specific argument parser. + """ + plugin_subcommands = context.plugin_manager.get_subcommands() + for name, plugin_subcommand in plugin_subcommands.items(): + # if the name of the plugin-based subcommand overlaps a built-in + # subcommand, we print an error + if name in BUILTIN_COMMANDS: + log.error( + dals( + f""" + The plugin '{name}' is trying to override the built-in command + with the same name, which is not allowed. + + Please uninstall the plugin to stop seeing this error message. + """ + ) + ) + continue + + parser = sub_parsers.add_parser( + name, + description=plugin_subcommand.summary, + help=plugin_subcommand.summary, + add_help=False, # defer to subcommand's help processing + ) + + # case 1: plugin extends the parser + if plugin_subcommand.configure_parser: + plugin_subcommand.configure_parser(parser) + + # attempt to add standard help processing, will fail if plugin defines their own + try: + add_parser_help(parser) + except argparse.ArgumentError: + pass + + # case 2: plugin has their own parser, see _GreedySubParsersAction + else: + parser.greedy = True + + # underscore prefixed indicating this is not a normal argparse argument + parser.set_defaults(_plugin_subcommand=plugin_subcommand) + + if context.no_plugins: + return + + # Ignore the legacy `conda-env` entrypoints since we already register `env` + # as a subcommand in `generate_parser` above + legacy = set(find_commands()).difference(plugin_subcommands) - {"env"} + + for name in legacy: + # if the name of the plugin-based subcommand overlaps a built-in + # subcommand, we print an error + if name in BUILTIN_COMMANDS: + log.error( + dals( + f""" + The (legacy) plugin '{name}' is trying to override the built-in command + with the same name, which is not allowed. + + Please uninstall the plugin to stop seeing this error message. + """ + ) + ) + continue + + parser = sub_parsers.add_parser( + name, + description=f"See `conda {name} --help`.", + help=f"See `conda {name} --help`.", + add_help=False, # defer to subcommand's help processing + ) + + # case 3: legacy plugins are always greedy + parser.greedy = True + + parser.set_defaults(_executable=name) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/condarc.py b/miniconda3/lib/python3.13/site-packages/conda/cli/condarc.py new file mode 100644 index 0000000000000000000000000000000000000000..2e01a27c206c58e3be462272ada6857b0394e6f1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/condarc.py @@ -0,0 +1,584 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Configuration file manipulation utilities for conda. + +This module provides classes and functions for working with conda configuration +files (.condarc), including reading, writing, and validating configuration keys. +""" + +from __future__ import annotations + +import os +import sys +from collections.abc import Sequence +from functools import cached_property +from logging import getLogger +from pathlib import Path +from typing import TYPE_CHECKING + +from ..common.configuration import DEFAULT_CONDARC_FILENAME + +if TYPE_CHECKING: + from collections.abc import Callable + from typing import Any + + from ..common.configuration import Configuration + +log = getLogger(__name__) + + +def _register_enum_representers() -> None: + """Register YAML representers for conda enum types. + + This function registers custom YAML representers for all conda enum types + to ensure they are serialized as strings rather than complex objects. + + This is called once at module load time to ensure representers are available + before any YAML serialization occurs. + """ + from ruamel.yaml.representer import RoundTripRepresenter + + from ..base.constants import ( + ChannelPriority, + DepsModifier, + PathConflict, + SafetyChecks, + SatSolverChoice, + UpdateModifier, + ) + + def enum_representer(dumper, data): + return dumper.represent_str(str(data)) + + # Register each enum type individually (base Enum class registration doesn't work) + for enum_class in ( + SafetyChecks, + PathConflict, + DepsModifier, + UpdateModifier, + ChannelPriority, + SatSolverChoice, + ): + RoundTripRepresenter.add_representer(enum_class, enum_representer) + + +# Register enum representers once at module load time +_register_enum_representers() + + +class _MissingSentinel: + """Sentinel value to indicate a missing configuration key. + + This is used by ConfigurationFile.get_key() to distinguish between a key that + doesn't exist and a key that exists but has a None value. + """ + + def __repr__(self): + return "" + + def __bool__(self): + return False + + def __eq__(self, other): + return isinstance(other, _MissingSentinel) + + def __hash__(self): + return hash(_MissingSentinel) + + +MISSING = _MissingSentinel() + + +class ParameterTypeGroups: + """ + Groups configuration parameters by their parameter type. + + Organizes configuration parameters from a Configuration instance into sequence + and map parameters, handling both regular and plugin parameters separately. + + This is primarily used by ConfigurationFile to efficiently determine which operations + are valid for different configuration keys. + """ + + def __init__(self, context: Configuration) -> None: + """ + Initialize ParameterTypeGroups by grouping parameters by type. + + :param context: Configuration instance containing configuration parameters. + """ + from ..common.iterators import groupby_to_dict as groupby + + self._grouped_parameter = groupby( + lambda p: context.describe_parameter(p)["parameter_type"], + context.list_parameters(), + ) + + # Handle plugin parameters if the context has a plugins attribute + if hasattr(context, "plugins"): + self._plugin_grouped_parameters = groupby( + lambda p: context.plugins.describe_parameter(p)["parameter_type"], + context.plugins.list_parameters(), + ) + else: + self._plugin_grouped_parameters = {} + + @cached_property + def sequence_parameters(self) -> list[str]: + """List of sequence parameter names.""" + return self._grouped_parameter.get("sequence", []) + + @cached_property + def plugin_sequence_parameters(self) -> list[str]: + """List of plugin sequence parameter names.""" + return self._plugin_grouped_parameters.get("sequence", []) + + @cached_property + def map_parameters(self) -> list[str]: + """List of map parameter names.""" + return self._grouped_parameter.get("map", []) + + @cached_property + def plugin_map_parameters(self) -> list[str]: + """List of plugin map parameter names.""" + return self._plugin_grouped_parameters.get("map", []) + + +def validate_provided_parameters( + parameters: Sequence[str], + plugin_parameters: Sequence[str], + context: Configuration, +) -> None: + """ + Validate that provided parameters exist in the configuration context. + + Compares the provided parameters with the available parameters in the context + and raises an error if any are invalid. + + :param parameters: Regular parameter names to validate. + :param plugin_parameters: Plugin parameter names to validate. + :param context: Configuration instance containing available parameters. + :raises ArgumentError: If any provided parameters are not valid. + """ + from ..common.io import dashlist + from ..exceptions import ArgumentError + + all_names = context.list_parameters(aliases=True) + + # Handle plugin parameters if the context has a plugins attribute + if hasattr(context, "plugins"): + all_plugin_names = context.plugins.list_parameters() + else: + all_plugin_names = [] + + not_params = set(parameters) - set(all_names) + not_plugin_params = set(plugin_parameters) - set(all_plugin_names) + + if not_params or not_plugin_params: + not_plugin_params = {f"plugins.{name}" for name in not_plugin_params} + error_params = not_params | not_plugin_params + raise ArgumentError( + f"Invalid configuration parameters: {dashlist(error_params)}" + ) + + +class ConfigurationFile: + """ + Represents and manipulates a conda configuration (.condarc) file. + + Provides methods to read, write, and modify configuration files while + validating keys and maintaining proper structure. + + Can be used as a context manager for atomic edits: + + with ConfigurationFile.from_user_condarc() as config: + config.set_key("channels", ["conda-forge"]) + config.add("channels", "defaults") + # File is automatically written when exiting the context + """ + + def __init__( + self, + path: str | os.PathLike[str] | Path | None = None, + context: Configuration | None = None, + content: dict[str, Any] | None = None, + warning_handler: Callable[[str], None] | None = None, + ) -> None: + self._path = path + self._content = content + + self._context = context + self._context_params: ParameterTypeGroups | None = None + + self.warning_handler = warning_handler or (lambda msg: None) + + @classmethod + def from_user_condarc( + cls, context: Configuration | None = None + ) -> ConfigurationFile: + """ + Create a ConfigurationFile instance for the default user .condarc file. + + :param context: Optional Configuration instance. If None, uses the global context. + :returns: ConfigurationFile instance configured for the user's .condarc file. + """ + from ..base.context import user_rc_path + + return cls(path=user_rc_path, context=context) + + @classmethod + def from_system_condarc( + cls, context: Configuration | None = None + ) -> ConfigurationFile: + """ + Create a ConfigurationFile instance for the system .condarc file. + + :param context: Optional Configuration instance. If None, uses the global context. + :returns: ConfigurationFile instance configured for the system .condarc file. + """ + from ..base.context import sys_rc_path + + return cls(path=sys_rc_path, context=context) + + @classmethod + def from_env_condarc( + cls, + prefix: str | os.PathLike[str] | Path | None = None, + context: Configuration | None = None, + ) -> ConfigurationFile: + """ + Create a ConfigurationFile instance for an environment-specific .condarc file. + + Environment-specific .condarc files are located at `{prefix}/.condarc` and allow + per-environment configuration overrides. + + :param prefix: Path to the conda environment. If None, uses $CONDA_PREFIX or sys.prefix. + :param context: Optional Configuration instance. If None, uses the global context. + :returns: ConfigurationFile instance configured for the environment's .condarc file. + """ + if prefix is None: + prefix = os.environ.get("CONDA_PREFIX", sys.prefix) + + return cls(path=Path(prefix) / DEFAULT_CONDARC_FILENAME, context=context) + + def __enter__(self) -> ConfigurationFile: + """Enter the context manager.""" + return self + + def __exit__(self, exc_type, exc_val, exc_tb) -> None: + """Exit the context manager and write changes if no exception occurred.""" + if exc_type is None: + self.write() + + @property + def path(self) -> str | os.PathLike[str] | Path: + """ + Get the path to the configuration file. + + :returns: Path to the configuration file. + :raises AttributeError: If path has not been set. + """ + if self._path is None: + raise AttributeError("Configuration file path has not been set") + + return self._path + + @path.setter + def path(self, path: str | os.PathLike[str] | Path) -> None: + """ + Set the path to the configuration file. + + :param path: Path to the configuration file. + """ + self._path = path + + @property + def context(self) -> Configuration: + """ + Get the context instance. + + If no context was provided during initialization, falls back to the global + conda context singleton. This lazy import is necessary to avoid circular + dependencies at module load time. + + :returns: Configuration instance. + """ + if self._context is None: + # Import the global context singleton + # This is imported lazily to avoid circular import issues + from ..base.context import context + + self._context = context + + return self._context + + @property + def context_params(self) -> ParameterTypeGroups: + if self._context_params is None: + self._context_params = ParameterTypeGroups(self.context) + return self._context_params + + @property + def content(self) -> dict[str, Any]: + """ + Get the configuration content, reading from file if needed. + + :returns: Dictionary containing configuration content. + """ + if self._content is None: + self.read() + + return self._content + + def read(self, path: str | os.PathLike[str] | Path | None = None) -> dict[str, Any]: + """ + Read configuration content from file. + + :param path: Optional path to read from. If None, uses the instance path. + :returns: Dictionary containing configuration content. + """ + from ..common.serialize import yaml + + path = Path(path or self._path) + + try: + self._content = yaml.read(path=path) or {} + except FileNotFoundError: + self._content = {} + + return self._content + + def write(self, path: str | os.PathLike[str] | Path | None = None) -> None: + """ + Write configuration content to file. + + :param path: Optional path to write to. If None, uses the instance path. + :raises CondaError: If the file cannot be written. + """ + from .. import CondaError + from ..common.serialize import yaml + + path: Path = Path(path or self._path) + try: + yaml.write(self.content, path=path) + except OSError as e: + raise CondaError(f"Cannot write to condarc file at {path}\nCaused by {e!r}") + + def key_exists(self, key: str) -> bool: + """ + Check if a configuration key is valid. + + :param key: Configuration key to check. + :returns: True if the key is valid, False otherwise. + """ + first, *rest = key.split(".") + + # Handle plugin parameters if the context has a plugins attribute + if ( + first == "plugins" + and len(rest) > 0 + and hasattr(self.context, "plugins") + and rest[0] in self.context.plugins.list_parameters() + ): + return True + + if first not in self.context.list_parameters(): + exists = bool(self.context.name_for_alias(first)) + if not exists: + self.warning_handler(f"Unknown key: {key!r}") + return exists + + return True + + def add(self, key: str, item: Any, prepend: bool = False) -> None: + """ + Add an item to a sequence configuration parameter. + + :param key: Configuration key name (may contain dots for nested keys). + :param item: Item to add to the sequence. + :param prepend: If True, add to the beginning; if False, add to the end. + :raises CondaValueError: If the key is not a known sequence parameter. + :raises CouldntParseError: If the key should be a list but isn't. + """ + from ..exceptions import CondaValueError, CouldntParseError + + key, subkey = key.split(".", 1) if "." in key else (key, None) + + if key in self.context_params.sequence_parameters: + arglist = self.content.setdefault(key, []) + elif ( + key == "plugins" + and subkey in self.context_params.plugin_sequence_parameters + ): + arglist = self.content.setdefault("plugins", {}).setdefault(subkey, []) + elif key in self.context_params.map_parameters: + arglist = self.content.setdefault(key, {}).setdefault(subkey, []) + elif key in self.context_params.plugin_map_parameters: + arglist = self.content.setdefault("plugins", {}).setdefault(subkey, {}) + else: + raise CondaValueError(f"Key '{key}' is not a known sequence parameter.") + + if not (isinstance(arglist, Sequence) and not isinstance(arglist, str)): + bad = self.content[key].__class__.__name__ + raise CouldntParseError(f"key {key!r} should be a list, not {bad}.") + + if item in arglist: + # Right now, all list keys should not contain duplicates + location = "top" if prepend else "bottom" + message_key = key + "." + subkey if subkey is not None else key + message = f"Warning: '{item}' already in '{message_key}' list, moving to the {location}" + + if subkey is None: + arglist = self.content[key] = [p for p in arglist if p != item] + else: + arglist = self.content[key][subkey] = [p for p in arglist if p != item] + + self.warning_handler(msg=message) + + arglist.insert(0 if prepend else len(arglist), item) + + def get_key( + self, + key: str, + ) -> tuple[str, Any | _MissingSentinel]: + """ + Get a configuration value by key. + + :param key: Configuration key name (may contain dots for nested keys). + :returns: Tuple of (key, value) or (key, MISSING) if key doesn't exist. + """ + key_parts = key.split(".") + + if not self.key_exists(key): + return key, MISSING + + if alias := self.context.name_for_alias(key): + key = alias + key_parts = alias.split(".") + + sub_config = self.content + try: + for part in key_parts: + sub_config = sub_config[part] + except KeyError: + pass + else: + return key, sub_config + + return key, MISSING + + def set_key(self, key: str, item: Any) -> None: + """ + Set a configuration value for a primitive or map parameter. + + :param key: Configuration key name (may contain dots for nested keys). + :param item: Value to set. + :raises CondaKeyError: If the key is unknown or invalid. + """ + from ..exceptions import CondaKeyError + + if not self.key_exists(key): + raise CondaKeyError(key, "unknown parameter") + + if aliased := self.context.name_for_alias(key): + log.warning( + "Key %s is an alias of %s; setting value with latter", key, aliased + ) + key = aliased + + first, *rest = key.split(".") + + if first == "plugins" and hasattr(self.context, "plugins"): + base_context = self.context.plugins + base_config = self.content.setdefault("plugins", {}) + parameter_name, *rest = rest + else: + base_context = self.context + base_config = self.content + parameter_name = first + + parameter_type = base_context.describe_parameter(parameter_name)[ + "parameter_type" + ] + + if parameter_type == "primitive" and len(rest) == 0: + base_config[parameter_name] = base_context.typify_parameter( + parameter_name, item, "--set parameter" + ) + + elif parameter_type == "map" and len(rest) == 1: + base_config.setdefault(parameter_name, {})[rest[0]] = item + + else: + raise CondaKeyError(key, "invalid parameter") + + def remove_item(self, key: str, item: Any) -> None: + """ + Remove an item from a sequence configuration parameter. + + :param key: Configuration key name. + :param item: Item to remove from the sequence. + :raises CondaKeyError: If the key is unknown, undefined, or the item is not present. + """ + from ..exceptions import CondaKeyError + + first, *rest = key.split(".") + + if first == "plugins" and hasattr(self.context, "plugins"): + base_context = self.context.plugins + base_config = self.content.setdefault("plugins", {}) + parameter_name = rest[0] + rest = [] + else: + base_context = self.context + base_config = self.content + parameter_name = first + + try: + parameter_type = base_context.describe_parameter(parameter_name)[ + "parameter_type" + ] + except KeyError: + # KeyError: key_parts[0] is an unknown parameter + raise CondaKeyError(key, "unknown parameter") + + if parameter_type == "sequence" and len(rest) == 0: + if parameter_name not in base_config: + if parameter_name != "channels": + raise CondaKeyError(key, "undefined in config") + self.content[parameter_name] = ["defaults"] + + if item not in base_config[parameter_name]: + raise CondaKeyError( + parameter_name, f"value {item!r} not present in config" + ) + base_config[parameter_name] = [ + i for i in base_config[parameter_name] if i != item + ] + else: + raise CondaKeyError(key, "invalid parameter") + + def remove_key(self, key: str) -> None: + """ + Remove a configuration key entirely. + + :param key: Configuration key name (may contain dots for nested keys). + :raises CondaKeyError: If the key is undefined in the config. + """ + from ..exceptions import CondaKeyError + + key_parts = key.split(".") + + sub_config = self.content + try: + for part in key_parts[:-1]: + sub_config = sub_config[part] + del sub_config[key_parts[-1]] + except KeyError: + # KeyError: part not found, nothing to remove, but maybe user passed an alias? + if alias := self.context.name_for_alias(key): + try: + return self.remove_key(alias) + except CondaKeyError: + pass # raise with originally passed key + raise CondaKeyError(key, "undefined in config") diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/find_commands.py b/miniconda3/lib/python3.13/site-packages/conda/cli/find_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..d99923bccaeb26bd0a0aa527017b8c470a8586f3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/find_commands.py @@ -0,0 +1,83 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Utilities for finding executables and `conda-*` commands.""" + +import os +import re +import sys +import sysconfig +from functools import cache +from os.path import basename, expanduser, isfile, join + +from ..common.compat import on_win + + +def find_executable(executable, include_others=True): + # backwards compatibility + global dir_paths + + if include_others: + from ..utils import sys_prefix_unfollowed + + prefixes = [sys_prefix_unfollowed()] + if sys.prefix != prefixes[0]: + prefixes.append(sys.prefix) + dir_paths = [join(p, basename(sysconfig.get_path("scripts"))) for p in prefixes] + # Is this still needed? + if on_win: + dir_paths.append("C:\\cygwin\\bin") + else: + dir_paths = [] + + dir_paths.extend(os.environ.get("PATH", "").split(os.pathsep)) + + for dir_path in dir_paths: + if on_win: + for ext in (".exe", ".bat", ""): + path = join(dir_path, executable + ext) + if isfile(path): + return path + else: + path = join(dir_path, executable) + if isfile(expanduser(path)): + return expanduser(path) + return None + + +@cache +def find_commands(include_others=True): + if include_others: + from ..utils import sys_prefix_unfollowed + + prefixes = [sys_prefix_unfollowed()] + if sys.prefix != prefixes[0]: + prefixes.append(sys.prefix) + dir_paths = [join(p, basename(sysconfig.get_path("scripts"))) for p in prefixes] + # Is this still needed? + if on_win: + dir_paths.append("C:\\cygwin\\bin") + else: + dir_paths = [] + + dir_paths.extend(os.environ.get("PATH", "").split(os.pathsep)) + + if on_win: + pat = re.compile(r"conda-([\w\-]+)(\.(exe|bat))?$") + else: + pat = re.compile(r"conda-([\w\-]+)$") + + res = set() + for dir_path in dir_paths: + try: + for entry in os.scandir(dir_path): + m = pat.match(entry.name) + if m and entry.is_file(): + res.add(m.group(1)) + except (FileNotFoundError, NotADirectoryError, PermissionError, OSError): + # FileNotFoundError: path doesn't exist + # NotADirectoryError: path is not a directory + # PermissionError: user doesn't have read access + # OSError: [WinError 123] The filename, directory name, or volume + # label syntax is incorrect + continue + return tuple(sorted(res)) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/helpers.py b/miniconda3/lib/python3.13/site-packages/conda/cli/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..8617cf84b279455f769e348d8aacd784ee5d7a39 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/helpers.py @@ -0,0 +1,635 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Collection of helper functions to standardize reused CLI arguments. +""" + +from __future__ import annotations + +from argparse import ( + SUPPRESS, + Action, + BooleanOptionalAction, + _HelpAction, + _StoreAction, + _StoreTrueAction, +) +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from argparse import ArgumentParser, _ArgumentGroup, _MutuallyExclusiveGroup + + +class LazyChoicesAction(Action): + def __init__(self, option_strings, dest, choices_func, **kwargs): + self.choices_func = choices_func + self._cached_choices = None + super().__init__(option_strings, dest, **kwargs) + + @property + def choices(self): + """Dynamically evaluate choices for help generation and validation.""" + if self._cached_choices is None: + self._cached_choices = self.choices_func() + return self._cached_choices + + @choices.setter + def choices(self, value): + """Ignore attempts to set choices since we use choices_func.""" + # argparse tries to set self.choices during __init__, but we ignore it + # since we dynamically generate choices via choices_func + pass + + def __call__(self, parser, namespace, values, option_string=None): + valid_choices = self.choices + if values not in valid_choices: + choices_string = ", ".join(f"'{val}'" for val in valid_choices) + # Use the same format as argparse for consistency + option_display = "/".join(self.option_strings) + parser.error( + f"argument {option_display}: invalid choice: {values!r} (choose from {choices_string})" + ) + setattr(namespace, self.dest, values) + + +class _ValidatePackages(_StoreAction): + """ + Used to validate match specs of packages + """ + + @staticmethod + def _validate_no_denylist_channels(packages_specs): + """ + Ensure the packages do not contain denylist_channels + """ + from ..base.context import validate_channels + from ..models.match_spec import MatchSpec + + if not isinstance(packages_specs, (list, tuple)): + packages_specs = [packages_specs] + + validate_channels( + channel + for spec in map(MatchSpec, packages_specs) + if (channel := spec.get_exact_value("channel")) + ) + + def __call__(self, parser, namespace, values, option_string=None): + self._validate_no_denylist_channels(values) + super().__call__(parser, namespace, values, option_string) + + +def add_parser_create_install_update(p, prefix_required=False): + from ..common.constants import NULL + + add_parser_prefix(p, prefix_required) + channel_options = add_parser_channels(p) + solver_mode_options = add_parser_solver_mode(p) + package_install_options = add_parser_package_install_options(p) + add_parser_networking(p) + + output_and_prompt_options = add_output_and_prompt_options(p) + output_and_prompt_options.add_argument( + "--download-only", + action="store_true", + default=NULL, + help="Solve an environment and ensure package caches are populated, but exit " + "prior to unlinking and linking packages into the prefix.", + ) + add_parser_show_channel_urls(output_and_prompt_options) + + add_parser_pscheck(p) + add_parser_known(p) + + # Add the file kwarg. We don't use {action="store", nargs='*'} as we don't + # want to gobble up all arguments after --file. + p.add_argument( + # "-f", # FUTURE: 26.3: Enable this after deprecating alias in --force + "--file", + default=[], + action="append", + help="Read package versions from the given file. Repeated file " + "specifications can be passed (e.g. --file=file1 --file=file2).", + ) + p.add_argument( + "packages", + metavar="package_spec", + action=_ValidatePackages, + nargs="*", + help="List of packages to install or update in the conda environment.", + ) + + return solver_mode_options, package_install_options, channel_options + + +def add_parser_pscheck(p: ArgumentParser) -> None: + p.add_argument("--force-pscheck", action="store_true", help=SUPPRESS) + + +def add_parser_show_channel_urls(p: ArgumentParser | _ArgumentGroup) -> None: + from ..common.constants import NULL + + p.add_argument( + "--show-channel-urls", + action="store_true", + dest="show_channel_urls", + default=NULL, + help="Show channel urls. " + "Overrides the value given by `conda config --show show_channel_urls`.", + ) + p.add_argument( + "--no-show-channel-urls", + action="store_false", + dest="show_channel_urls", + help=SUPPRESS, + ) + + +def add_parser_help(p: ArgumentParser) -> None: + """ + So we can use consistent capitalization and periods in the help. You must + use the add_help=False argument to ArgumentParser or add_parser to use + this. Add this first to be consistent with the default argparse output. + + """ + p.add_argument( + "-h", + "--help", + action=_HelpAction, + help="Show this help message and exit.", + ) + + +def add_parser_prefix( + p: ArgumentParser, + prefix_required: bool = False, +) -> _MutuallyExclusiveGroup: + target_environment_group = p.add_argument_group("Target Environment Specification") + npgroup = target_environment_group.add_mutually_exclusive_group( + required=prefix_required + ) + add_parser_prefix_to_group(npgroup) + return npgroup + + +def add_parser_prefix_to_group(m: _MutuallyExclusiveGroup) -> None: + m.add_argument( + "-n", + "--name", + action="store", + help="Name of environment.", + metavar="ENVIRONMENT", + ) + m.add_argument( + "-p", + "--prefix", + action="store", + help="Full path to environment location (i.e. prefix).", + metavar="PATH", + ) + + +def add_parser_json(p: ArgumentParser) -> _ArgumentGroup: + from ..common.constants import NULL + + output_and_prompt_options = p.add_argument_group( + "Output, Prompt, and Flow Control Options" + ) + output_and_prompt_options.add_argument( + "--json", + action="store_true", + default=NULL, + help="Report all output as json. Suitable for using conda programmatically.", + ) + output_and_prompt_options.add_argument( + "--console", + default=NULL, + help="Select the backend to use for normal output rendering.", + ) + add_parser_verbose(output_and_prompt_options) + output_and_prompt_options.add_argument( + "-q", + "--quiet", + action="store_true", + default=NULL, + help="Do not display progress bar.", + ) + return output_and_prompt_options + + +def add_output_and_prompt_options(p: ArgumentParser) -> _ArgumentGroup: + from ..common.constants import NULL + + output_and_prompt_options = add_parser_json(p) + output_and_prompt_options.add_argument( + "-d", + "--dry-run", + action="store_true", + help="Only display what would have been done.", + ) + output_and_prompt_options.add_argument( + "-y", + "--yes", + action="store_true", + default=NULL, + help="Sets any confirmation values to 'yes' automatically. " + "Users will not be asked to confirm any adding, deleting, backups, etc.", + ) + return output_and_prompt_options + + +def add_parser_frozen_env(p: ArgumentParser): + from ..common.constants import NULL + + p.add_argument( + "--override-frozen", + action="store_false", + default=NULL, + help="DANGEROUS. Use at your own risk. Ignore protections if the environment is frozen.", + dest="protect_frozen_envs", + ) + + +def add_parser_channels(p: ArgumentParser) -> _ArgumentGroup: + from ..common.constants import NULL + + channel_customization_options = p.add_argument_group("Channel Customization") + channel_customization_options.add_argument( + "-c", + "--channel", + # beware conda-build uses this (currently or in the past?) + # if ever renaming to "channels" consider removing context.channels alias to channel + dest="channel", + action="append", + help=( + "Additional channel to search for packages. These are URLs searched in the order " + "they are given (including local directories using the 'file://' syntax or " + "simply a path like '/home/conda/mychan' or '../mychan'). Then, the defaults " + "or channels from .condarc are searched (unless --override-channels is given). " + "You can use 'defaults' to get the default packages for conda. You can also " + "use any name and the .condarc channel_alias value will be prepended. The " + "default channel_alias is https://conda.anaconda.org/." + ), + ) + channel_customization_options.add_argument( + "--use-local", + action="store_true", + default=NULL, + help="Use locally built packages. Identical to '-c local'.", + ) + channel_customization_options.add_argument( + "-O", + "--override-channels", + action="store_true", + help="""Do not search default or .condarc channels. Requires --channel.""", + ) + channel_customization_options.add_argument( + "--repodata-fn", + action="append", + dest="repodata_fns", + help=( + "Specify file name of repodata on the remote server where your channels " + "are configured or within local backups. Conda will try whatever you " + "specify, but will ultimately fall back to repodata.json if your specs are " + "not satisfiable with what you specify here. This is used to employ repodata " + "that is smaller and reduced in time scope. You may pass this flag more than " + "once. Leftmost entries are tried first, and the fallback to repodata.json " + "is added for you automatically. For more information, see " + "conda config --describe repodata_fns." + ), + ) + channel_customization_options.add_argument( + "--experimental", + action="append", + choices=["jlap", "lock"], + help="jlap: Download incremental package index data from repodata.jlap; implies 'lock'. " + "lock: use locking when reading, updating index (repodata.json) cache. Now enabled.", + ) + channel_customization_options.add_argument( + "--no-lock", + action="store_true", + help="Disable locking when reading, updating index (repodata.json) cache. ", + ) + + channel_customization_options.add_argument( + "--repodata-use-zst", + action=BooleanOptionalAction, + dest="repodata_use_zst", + default=NULL, + help="Check for/do not check for repodata.json.zst. Enabled by default.", + ) + return channel_customization_options + + +def add_parser_solver_mode(p: ArgumentParser) -> _ArgumentGroup: + from ..base.constants import DepsModifier + from ..common.constants import NULL + + solver_mode_options = p.add_argument_group("Solver Mode Modifiers") + deps_modifiers = solver_mode_options.add_mutually_exclusive_group() + solver_mode_options.add_argument( + "--strict-channel-priority", + action="store_const", + dest="channel_priority", + default=NULL, + const="strict", + help="Packages in lower priority channels are not considered if a package " + "with the same name appears in a higher priority channel.", + ) + solver_mode_options.add_argument( + "--channel-priority", + action="store_true", + dest="channel_priority", + default=NULL, + help=SUPPRESS, + ) + solver_mode_options.add_argument( + "--no-channel-priority", + action="store_const", + dest="channel_priority", + default=NULL, + const="disabled", + help="Package version takes precedence over channel priority. " + "Overrides the value given by `conda config --show channel_priority`.", + ) + deps_modifiers.add_argument( + "--no-deps", + action="store_const", + const=DepsModifier.NO_DEPS, + dest="deps_modifier", + help="Do not install, update, remove, or change dependencies. This WILL lead " + "to broken environments and inconsistent behavior. Use at your own risk.", + default=NULL, + ) + deps_modifiers.add_argument( + "--only-deps", + action="store_const", + const=DepsModifier.ONLY_DEPS, + dest="deps_modifier", + help="Only install dependencies.", + default=NULL, + ) + solver_mode_options.add_argument( + "--no-pin", + action="store_true", + dest="ignore_pinned", + default=NULL, + help="Ignore pinned file.", + ) + return solver_mode_options + + +def add_parser_update_modifiers(solver_mode_options: ArgumentParser): + from ..base.constants import UpdateModifier + from ..common.constants import NULL + + update_modifiers = solver_mode_options.add_mutually_exclusive_group() + update_modifiers.add_argument( + "--freeze-installed", + "--no-update-deps", + action="store_const", + const=UpdateModifier.FREEZE_INSTALLED, + dest="update_modifier", + default=NULL, + help="Do not update or change already-installed dependencies.", + ) + update_modifiers.add_argument( + "--update-deps", + action="store_const", + const=UpdateModifier.UPDATE_DEPS, + dest="update_modifier", + default=NULL, + help="Update dependencies that have available updates.", + ) + update_modifiers.add_argument( + "-S", + "--satisfied-skip-solve", + action="store_const", + const=UpdateModifier.SPECS_SATISFIED_SKIP_SOLVE, + dest="update_modifier", + default=NULL, + help="Exit early and do not run the solver if the requested specs are satisfied. " + "Also skips aggressive updates as configured by the " + "'aggressive_update_packages' config setting. Use " + "'conda config --describe aggressive_update_packages' to view your setting. " + "--satisfied-skip-solve is similar to the default behavior of 'pip install'.", + ) + update_modifiers.add_argument( + "--update-all", + "--all", + action="store_const", + const=UpdateModifier.UPDATE_ALL, + dest="update_modifier", + help="Update all installed packages in the environment.", + default=NULL, + ) + update_modifiers.add_argument( + "--update-specs", + action="store_const", + const=UpdateModifier.UPDATE_SPECS, + dest="update_modifier", + help="Update based on provided specifications.", + default=NULL, + ) + + +def add_parser_prune(p: ArgumentParser) -> None: + from ..common.constants import NULL + + p.add_argument( + "--prune", + action="store_true", + default=NULL, + help=SUPPRESS, + ) + + +def add_parser_solver(p: ArgumentParser) -> None: + """ + Add a command-line flag for alternative solver backends. + + See ``context.solver`` for more info. + """ + from ..base.context import context + from ..common.constants import NULL + + group = p.add_mutually_exclusive_group() + group.add_argument( + "--solver", + dest="solver", + action=LazyChoicesAction, + choices_func=context.plugin_manager.get_solvers, + help="Choose which solver backend to use.", + default=NULL, + ) + + +def add_parser_networking(p: ArgumentParser) -> _ArgumentGroup: + from ..common.constants import NULL + + networking_options = p.add_argument_group("Networking Options") + networking_options.add_argument( + "-C", + "--use-index-cache", + action="store_true", + default=False, + help="Use cache of channel index files, even if it has expired. This is useful " + "if you don't want conda to check whether a new version of the repodata " + "file exists, which will save bandwidth.", + ) + networking_options.add_argument( + "-k", + "--insecure", + action="store_false", + dest="ssl_verify", + default=NULL, + help='Allow conda to perform "insecure" SSL connections and transfers. ' + "Equivalent to setting 'ssl_verify' to 'false'.", + ) + networking_options.add_argument( + "--offline", + action="store_true", + default=NULL, + help="Offline mode. Don't connect to the Internet.", + ) + return networking_options + + +def add_parser_package_install_options(p: ArgumentParser) -> _ArgumentGroup: + from ..common.constants import NULL + from ..deprecations import deprecated + + package_install_options = p.add_argument_group( + "Package Linking and Install-time Options" + ) + package_install_options.add_argument( + "-f", + dest="force", + action=deprecated.action( + "25.9", + "26.3", + _StoreTrueAction, + addendum="Use `--force` instead.", + ), + default=NULL, + help=SUPPRESS, + ) + package_install_options.add_argument( + "--force", + action="store_true", + default=NULL, + help=SUPPRESS, + ) + package_install_options.add_argument( + "--copy", + action="store_true", + default=NULL, + help="Install all packages using copies instead of hard- or soft-linking.", + ) + package_install_options.add_argument( + "--shortcuts", + action="store_true", + help=SUPPRESS, + dest="shortcuts", + default=NULL, + ) + package_install_options.add_argument( + "--no-shortcuts", + action="store_false", + help="Don't install start menu shortcuts", + dest="shortcuts", + default=NULL, + ) + package_install_options.add_argument( + "--shortcuts-only", + action="append", + help="Install shortcuts only for this package name. Can be used several times.", + dest="shortcuts_only", + ) + return package_install_options + + +def add_parser_known(p: ArgumentParser) -> None: + p.add_argument( + "--unknown", + action="store_true", + default=False, + dest="unknown", + help=SUPPRESS, + ) + + +def add_parser_default_packages(p: ArgumentParser) -> None: + p.add_argument( + "--no-default-packages", + action="store_true", + help="Ignore create_default_packages in the .condarc file.", + ) + + +def add_parser_platform(parser): + from ..base.constants import KNOWN_SUBDIRS + from ..common.constants import NULL + + parser.add_argument( + "--subdir", + "--platform", + default=NULL, + dest="subdir", + choices=[s for s in KNOWN_SUBDIRS if s != "noarch"], + metavar="SUBDIR", + help="Use packages built for this platform. " + "The new environment will be configured to remember this choice. " + "Should be formatted like 'osx-64', 'linux-32', 'win-64', and so on. " + "Defaults to the current (native) platform.", + ) + + +def add_parser_verbose(parser: ArgumentParser | _ArgumentGroup) -> None: + from ..common.constants import NULL + from .actions import NullCountAction + + parser.add_argument( + "-v", + "--verbose", + action=NullCountAction, + help=( + "Can be used multiple times. Once for detailed output, twice for INFO logging, " + "thrice for DEBUG logging, four times for TRACE logging." + ), + dest="verbosity", + default=NULL, + ) + parser.add_argument( + "--debug", + action="store_true", + help=SUPPRESS, + default=NULL, + ) + parser.add_argument( + "--trace", + action="store_true", + help=SUPPRESS, + default=NULL, + ) + + +def add_parser_environment_specifier(p: ArgumentParser) -> None: + from ..base.context import context + from ..common.constants import NULL + + p.add_argument( + "--environment-specifier", + "--env-spec", # for brevity + action=LazyChoicesAction, + choices_func=context.plugin_manager.get_environment_specifiers, + default=NULL, + help="(EXPERIMENTAL) Specify the environment specifier plugin to use.", + ) + + +def comma_separated_stripped(value: str) -> list[str]: + """ + Custom type for argparse to handle comma-separated strings with stripping + """ + return [item.strip() for item in value.split(",")] diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/install.py b/miniconda3/lib/python3.13/site-packages/conda/cli/install.py new file mode 100644 index 0000000000000000000000000000000000000000..2f819829c4c4ff55323f1570748a4d2e0d49be3d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/install.py @@ -0,0 +1,593 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda package installation logic. + +Core logic for `conda [create|install|update|remove]` commands. + +See conda.cli.main_create, conda.cli.main_install, conda.cli.main_update, and +conda.cli.main_remove for the entry points into this module. +""" + +from __future__ import annotations + +import os +from logging import getLogger +from os.path import abspath, basename, exists, isdir +from pathlib import Path + +from boltons.setutils import IndexedSet + +from ..base.constants import ( + REPODATA_FN, + RESERVED_ENV_NAMES, + UpdateModifier, +) +from ..base.context import context +from ..common.configuration import DEFAULT_CONDARC_FILENAME +from ..common.constants import NULL +from ..core.index import Index +from ..core.link import PrefixSetup, UnlinkLinkTransaction +from ..core.prefix_data import PrefixData +from ..core.solve import diff_for_unlink_link_precs +from ..deprecations import deprecated +from ..exceptions import ( + CondaEnvException, + CondaExitZero, + CondaImportError, + CondaIndexError, + CondaSystemExit, + CondaUpdatePackageError, + CondaValueError, + DirectoryNotACondaEnvironmentError, + DryRunExit, + NoBaseEnvironmentError, + PackageNotInstalledError, + PackagesNotFoundError, + ResolvePackageNotFound, + SpecsConfigurationConflictError, + UnsatisfiableError, +) +from ..gateways.disk.delete import delete_trash, path_is_clean +from ..history import History +from ..misc import ( + _get_best_prec_match, + clone_env, + install_explicit_packages, +) +from ..models.channel import all_channel_urls +from ..models.environment import Environment +from ..models.match_spec import MatchSpec +from ..models.prefix_graph import PrefixGraph +from ..reporters import confirm_yn, get_spinner +from . import common +from .common import check_non_admin +from .main_config import set_keys + +log = getLogger(__name__) +stderrlog = getLogger("conda.stderr") + + +def reinstall_packages(args, specs: list[str], **kwargs) -> int: + """Reinstall packages using conda install. + + Helper for health fixes that need to reinstall packages. + + :param args: Parsed arguments namespace + :param specs: Package specs to reinstall + :param kwargs: Override default install options (e.g., force_reinstall=True) + :return: Exit code from install + """ + args.packages = specs + args.channel = kwargs.get("channel", None) + args.override_channels = kwargs.get("override_channels", False) + args.force_reinstall = kwargs.get("force_reinstall", False) + args.satisfied_skip_solve = kwargs.get("satisfied_skip_solve", False) + args.update_deps = kwargs.get("update_deps", False) + args.only_deps = kwargs.get("only_deps", False) + args.no_deps = kwargs.get("no_deps", False) + args.prune = kwargs.get("prune", False) + args.freeze_installed = kwargs.get("freeze_installed", False) + args.solver_retries = kwargs.get("solver_retries", 0) + + return install(args, None) + + +@deprecated("25.9", "26.3", addendum="Use PrefixData.exists()") +def validate_prefix_exists(prefix: str | Path) -> None: + """ + Validate that we are receiving at least one valid value for --name or --prefix. + """ + prefix = Path(prefix) + if not prefix.exists(): + raise CondaEnvException("The environment you have specified does not exist.") + + +@deprecated( + "25.9", "26.3", addendum="Use PrefixData.exists() + PrefixData.validate_path()" +) +def validate_new_prefix(dest: str, force: bool = False) -> str: + """Ensure that the new prefix does not exist.""" + from ..base.context import context, validate_prefix_name + from ..common.path import expand + + if os.sep in dest: + dest = expand(dest) + else: + dest = validate_prefix_name(dest, ctx=context, allow_base=False) + + if not force and os.path.exists(dest): + env_name = os.path.basename(os.path.normpath(dest)) + raise CondaEnvException( + f"The environment '{env_name}' already exists. Override with --yes." + ) + + return dest + + +@deprecated( + "25.9", + "26.3", + addendum="Use PrefixData.exists(), PrefixData.validate_path(), PrefixData.validate_name()", +) +def check_prefix(prefix: str, json=False): + if os.pathsep in prefix: + raise CondaValueError( + f"Cannot create a conda environment with '{os.pathsep}' in the prefix. Aborting." + ) + name = basename(prefix) + error = None + if name in RESERVED_ENV_NAMES: + error = f"'{name}' is a reserved environment name" + if exists(prefix): + if isdir(prefix) and "conda-meta" not in tuple( + entry.name for entry in os.scandir(prefix) + ): + return None + error = f"prefix already exists: {prefix}" + + if error: + raise CondaValueError(error, json) + + if " " in prefix: + stderrlog.warning( + "WARNING: A space was detected in your requested environment path:\n" + f"'{prefix}'\n" + "Spaces in paths can sometimes be problematic. To minimize issues,\n" + "make sure you activate your environment before running any executables!\n" + ) + + +def clone(src_arg, dst_prefix, json=False, quiet=False, index_args=None): + # Validate source + if os.sep in src_arg: + source_prefix_data = PrefixData(abspath(src_arg)) + else: + source_prefix_data = PrefixData.from_name(src_arg) + source_prefix_data.assert_environment() + src_prefix = str(source_prefix_data.prefix_path) + + if not json: + print(f"Source: {src_prefix}") + print(f"Destination: {dst_prefix}") + + actions, untracked_files = clone_env( + src_prefix, dst_prefix, verbose=not json, quiet=quiet, index_args=index_args + ) + + if json: + common.stdout_json_success( + actions=actions, + untracked_files=list(untracked_files), + src_prefix=src_prefix, + dst_prefix=dst_prefix, + ) + + +@deprecated("25.9", "26.3", addendum="Use conda.cli.common.print_activate()") +def print_activate(env_name_or_prefix): # pragma: no cover + from .common import print_activate as _print_activate + + _print_activate(env_name_or_prefix) + + +def get_revision(arg, json=False): + try: + return int(arg) + except ValueError: + raise CondaValueError(f"expected revision number, not: '{arg}'", json) + + +def get_index_args(args) -> dict[str, any]: + """Returns a dict of args required for fetching an index + :param args: The args provided by the cli + :returns: dict of index args + """ + return { + # TODO: deprecate --use-index-cache + # "use_cache": args.use_index_cache, # --use-index-cache + "channel_urls": context.channels, + # TODO: deprecate --unknown + # "unknown": args.unknown, # --unknown + "prepend": not args.override_channels, # --override-channels + "use_local": args.use_local, # --use-local + } + + +class TryRepodata: + def __init__( + self, notify_success, repodata, last_repodata, index_args, allowed_errors + ): + self.notify_success = notify_success + self.repodata = repodata + self.last_repodata = last_repodata + self.index_args = index_args + self.allowed_errors = allowed_errors + + def __enter__(self): + return self.repodata + + def __exit__(self, exc_type, exc_value, traceback): + if not exc_value: + self.notify_success() + + # Swallow the error to allow for the next repodata to be tried if: + # 1. the error is in the 'allowed_errors' type + # 2. there are more repodatas to try AND + # 3. the error says it's okay to retry + # + # TODO: Regarding (3) This is a temporary workaround to allow downstream libraries + # to inject this attribute set to False and skip the retry logic + # Other solvers might implement their own internal retry logic without + # depending --freeze-install implicitly like conda classic does. Example + # retry loop in conda-libmamba-solver: + # https://github.com/conda-incubator/conda-libmamba-solver/blob/da5b1ba/conda_libmamba_solver/solver.py#L254-L299 + # If we end up raising UnsatisfiableError, we annotate it with `allow_retry` + # so we don't have go through all the repodatas and freeze-installed logic + # unnecessarily (see https://github.com/conda/conda/issues/11294). see also: + # https://github.com/conda-incubator/conda-libmamba-solver/blob/7c698209/conda_libmamba_solver/solver.py#L617 + if ( + isinstance(exc_value, self.allowed_errors) + and (self.repodata != self.last_repodata) + and getattr(exc_value, "allow_retry", True) + ): + return True + elif isinstance(exc_value, ResolvePackageNotFound): + # convert the ResolvePackageNotFound into PackagesNotFoundError + raise PackagesNotFoundError( + exc_value._formatted_chains, + all_channel_urls(context.channels), + ) + + +class Repodatas: + def __init__(self, repodata_fns, index_args, allows_errors=()): + self.repodata_fns = repodata_fns + self.index_args = index_args + self.success = False + self.allowed_errors = ( + ResolvePackageNotFound, + PackagesNotFoundError, + *allows_errors, + ) + + def __iter__(self): + for repodata in self.repodata_fns: + yield TryRepodata( + self.succeed, + repodata, + self.repodata_fns[-1], + self.index_args, + self.allowed_errors, + ) + if self.success: + break + + def succeed(self): + self.success = True + + +def validate_install_command(prefix: str, command: str = "install"): + """Executes a set of validations that are required before any installation + command is executed. This includes: + * ensure the configuration is valid + * ensuring the user in not an admin + * ensure the user is not forcing 32bit installs in the root prefix + + :param prefix: The prefix where the environment will be created + :param command: Type of operation being performed + :raises: error if the configuration for the install is bad + """ + context.validate_configuration() + check_non_admin() + + prefix_data = PrefixData(prefix) + + if context.force_32bit and prefix_data.is_base(): + raise CondaValueError("cannot use CONDA_FORCE_32BIT=1 in base env") + + if command in ("install", "update", "remove"): + try: + prefix_data.assert_writable() + except DirectoryNotACondaEnvironmentError as exc: + if prefix_data == PrefixData(context.conda_prefix): + raise NoBaseEnvironmentError() from exc + delete_trash(prefix) + if not path_is_clean(prefix): + raise + if context.protect_frozen_envs: + prefix_data.assert_not_frozen() + + +def ensure_update_specs_exist(prefix: str, specs: list[str]): + """Checks that each spec that is requested as an update exists in the prefix + + :param prefix: The target install prefix + :param specs: List of specs to be updated + :raises CondaError: if there is an invalid spec provided + :raises PackageNotInstalledError: if the requested specs to install don't exist in the prefix + """ + prefix_data = PrefixData(prefix) + for spec in specs: + spec = MatchSpec(spec) + if not spec.is_name_only_spec: + raise CondaUpdatePackageError(spec) + if not prefix_data.get(spec.name, None): + raise PackageNotInstalledError(prefix, spec.name) + + +def install(args, parser, command="install"): + """Logic for `conda install`, `conda update`, and `conda create`.""" + newenv = command == "create" + isupdate = command == "update" + isinstall = command == "install" + + # fail early if using a deprecated option + if newenv and args.clone: + deprecated.topic( + "25.9", + "26.3", + topic="This function will not handle clones anymore.", + addendum="Use `conda.cli.install.install_clone()` instead", + ) + return install_clone(args, parser) + + prefix = context.target_prefix + index_args = get_index_args(args=args) + + # common validations for all types of installs + validate_install_command(prefix=prefix, command=command) + + if context.use_only_tar_bz2: + args.repodata_fns = ("repodata.json",) + + env = Environment.from_cli( + args=args, + add_default_packages=command == "create" and not args.no_default_packages, + ) + + # for 'conda update' make sure: + # 1) there are no explicit_packages specified + # 2) the requested specs actually exist in the prefix + # and that they are name-only specs + if isupdate: + if env.explicit_packages: + raise CondaUpdatePackageError(env.explicit_packages) + if env.config.update_modifier != UpdateModifier.UPDATE_ALL: + ensure_update_specs_exist(prefix=env.prefix, specs=env.requested_packages) + + # install explicit specs + if len(env.explicit_packages) > 0 and len(env.requested_packages) == 0: + return install_explicit_packages(env.explicit_packages, env.prefix) + + repodata_fns = args.repodata_fns + if not repodata_fns: + repodata_fns = list(env.config.repodata_fns) + if REPODATA_FN not in repodata_fns: + repodata_fns.append(REPODATA_FN) + + # This helps us differentiate between an update, the --freeze-installed option, and the retry + # behavior in our initial fast frozen solve + _should_retry_unfrozen = ( + getattr(args, "update_modifier", NULL) + not in (UpdateModifier.FREEZE_INSTALLED, UpdateModifier.UPDATE_SPECS) + ) and not newenv + + if isinstall and args.update_modifier == NULL: + update_modifier = UpdateModifier.FREEZE_INSTALLED + else: + update_modifier = env.config.update_modifier + deps_modifier = env.config.deps_modifier + + for repodata_fn in Repodatas( + repodata_fns, + index_args, + (UnsatisfiableError, SpecsConfigurationConflictError, SystemExit), + ): + with repodata_fn as repodata: + solver_backend = context.plugin_manager.get_cached_solver_backend() + solver = solver_backend( + prefix, + env.config.channels, + context.subdirs, + specs_to_add=env.requested_packages, + repodata_fn=repodata, + command=args.cmd, + ) + try: + unlink_link_transaction = solver.solve_for_transaction( + deps_modifier=deps_modifier, + update_modifier=update_modifier, + force_reinstall=context.force_reinstall or context.force, + should_retry_solve=( + _should_retry_unfrozen or repodata != repodata_fns[-1] + ), + ) + except (UnsatisfiableError, SpecsConfigurationConflictError) as e: + if not getattr(e, "allow_retry", True): + raise e + if _should_retry_unfrozen: + unlink_link_transaction = solver.solve_for_transaction( + deps_modifier=deps_modifier, + update_modifier=UpdateModifier.UPDATE_SPECS, + force_reinstall=context.force_reinstall or context.force, + should_retry_solve=(repodata != repodata_fns[-1]), + ) + else: + raise e + except SystemExit as e: + if not getattr(e, "allow_retry", True): + raise e + if e.args and "could not import" in e.args[0]: + raise CondaImportError(str(e)) + raise e + + handle_txn(unlink_link_transaction, prefix, args, newenv) + + +def install_clone(args, parser): + """Executes an install of a new conda environment by cloning.""" + prefix = context.target_prefix + index_args = get_index_args(args) + + # common validations for all types of installs + validate_install_command(prefix=prefix, command="create") + + clone( + args.clone, + prefix, + json=context.json, + quiet=context.quiet, + index_args=index_args, + ) + + +def install_revision(args, parser): + """Install a previous version of a conda environment""" + prefix = context.target_prefix + index_args = get_index_args(args) + + # common validations for all types of installs + validate_install_command(prefix=prefix, command="install") + + # this is sort of a hack. current_repodata.json may not have any .tar.bz2 files, + # because it deduplicates records that exist as both formats. Forcing this to + # repodata.json ensures that .tar.bz2 files are available + if context.use_only_tar_bz2: + args.repodata_fns = ("repodata.json",) + + # ensure trash is cleared from existing prefix + delete_trash(prefix) + + repodata_fns = args.repodata_fns + if not repodata_fns: + repodata_fns = list(context.repodata_fns) + if REPODATA_FN not in repodata_fns: + repodata_fns.append(REPODATA_FN) + + for repodata_fn in Repodatas(repodata_fns, index_args): + with repodata_fn as repodata: + with get_spinner(f"Collecting package metadata ({repodata})"): + index = Index( + channels=index_args["channel_urls"], + prepend=index_args["prepend"], # --override-channels + platform=None, + # these options were commented out in the version of this + # code bit that used the now-deprecated `get_index` function + # we have left them here so that this information is not lost + # use_cache=index_args["use_cache"], # --use-index-cache + # unknown=index_args["unknown"], # --unknown + use_local=index_args["use_local"], + prefix=prefix, + repodata_fn=repodata, + ) + revision_idx = get_revision(args.revision) + with get_spinner(f"Reverting to revision {revision_idx}"): + unlink_link_transaction = revert_actions(prefix, revision_idx, index) + + handle_txn(unlink_link_transaction, prefix, args, newenv=False) + + +def revert_actions(prefix, revision=-1, index: Index | None = None): + # TODO: If revision raise a revision error, should always go back to a safe revision + h = History(prefix) + # TODO: need a History method to get user-requested specs for revision number + # Doing a revert right now messes up user-requested spec history. + # Either need to wipe out history after ``revision``, or add the correct + # history information to the new entry about to be created. + # TODO: This is wrong!!!!!!!!!! + user_requested_specs = h.get_requested_specs_map().values() + try: + target_state = { + MatchSpec.from_dist_str(dist_str) for dist_str in h.get_state(revision) + } + except IndexError: + raise CondaIndexError("no such revision: %d" % revision) + + if index is not None: + index.reload(prefix=True) + + not_found_in_index_specs = set() + link_precs = set() + for spec in target_state: + precs = tuple(prec for prec in index.values() if spec.match(prec)) + if not precs: + not_found_in_index_specs.add(spec) + elif len(precs) > 1: + link_precs.add(_get_best_prec_match(precs)) + else: + link_precs.add(precs[0]) + + if not_found_in_index_specs: + raise PackagesNotFoundError(not_found_in_index_specs) + + final_precs = IndexedSet(PrefixGraph(link_precs).graph) # toposort + unlink_precs, link_precs = diff_for_unlink_link_precs(prefix, final_precs) + setup = PrefixSetup(prefix, unlink_precs, link_precs, (), user_requested_specs, ()) + return UnlinkLinkTransaction(setup) + + +def handle_txn(unlink_link_transaction, prefix, args, newenv, remove_op=False): + if unlink_link_transaction.nothing_to_do: + if remove_op: + # No packages found to remove from environment + raise PackagesNotFoundError(args.package_names) + elif not newenv: + if context.json: + common.stdout_json_success( + message="All requested packages already installed." + ) + else: + print("\n# All requested packages already installed.\n") + return + + if not context.json: + unlink_link_transaction.print_transaction_summary() + confirm_yn() + + elif context.dry_run: + actions = unlink_link_transaction._make_legacy_action_groups()[0] + common.stdout_json_success(prefix=prefix, actions=actions, dry_run=True) + raise DryRunExit() + + try: + unlink_link_transaction.download_and_extract() + if context.download_only: + raise CondaExitZero( + "Package caches prepared. UnlinkLinkTransaction cancelled with " + "--download-only option." + ) + unlink_link_transaction.execute() + + except SystemExit as e: + raise CondaSystemExit("Exiting", e) + + if newenv: + if context.subdir != context._native_subdir(): + set_keys( + ("subdir", context.subdir), + path=Path(prefix, DEFAULT_CONDARC_FILENAME), + ) + + if context.json: + actions = unlink_link_transaction._make_legacy_action_groups()[0] + common.stdout_json_success(prefix=prefix, actions=actions) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main.py new file mode 100644 index 0000000000000000000000000000000000000000..0180e6033141be8ef1712340489982f0d11c3a97 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main.py @@ -0,0 +1,114 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Entry point for all conda subcommands.""" + +import sys + + +def init_loggers(): + import logging + + from ..base.context import context + from ..gateways.logging import initialize_logging, set_log_level + + initialize_logging() + + # silence logging info to avoid interfering with JSON output + if context.json: + for logger in ("conda.stdout.verbose", "conda.stdoutlog", "conda.stderrlog"): + logging.getLogger(logger).setLevel(logging.CRITICAL + 10) + + # set log_level + set_log_level(context.log_level) + + +def main_subshell(*args, post_parse_hook=None, **kwargs): + """Entrypoint for the "subshell" invocation of CLI interface. E.g. `conda create`.""" + # defer import here so it doesn't hit the 'conda shell.*' subcommands paths + from ..base.context import context + from .conda_argparse import do_call, generate_parser, generate_pre_parser + + args = args or ["--help"] + + pre_parser = generate_pre_parser(add_help=False) + args_subset = args[: args.index("--")] if "--" in args else args + pre_args, _ = pre_parser.parse_known_args(args_subset) + + # the arguments that we want to pass to the main parser later on + override_args = { + "json": pre_args.json, + "debug": pre_args.debug, + "trace": pre_args.trace, + "verbosity": pre_args.verbosity, + } + + context.__init__(argparse_args=pre_args) + if context.no_plugins: + context.plugin_manager.disable_external_plugins() + + # reinitialize in case any of the entrypoints modified the context + context.__init__(argparse_args=pre_args) + + parser = generate_parser(add_help=True) + args = parser.parse_args(args, override_args=override_args, namespace=pre_args) + + context.__init__(argparse_args=args) + init_loggers() + + # used with main_pip.py + if post_parse_hook: + post_parse_hook(args, parser) + + exit_code = do_call(args, parser) + if isinstance(exit_code, int): + return exit_code + elif hasattr(exit_code, "rc"): + return exit_code.rc + + +def main_sourced(shell, *args, **kwargs): + """Entrypoint for the "sourced" invocation of CLI interface. E.g. `conda activate`.""" + shell = shell.replace("shell.", "", 1) + + # This is called any way later in conda.activate, so no point in removing it + from ..base.context import context + from ..common.compat import on_win + + context.__init__() + + from ..activate import _build_activator_cls + + try: + activator_cls = _build_activator_cls(shell) + except KeyError: + from ..exceptions import CondaError + + raise CondaError(f"{shell} is not a supported shell.") + + activator = activator_cls(args) + result = activator.execute() + + # Fix line endings for shells that need it on Windows + if on_win and activator.needs_line_ending_fix: + result = result.replace("\r", "") + sys.stdout.reconfigure(encoding="utf-8", newline="\n") + + print(result, end="") + return 0 + + +def main(*args, **kwargs): + # conda.common.compat contains only stdlib imports + from ..common.compat import ensure_text_type + from ..exception_handler import conda_exception_handler + + # cleanup argv + args = args or sys.argv[1:] # drop executable/script + args = tuple(ensure_text_type(s) for s in args) + + if args and args[0].strip().startswith("shell."): + main = main_sourced + else: + main = main_subshell + + return conda_exception_handler(main, *args, **kwargs) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_clean.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_clean.py new file mode 100644 index 0000000000000000000000000000000000000000..7ddbd28fafad53ed875d114ed2bf38694d177b8c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_clean.py @@ -0,0 +1,421 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda clean`. + +Removes cached package tarballs, index files, package metadata, temporary files, and log files. +""" + +from __future__ import annotations + +import os +import sys +from logging import getLogger +from os.path import isdir, join +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + from collections.abc import Iterable + from typing import Any + +log = getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .actions import ExtendConstAction + from .helpers import add_output_and_prompt_options + + summary = "Remove unused packages and caches." + description = summary + epilog = dals( + """ + Examples:: + + conda clean --tarballs + """ + ) + + p = sub_parsers.add_parser( + "clean", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + removal_target_options = p.add_argument_group("Removal Targets") + removal_target_options.add_argument( + "-a", + "--all", + action="store_true", + help="Remove index cache, lock files, unused cache packages, tarballs, and logfiles.", + ) + removal_target_options.add_argument( + "-i", + "--index-cache", + action="store_true", + help="Remove index cache.", + ) + removal_target_options.add_argument( + "-p", + "--packages", + action="store_true", + help="Remove unused packages from writable package caches. " + "WARNING: This does not check for packages installed using " + "symlinks back to the package cache.", + ) + removal_target_options.add_argument( + "-t", + "--tarballs", + action="store_true", + help="Remove cached package tarballs.", + ) + removal_target_options.add_argument( + "-f", + "--force-pkgs-dirs", + action="store_true", + help="Remove *all* writable package caches. This option is not included with the --all " + "flag. WARNING: This will break environments with packages installed using symlinks " + "back to the package cache.", + ) + removal_target_options.add_argument( + "-c", # for tempfile extension (.c~) + "--tempfiles", + const=sys.prefix, + action=ExtendConstAction, + help=( + "Remove temporary files that could not be deleted earlier due to being in-use. " + "The argument for the --tempfiles flag is a path (or list of paths) to the " + "environment(s) where the tempfiles should be found and removed." + ), + ) + removal_target_options.add_argument( + "-l", + "--logfiles", + action="store_true", + help="Remove log files.", + ) + + add_output_and_prompt_options(p) + + p.set_defaults(func="conda.cli.main_clean.execute") + + return p + + +def _get_size(*parts: str, warnings: list[str] | None) -> int: + path = join(*parts) + try: + stat = os.lstat(path) + except OSError as e: + if warnings is None: + raise + warnings.append(f"WARNING: {path}: {e}") + + # let the user deal with the issue + raise NotImplementedError + else: + # TODO: This doesn't handle packages that have hard links to files within + # themselves, like bin/python3.3 and bin/python3.3m in the Python package + if stat.st_nlink > 1: + raise NotImplementedError + + return stat.st_size + + +def _get_pkgs_dirs(pkg_sizes: dict[str, dict[str, int]]) -> dict[str, tuple[str, ...]]: + return {pkgs_dir: tuple(pkgs) for pkgs_dir, pkgs in pkg_sizes.items()} + + +def _get_total_size(pkg_sizes: dict[str, dict[str, int]]) -> int: + return sum(sum(pkgs.values()) for pkgs in pkg_sizes.values()) + + +def _rm_rf(*parts: str, quiet: bool, verbose: bool) -> None: + from ..gateways.disk.delete import rm_rf + + path = join(*parts) + try: + if rm_rf(path): + if not quiet and verbose: + print(f"Removed {path}") + elif not quiet: + print(f"WARNING: cannot remove, file permissions: {path}") + except OSError as e: + if not quiet: + print(f"WARNING: cannot remove, file permissions: {path}\n{e!r}") + else: + log.info("%r", e) + + +def find_tarballs() -> dict[str, Any]: + from ..base.constants import PARTIAL_EXTENSION + from ..base.context import context + + warnings: list[str] = [] + pkg_sizes: dict[str, dict[str, int]] = {} + for pkgs_dir in find_pkgs_dirs(): + # tarballs are files in pkgs_dir + _, _, files = next(os.walk(pkgs_dir)) + for file in files: + # tarballs end in .tar.bz2, .conda (or .tar.bz2.partial, .conda.partial) + package = file.removesuffix(PARTIAL_EXTENSION) + if not context.plugin_manager.has_package_extension(package): + continue + + # get size + try: + size = _get_size(pkgs_dir, file, warnings=warnings) + except NotImplementedError: + pass + else: + pkg_sizes.setdefault(pkgs_dir, {})[file] = size + + return { + "warnings": warnings, + "pkg_sizes": pkg_sizes, + "pkgs_dirs": _get_pkgs_dirs(pkg_sizes), + "total_size": _get_total_size(pkg_sizes), + } + + +def find_pkgs() -> dict[str, Any]: + warnings: list[str] = [] + pkg_sizes: dict[str, dict[str, int]] = {} + for pkgs_dir in find_pkgs_dirs(): + # pkgs are directories in pkgs_dir + _, pkgs, _ = next(os.walk(pkgs_dir)) + for pkg in pkgs: + # pkgs also have an info directory + if not isdir(join(pkgs_dir, pkg, "info")): + continue + + # get size + try: + size = sum( + _get_size(root, file, warnings=warnings) + for root, _, files in os.walk(join(pkgs_dir, pkg)) + for file in files + ) + except NotImplementedError: + pass + else: + pkg_sizes.setdefault(pkgs_dir, {})[pkg] = size + + return { + "warnings": warnings, + "pkg_sizes": pkg_sizes, + "pkgs_dirs": _get_pkgs_dirs(pkg_sizes), + "total_size": _get_total_size(pkg_sizes), + } + + +def rm_pkgs( + pkgs_dirs: dict[str, tuple[str]], + warnings: list[str], + total_size: int, + pkg_sizes: dict[str, dict[str, int]], + *, + quiet: bool, + verbose: bool, + dry_run: bool, + name: str, +) -> None: + from ..base.context import context + from ..reporters import confirm_yn + from ..utils import human_bytes + + if not quiet and warnings: + for warning in warnings: + print(warning) + + if not any(pkgs for pkgs in pkg_sizes.values()): + if not quiet: + print(f"There are no unused {name} to remove.") + return + + if not quiet: + if verbose: + print(f"Will remove the following {name}:") + for pkgs_dir, pkgs in pkg_sizes.items(): + print(f" {pkgs_dir}") + print(f" {'-' * len(pkgs_dir)}") + for pkg, size in pkgs.items(): + print(f" - {pkg:<40} {human_bytes(size):>10}") + print() + print("-" * 17) + print(f"Total: {human_bytes(total_size):>10}") + print() + else: + count = sum(len(pkgs) for pkgs in pkg_sizes.values()) + print(f"Will remove {count} ({human_bytes(total_size)}) {name}.") + + if dry_run: + return + if not context.json or not context.always_yes: + confirm_yn() + + for pkgs_dir, pkgs in pkg_sizes.items(): + for pkg in pkgs: + _rm_rf(pkgs_dir, pkg, quiet=quiet, verbose=verbose) + + +def find_index_cache() -> list[str]: + files = [] + for pkgs_dir in find_pkgs_dirs(): + # caches are directories in pkgs_dir + path = join(pkgs_dir, "cache") + if isdir(path): + files.append(path) + return files + + +def find_pkgs_dirs() -> list[str]: + from ..core.package_cache_data import PackageCacheData + + return [ + pc.pkgs_dir for pc in PackageCacheData.writable_caches() if isdir(pc.pkgs_dir) + ] + + +def find_tempfiles(paths: Iterable[str]) -> list[str]: + from ..base.constants import CONDA_TEMP_EXTENSIONS + + tempfiles = [] + for path in sorted(set(paths or [sys.prefix])): + # tempfiles are files in path + for root, _, files in os.walk(path): + for file in files: + # tempfiles also end in .c~ or .trash + if not file.endswith(CONDA_TEMP_EXTENSIONS): + continue + + tempfiles.append(join(root, file)) + + return tempfiles + + +def find_logfiles() -> list[str]: + from ..base.constants import CONDA_LOGS_DIR + + files = [] + for pkgs_dir in find_pkgs_dirs(): + # .logs are directories in pkgs_dir + path = join(pkgs_dir, CONDA_LOGS_DIR) + if not isdir(path): + continue + + try: + # logfiles are files in .logs + _, _, logs = next(os.walk(path)) + files.extend([join(path, log) for log in logs]) + except StopIteration: + # StopIteration: .logs is empty + pass + + return files + + +def rm_items( + items: list[str], + *, + quiet: bool, + verbose: bool, + dry_run: bool, + name: str, +) -> None: + from ..base.context import context + from ..reporters import confirm_yn + + if not items: + if not quiet: + print(f"There are no {name} to remove.") + return + + if not quiet: + if verbose: + print(f"Will remove the following {name}:") + for item in items: + print(f" - {item}") + print() + else: + print(f"Will remove {len(items)} {name}.") + + if dry_run: + return + if not context.json or not context.always_yes: + confirm_yn() + + for item in items: + _rm_rf(item, quiet=quiet, verbose=verbose) + + +def _execute(args, parser): + from ..base.context import context + + json_result = {"success": True} + kwargs = { + "quiet": context.json or context.quiet, + "verbose": context.verbose, + "dry_run": context.dry_run, + } + + if args.force_pkgs_dirs: + json_result["pkgs_dirs"] = pkgs_dirs = find_pkgs_dirs() + rm_items(pkgs_dirs, **kwargs, name="package cache(s)") + + # we return here because all other clean operations target individual parts of + # package caches + return json_result + + if not ( + args.all + or args.tarballs + or args.index_cache + or args.packages + or args.tempfiles + or args.logfiles + ): + from ..exceptions import ArgumentError + + raise ArgumentError( + "At least one removal target must be given. See 'conda clean --help'." + ) + + if args.tarballs or args.all: + json_result["tarballs"] = tars = find_tarballs() + rm_pkgs(**tars, **kwargs, name="tarball(s)") + + if args.index_cache or args.all: + cache = find_index_cache() + json_result["index_cache"] = {"files": cache} + rm_items(cache, **kwargs, name="index cache(s)") + + if args.packages or args.all: + json_result["packages"] = pkgs = find_pkgs() + rm_pkgs(**pkgs, **kwargs, name="package(s)") + + if args.tempfiles or args.all: + json_result["tempfiles"] = tmps = find_tempfiles(args.tempfiles) + rm_items(tmps, **kwargs, name="tempfile(s)") + + if args.logfiles or args.all: + json_result["logfiles"] = logs = find_logfiles() + rm_items(logs, **kwargs, name="logfile(s)") + + return json_result + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import context + from .common import stdout_json + + json_result = _execute(args, parser) + if context.json: + stdout_json(json_result) + if args.dry_run: + from ..exceptions import DryRunExit + + raise DryRunExit + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_commands.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..67dd8408c9c8b466d85c14b9ef841c8fa594081e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_commands.py @@ -0,0 +1,44 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Mock CLI implementation for `conda activate`. + +A mock implementation of the activate shell command for better UX. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + p = sub_parsers.add_parser( + "commands", + help=( + "List all available conda subcommands (including those from plugins). " + "Generally only used by tab-completion." + ), + **kwargs, + ) + p.set_defaults(func="conda.cli.main_commands.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from .conda_argparse import find_builtin_commands + from .find_commands import find_commands + + print( + *sorted( + { + *find_builtin_commands(parser), + *find_commands(True), + } + ), + sep="\n", + end="", + ) + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_compare.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..00910565c9d99affab8356abf8bca9c63aeb1ccb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_compare.py @@ -0,0 +1,145 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda compare`. + +Compare the packages in an environment with the packages listed in an environment file. +""" + +from __future__ import annotations + +import logging +import os +from os.path import abspath, expanduser, expandvars +from typing import TYPE_CHECKING + +from ..deprecations import deprecated + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + +log = logging.getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import add_parser_json, add_parser_prefix + + summary = "Compare packages between conda environments." + description = summary + epilog = dals( + """ + Examples: + + Compare packages in the current environment with respect + to 'environment.yml' located in the current working directory:: + + conda compare environment.yml + + Compare packages installed into the environment 'myenv' with respect + to 'environment.yml' in a different directory:: + + conda compare -n myenv path/to/file/environment.yml + + """ + ) + + p = sub_parsers.add_parser( + "compare", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_json(p) + add_parser_prefix(p) + p.add_argument( + "file", + action="store", + help="Path to the environment file that is to be compared against.", + ) + p.set_defaults(func="conda.cli.main_compare.execute") + + return p + + +@deprecated( + "26.3", + "26.9", + addendum="Use `conda.core.prefix_data.PrefixData.map_records` instead.", +) +def get_packages(prefix): + from ..core.prefix_data import PrefixData + from ..exceptions import EnvironmentLocationNotFound + + if not os.path.isdir(prefix): + raise EnvironmentLocationNotFound(prefix) + + return sorted( + PrefixData(prefix, interoperability=True).iter_records(), + key=lambda x: x.name, + ) + + +def compare_packages(active_pkgs, specification_pkgs) -> tuple[int, list[str]]: + from ..models.match_spec import MatchSpec + + errors = [] + for pkg in specification_pkgs: + pkg_spec = MatchSpec(pkg) + if (name := pkg_spec.name) in active_pkgs: + if not pkg_spec.match(active_pkg := active_pkgs[name]): + errors.append( + f"{name} found but mismatch. Specification pkg: {pkg}, " + f"Running pkg: {active_pkg.spec}" + ) + else: + errors.append(f"{name} not found") + if not errors: + return 0, [ + "Success. All the packages in the " + "specification file are present in the environment " + "with matching version and build string." + ] + return 1, errors + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import context + from ..core.prefix_data import PrefixData + from ..gateways.connection.session import CONDA_SESSION_SCHEMES + from .common import stdout_json + + prefix_data = PrefixData.from_context(interoperability=True) + prefix_data.assert_environment() + + url_scheme = args.file.split("://", 1)[0] + if url_scheme in CONDA_SESSION_SCHEMES: + filename = args.file + else: + filename = abspath(expanduser(expandvars(args.file))) + + spec_hook = context.plugin_manager.get_environment_specifier( + source=filename, + name=context.environment_specifier, + ) + spec = spec_hook.environment_spec(filename) + env = spec.env + + active_pkgs = prefix_data.map_records() + specification_pkgs = ( + *env.requested_packages, + *( + package + for packages in env.external_packages.values() + for package in packages + ), + ) + + exitcode, output = compare_packages(active_pkgs, specification_pkgs) + + if context.json: + stdout_json(output) + else: + print("\n".join(map(str, output))) + + return exitcode diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_config.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bee43d082135715db1f048e9fdbaf8a9c3fd6bd7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_config.py @@ -0,0 +1,827 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda config`. + +Allows for programmatically interacting with conda's configuration files (e.g., `~/.condarc`). +""" + +from __future__ import annotations + +import os +import sys +from argparse import SUPPRESS +from collections.abc import Mapping +from itertools import chain +from logging import getLogger +from os.path import isfile, join +from textwrap import wrap +from typing import TYPE_CHECKING + +from ..common.configuration import DEFAULT_CONDARC_FILENAME +from ..exceptions import CouldntParseError +from .condarc import ( + MISSING, + ConfigurationFile, + validate_provided_parameters, +) + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + from collections.abc import Sequence + from pathlib import Path + from typing import Any + +log = getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..base.constants import CONDA_HOMEPAGE_URL + from ..base.context import context, sys_rc_path, user_rc_path + from ..common.constants import NULL + from .helpers import add_parser_json, add_parser_prefix_to_group + + escaped_user_rc_path = user_rc_path.replace("%", "%%") + escaped_sys_rc_path = sys_rc_path.replace("%", "%%") + + summary = "Modify configuration values in .condarc." + description = dals( + f""" + {summary} + + This is modeled after the git config command. Writes to the user .condarc + file ({escaped_user_rc_path}) by default. Use the + --show-sources flag to display all identified configuration locations on + your computer. + + """ + ) + epilog = dals( + f""" + See `conda config --describe` or {CONDA_HOMEPAGE_URL}/docs/config.html + for details on all the options that can go in .condarc. + + Examples: + + Display all configuration values as calculated and compiled:: + + conda config --show + + Display all identified configuration sources:: + + conda config --show-sources + + Print the descriptions of all available configuration + options to your command line:: + + conda config --describe + + Print the description for the "channel_priority" configuration + option to your command line:: + + conda config --describe channel_priority + + Add the conda-canary channel:: + + conda config --add channels conda-canary + + Set the output verbosity to level 3 (highest) for + the current activate environment:: + + conda config --set verbosity 3 --env + + Add the 'conda-forge' channel as a backup to 'defaults':: + + conda config --append channels conda-forge + + """ + ) + + p = sub_parsers.add_parser( + "config", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_json(p) + + # TODO: use argparse.FileType + config_file_location_group = p.add_argument_group( + "Config File Location Selection", + f"Without one of these flags, the user config file at '{escaped_user_rc_path}' is used.", + ) + location = config_file_location_group.add_mutually_exclusive_group() + location.add_argument( + "--system", + action="store_true", + help=f"Write to the system .condarc file at '{escaped_sys_rc_path}'.", + ) + location.add_argument( + "--env", + action="store_true", + help="Write to the active conda environment .condarc file ({}). " + "If no environment is active, write to the user config file ({})." + "".format( + context.active_prefix or "", + escaped_user_rc_path, + ), + ) + location.add_argument("--file", action="store", help="Write to the given file.") + add_parser_prefix_to_group(location) + + # XXX: Does this really have to be mutually exclusive. I think the below + # code will work even if it is a regular group (although combination of + # --add and --remove with the same keys will not be well-defined). + _config_subcommands = p.add_argument_group("Config Subcommands") + config_subcommands = _config_subcommands.add_mutually_exclusive_group() + config_subcommands.add_argument( + "--show", + nargs="*", + default=None, + help="Display configuration values as calculated and compiled. " + "If no arguments given, show information for all configuration values.", + ) + config_subcommands.add_argument( + "--show-sources", + action="store_true", + help="Display all identified configuration sources.", + ) + config_subcommands.add_argument( + "--validate", + action="store_true", + help="Validate all configuration sources. Iterates over all .condarc files " + "and checks for parsing errors.", + ) + config_subcommands.add_argument( + "--describe", + nargs="*", + default=None, + help="Describe given configuration parameters. If no arguments given, show " + "information for all configuration parameters.", + ) + config_subcommands.add_argument( + "--write-default", + action="store_true", + help="Write the default configuration to a file. " + "Equivalent to `conda config --describe > ~/.condarc`.", + ) + + _config_modifiers = p.add_argument_group("Config Modifiers") + config_modifiers = _config_modifiers.add_mutually_exclusive_group() + config_modifiers.add_argument( + "--get", + nargs="*", + action="store", + help="Get a configuration value.", + default=None, + metavar="KEY", + ) + config_modifiers.add_argument( + "--append", + nargs=2, + action="append", + help="""Add one configuration value to the end of a list key.""", + default=[], + metavar=("KEY", "VALUE"), + ) + config_modifiers.add_argument( + "--prepend", + "--add", + nargs=2, + action="append", + help="""Add one configuration value to the beginning of a list key.""", + default=[], + metavar=("KEY", "VALUE"), + ) + config_modifiers.add_argument( + "--set", + nargs=2, + action="append", + help="""Set a boolean or string key.""", + default=[], + metavar=("KEY", "VALUE"), + ) + config_modifiers.add_argument( + "--remove", + nargs=2, + action="append", + help="""Remove a configuration value from a list key. + This removes all instances of the value.""", + default=[], + metavar=("KEY", "VALUE"), + ) + config_modifiers.add_argument( + "--remove-key", + action="append", + help="""Remove a configuration key (and all its values).""", + default=[], + metavar="KEY", + ) + config_modifiers.add_argument( + "--stdin", + action="store_true", + help="Apply configuration information given in yaml format piped through stdin.", + ) + + p.add_argument( + "-f", + "--force", + action="store_true", + default=NULL, + help=SUPPRESS, # TODO: No longer used. Remove in a future release. + ) + + p.set_defaults(func="conda.cli.main_config.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from .. import CondaError + + try: + return execute_config(args, parser) + except (CouldntParseError, NotImplementedError) as e: + raise CondaError(e) + + +def format_dict(d): + from ..common.compat import isiterable + from ..common.configuration import pretty_list, pretty_map + + lines = [] + for k, v in d.items(): + if isinstance(v, Mapping): + if v: + lines.append(f"{k}:") + lines.append(pretty_map(v)) + else: + lines.append(f"{k}: {{}}") + elif isiterable(v): + if v: + lines.append(f"{k}:") + lines.append(pretty_list(v)) + else: + lines.append(f"{k}: []") + else: + lines.append("{}: {}".format(k, v if v is not None else "None")) + return lines + + +def parameter_description_builder(name, context=None, plugins=False): + from ..common.serialize import json, yaml + + # Keeping this for backward-compatibility, in case no context instance is provided + if context is None: + from ..base.context import context + + name_prefix = "plugins." if plugins else "" + + builder = [] + details = context.describe_parameter(name) + aliases = details["aliases"] + string_delimiter = details.get("string_delimiter") + element_types = details["element_types"] + default_value_str = json.dumps(details["default_value"]) + + if details["parameter_type"] == "primitive": + builder.append( + "{} ({})".format( + f"{name_prefix}{name}", + ", ".join(sorted(set(element_types))), + ) + ) + else: + builder.append( + "{} ({}: {})".format( + f"{name_prefix}{name}", + details["parameter_type"], + ", ".join(sorted(set(element_types))), + ) + ) + + if aliases: + builder.append(" aliases: {}".format(", ".join(aliases))) + if string_delimiter: + builder.append(f" env var string delimiter: '{string_delimiter}'") + + builder.extend(" " + line for line in wrap(details["description"], 70)) + + builder.append("") + builder = ["# " + line for line in builder] + + # If we are dealing with a plugin parameter, we need to nest it + # instead of having it at the top level (YAML-wise). + if plugins: + yaml_content = yaml.dumps({"plugins": {name: json.loads(default_value_str)}}) + else: + yaml_content = yaml.dumps({name: json.loads(default_value_str)}) + + builder.extend(yaml_content.strip().split("\n")) + + builder = ["# " + line for line in builder] + builder.append("") + return builder + + +def describe_all_parameters(context=None, plugins=False) -> str: + """ + Return a string with the descriptions of all available configuration + + When ``context`` has no parameters, this function returns ``""`` + """ + # Keeping this for backward-compatibility, in case no context instance is provided + if context is None: + from ..base.context import context + + if not context.parameter_names: + return "" + + builder = [] + skip_categories = ("CLI-only", "Hidden and Undocumented") + for category, parameter_names in context.category_map.items(): + if category in skip_categories: + continue + builder.append("# ######################################################") + builder.append(f"# ## {category:^48} ##") + builder.append("# ######################################################") + builder.append("") + builder.extend( + chain.from_iterable( + parameter_description_builder(name, context, plugins=plugins) + for name in parameter_names + ) + ) + builder.append("") + return "\n".join(builder) + + +def print_config_item(key, value): + stdout_write = getLogger("conda.stdout").info + if isinstance(value, (dict,)): + for k, v in value.items(): + print_config_item(key + "." + k, v) + elif isinstance(value, (bool, int, str)): + stdout_write(" ".join(("--set", key, str(value)))) + elif isinstance(value, (list, tuple)): + # Note, since `conda config --add` prepends, print `--add` commands in + # reverse order (using repr), so that entering them in this order will + # recreate the same file. + numitems = len(value) + for q, item in enumerate(reversed(value)): + if key == "channels" and q in (0, numitems - 1): + stdout_write( + " ".join( + ( + "--add", + key, + repr(item), + " # lowest priority" if q == 0 else " # highest priority", + ) + ) + ) + else: + stdout_write(" ".join(("--add", key, repr(item)))) + + +def set_keys(*args: tuple[str, Any], path: str | os.PathLike[str] | Path) -> None: + """ + Set multiple configuration keys in a file. + + :param args: Variable number of (key, value) tuples to set. + :param path: Path to the configuration file. + """ + config = ConfigurationFile(path) + for key, value in args: + config.set_key(key, value) + config.write() + + +def execute_config(args: Namespace, parser: ArgumentParser) -> int | None: + """ + Execute the conda config command based on provided arguments. + + Handles various config subcommands including show, show-sources, describe, + validate, write-default, and modification operations (add, set, remove, etc.). + + :param args: Parsed command line arguments. + :param parser: Argument parser instance. + """ + from .. import CondaError + from ..base.context import ( + context, + sys_rc_path, + user_rc_path, + ) + from ..common.io import timeout + from ..common.serialize import json, yaml + from ..core.prefix_data import PrefixData + + # Override context for --file operations with --show/--describe + if args.file and (args.show is not None or args.describe is not None): + from ..base.context import Context + + context = Context(search_path=(args.file,), argparse_args=args) + + stdout_write = getLogger("conda.stdout").info + stderr_write = getLogger("conda.stderr").info + get_key_pairs = [] + json_warnings = [] + + if args.show_sources: + if context.json: + stdout_write( + json.dumps( + { + str(source): values + for source, values in context.collect_all().items() + }, + sort_keys=True, + ) + ) + else: + lines = [] + for source, reprs in context.collect_all().items(): + lines.append(f"==> {source} <==") + lines.extend(format_dict(reprs)) + lines.append("") + stdout_write("\n".join(lines)) + return + + if args.show is not None: + if args.show: + provided_parameters = tuple( + name for name in args.show if not name.startswith("plugins.") + ) + provided_plugin_parameters = tuple( + name.replace("plugins.", "") + for name in args.show + if name.startswith("plugins.") + ) + + validate_provided_parameters( + provided_parameters, provided_plugin_parameters, context + ) + provided_parameters = tuple( + dict.fromkeys( + context.name_for_alias(name) or name for name in provided_parameters + ) + ) + + else: + provided_parameters = context.list_parameters() + provided_plugin_parameters = context.plugins.list_parameters() + + d = {key: getattr(context, key) for key in provided_parameters} + + d["plugins"] = {} + + # sort to make sure "plugins" appears in the right spot + d = {key: value for key, value in sorted(d.items())} + + for key in provided_plugin_parameters: + value = getattr(context.plugins, key) + if isinstance(value, Mapping): + d["plugins"][key] = dict(value) + elif isinstance(value, tuple) and len(value) == 0: + d["plugins"][key] = [] + else: + d["plugins"][key] = value + + if not d["plugins"]: + del d["plugins"] + + if context.json: + stdout_write(json.dumps(d, sort_keys=True)) + else: + # Add in custom formatting + if "custom_channels" in d: + d["custom_channels"] = { + channel.name: f"{channel.scheme}://{channel.location}" + for channel in d["custom_channels"].values() + } + if "custom_multichannels" in d: + from ..common.io import dashlist + + d["custom_multichannels"] = { + multichannel_name: dashlist(channels, indent=4) + for multichannel_name, channels in d["custom_multichannels"].items() + } + if "channel_settings" in d: + ident = " " * 4 + d["channel_settings"] = tuple( + f"\n{ident}".join(format_dict(mapping)) + for mapping in d["channel_settings"] + ) + + stdout_write("\n".join(format_dict(d))) + context.validate_configuration() + context.plugins.validate_configuration() + return + + if args.describe is not None: + if args.describe: + provided_parameters = tuple( + name for name in args.describe if not name.startswith("plugins.") + ) + provided_plugin_parameters = tuple( + name.replace("plugins.", "") + for name in args.describe + if name.startswith("plugins.") + ) + validate_provided_parameters( + provided_parameters, provided_plugin_parameters, context + ) + provided_parameters = tuple( + dict.fromkeys( + context.name_for_alias(name) or name for name in provided_parameters + ) + ) + + if context.json: + json_descriptions = [ + context.describe_parameter(name) for name in provided_parameters + ] + [ + context.plugins.describe_parameter(name) + for name in provided_plugin_parameters + ] + stdout_write( + json.dumps( + json_descriptions, + sort_keys=True, + ) + ) + else: + builder = [] + builder.extend( + chain.from_iterable( + parameter_description_builder(name, context) + for name in provided_parameters + ) + ) + builder.extend( + chain.from_iterable( + parameter_description_builder( + name, context.plugins, plugins=True + ) + for name in provided_plugin_parameters + ) + ) + stdout_write("\n".join(builder)) + else: + if context.json: + skip_categories = ("CLI-only", "Hidden and Undocumented") + provided_parameters = sorted( + chain.from_iterable( + parameter_names + for category, parameter_names in context.category_map.items() + if category not in skip_categories + ) + ) + stdout_write( + json.dumps( + [ + context.describe_parameter(name) + for name in provided_parameters + ], + sort_keys=True, + ) + ) + else: + stdout_write(describe_all_parameters(context)) + stdout_write(describe_all_parameters(context.plugins, plugins=True)) + return + + if args.validate: + context.validate_all() + return + + if args.system: + rc_path = sys_rc_path + elif args.env: + if context.active_prefix: + rc_path = join(context.active_prefix, DEFAULT_CONDARC_FILENAME) + else: + rc_path = user_rc_path + elif args.file: + rc_path = args.file + elif args.prefix or args.name: + prefix_data = PrefixData.from_context() + prefix_data.assert_environment() + rc_path = str(prefix_data.prefix_path / DEFAULT_CONDARC_FILENAME) + else: + rc_path = user_rc_path + + if args.write_default: + if isfile(rc_path): + with open(rc_path) as fh: + data = fh.read().strip() + if data: + raise CondaError( + f"The file '{rc_path}' " + "already contains configuration information.\n" + "Remove the file to proceed.\n" + "Use `conda config --describe` to display default configuration." + ) + + with open(rc_path, "w") as fh: + fh.write(describe_all_parameters(context)) + fh.write(describe_all_parameters(context.plugins, plugins=True)) + return + + rc_config = ConfigurationFile( + path=rc_path, + context=context, + warning_handler=lambda msg: json_warnings.append(msg) + if context.json + else stderr_write(msg), + ) + + # read existing condarc + if os.path.exists(rc_path): + rc_config.read() + elif os.path.exists(sys_rc_path): + # In case the considered rc file doesn't exist, fall back to the system rc + rc_config.read(sys_rc_path) + + # Get + if args.get is not None: + context.validate_all() + for key in args.get or sorted(rc_config.content.keys()): + name, value = rc_config.get_key(key) + if value is not MISSING: + get_key_pairs.append((name, value)) + + if args.stdin: + content = timeout(5, sys.stdin.read) + if not content: + return + try: + # round trip load required because... we need to round trip + parsed = yaml.loads(content) + rc_config.content.update(parsed) + except Exception: # pragma: no cover + from ..exceptions import ParseError + + raise ParseError(f"invalid yaml content:\n{content}") + + # prepend, append, add + for arg, prepend in zip((args.prepend, args.append), (True, False)): + for key, item in arg: + rc_config.add(key, item, prepend=prepend) + + # Set + for key, item in args.set: + rc_config.set_key(key, item) + + # Remove + for key, item in args.remove: + rc_config.remove_item(key, item) + + # Remove Key + for key in args.remove_key: + rc_config.remove_key(key) + + # config.rc_keys + if not args.get: + rc_config.write() + + if context.json: + from .common import stdout_json_success + + stdout_json_success( + rc_path=rc_path, warnings=json_warnings, get=dict(get_key_pairs) + ) + else: + for k, v in get_key_pairs: + print_config_item(k, v) + + +# Deprecated private functions - moved to conda.cli.condarc.ConfigurationFile +from ..deprecations import deprecated + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.ConfigurationFile.key_exists() instead.", +) +def _key_exists(key: str, warnings: list[str], context=None) -> bool: + """Deprecated. Use ConfigurationFile.key_exists() instead.""" + from .condarc import ConfigurationFile + + config = ConfigurationFile( + context=context, + content={}, + warning_handler=lambda msg: warnings.append(msg), + ) + return config.key_exists(key) + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.ConfigurationFile.get_key() instead.", +) +def _get_key( + key: str, + warnings: list[str], + config: dict[str, Any], + context=None, +) -> tuple[str, Any]: + """Deprecated. Use ConfigurationFile.get_key() instead.""" + from .condarc import MISSING, ConfigurationFile + + config_file = ConfigurationFile( + context=context, + content=config, + warning_handler=lambda msg: warnings.append(msg), + ) + key, value = config_file.get_key(key) + + # Return None instead of MISSING for backward compatibility + if value is MISSING: + return key, None + return key, value + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.ConfigurationFile.set_key() instead.", +) +def _set_key(key: str, item: Any, config: dict) -> None: + """Deprecated. Use ConfigurationFile.set_key() instead.""" + from .condarc import ConfigurationFile + + config_file = ConfigurationFile(content=config) + config_file.set_key(key, item) + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.ConfigurationFile.remove_item() instead.", +) +def _remove_item(key: str, item: Any, config: dict) -> None: + """Deprecated. Use ConfigurationFile.remove_item() instead.""" + from .condarc import ConfigurationFile + + config_file = ConfigurationFile(content=config) + config_file.remove_item(key, item) + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.ConfigurationFile.remove_key() instead.", +) +def _remove_key(key: str, config: dict) -> None: + """Deprecated. Use ConfigurationFile.remove_key() instead.""" + from .condarc import ConfigurationFile + + config_file = ConfigurationFile(content=config) + config_file.remove_key(key) + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.ConfigurationFile.read() instead.", +) +def _read_rc(path: str | os.PathLike[str] | Path) -> dict: + """Deprecated. Use ConfigurationFile.read() instead.""" + from .condarc import ConfigurationFile + + config = ConfigurationFile(path=path) + return config.read() + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.ConfigurationFile.write() instead.", +) +def _write_rc(path: str | os.PathLike[str] | Path, config: dict) -> None: + """Deprecated. Use ConfigurationFile.write() instead.""" + from .condarc import ConfigurationFile + + config_file = ConfigurationFile(path=path, content=config) + config_file.write() + + +@deprecated( + "26.9", + "27.3", + addendum="Use conda.cli.condarc.validate_provided_parameters() instead.", +) +def _validate_provided_parameters( + parameters: Sequence[str], + plugin_parameters: Sequence[str], + context, +) -> None: + """Deprecated. Use validate_provided_parameters() instead.""" + from .condarc import validate_provided_parameters + + validate_provided_parameters(parameters, plugin_parameters, context) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_create.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_create.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9c36e9364db0cadc529633212f52231d432c44 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_create.py @@ -0,0 +1,176 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda create`. + +Creates new conda environments with the specified packages. +""" + +from __future__ import annotations + +from logging import getLogger +from typing import TYPE_CHECKING + +from ..notices import notices + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + +log = getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..common.constants import NULL + from .actions import NullCountAction + from .helpers import ( + add_parser_create_install_update, + add_parser_default_packages, + add_parser_platform, + add_parser_solver, + ) + + summary = "Create a new conda environment from a list of specified packages. " + description = dals( + f""" + {summary} + + To use the newly-created environment, use 'conda activate envname'. + This command requires either the -n NAME or -p PREFIX option unless + --dry-run or --download-only is specified. + """ + ) + epilog = dals( + """ + Examples: + + Create an environment containing the package 'sqlite':: + + conda create -n myenv sqlite + + Create an environment (env2) as a clone of an existing environment (env1):: + + conda create -n env2 --clone path/to/file/env1 + + """ + ) + p = sub_parsers.add_parser( + "create", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + p.add_argument( + "--clone", + action="store", + help="Create a new environment as a copy of an existing local environment.", + metavar="ENV", + ) + solver_mode_options, _, channel_options = add_parser_create_install_update(p) + add_parser_default_packages(solver_mode_options) + add_parser_platform(channel_options) + add_parser_solver(solver_mode_options) + p.add_argument( + "--dev", + action=NullCountAction, + help="Use `sys.executable -m conda` in wrapper scripts instead of CONDA_EXE. " + "This is mainly for use during tests where we test new conda sources " + "against old Python versions.", + dest="dev", + default=NULL, + ) + p.set_defaults(func="conda.cli.main_create.execute") + + return p + + +@notices +def execute(args: Namespace, parser: ArgumentParser) -> int: + import os + from tempfile import mktemp + + from ..base.constants import UNUSED_ENV_NAME + from ..base.context import context + from ..core.prefix_data import PrefixData + from ..exceptions import ArgumentError, CondaValueError, TooManyArgumentsError + from ..gateways.disk.delete import rm_rf + from ..reporters import confirm_yn + from .common import ( + print_activate, + validate_environment_files_consistency, + validate_subdir_config, + ) + from .install import install, install_clone + + # Ensure provided combination of command line argments are valid + # At least one of the arguments -n/--name -p/--prefix is required + if not args.name and not args.prefix: + if context.dry_run or context.download_only: + args.prefix = os.path.join(mktemp(), UNUSED_ENV_NAME) + context.__init__(argparse_args=args) + else: + raise ArgumentError( + "one of the arguments -n/--name -p/--prefix is required" + ) + + # If the --clone argument is provided, users must not provide any other + # package specification. That includes providing the --file argument or + # a list of packages + if args.clone: + if args.packages: + raise TooManyArgumentsError( + 0, + len(args.packages), + list(args.packages), + "Did not expect any new packages or arguments for `--clone`.", + ) + elif args.file: + raise TooManyArgumentsError( + 0, + len(args.file), + list(args.file), + "`--file` and `--clone` arguments are mutually exclusive.", + ) + prefix_data = PrefixData.from_context(validate=True) + + if prefix_data.is_environment(): + if context.dry_run: + # Taking the "easy" way out, rather than trying to fake removing + # the existing environment before creating a new one. + raise CondaValueError( + "Cannot `create --dry-run` with an existing conda environment" + ) + confirm_yn( + f"WARNING: A conda environment already exists at '{context.target_prefix}'\n\n" + "Remove existing environment?\nThis will remove ALL directories contained within " + "this specified prefix directory, including any other conda environments.\n\n", + default="no", + dry_run=False, + ) + log.info("Removing existing environment %s", context.target_prefix) + rm_rf(context.target_prefix) + elif prefix_data.exists(): + confirm_yn( + f"WARNING: A directory already exists at the target location '{context.target_prefix}'\n" + "but it is not a conda environment.\n" + "Continue creating environment", + default="no", + dry_run=False, + ) + + # Ensure the subdir config is valid + validate_subdir_config() + + # Validate that input files are of the same format type + validate_environment_files_consistency(args.file) + + # Run appropriate install + if args.clone: + install_clone(args, parser) + else: + install(args, parser, "create") + # Run post-install steps applicable to all new environments + prefix_data.set_nonadmin() + print_activate(args.name or context.target_prefix) + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_env.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8003c697553e7798bee4bf57b0c773987c92b1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env.py @@ -0,0 +1,48 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Entry point for all conda-env subcommands.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from . import main_export + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from . import ( + main_env_config, + main_env_create, + main_env_list, + main_env_remove, + main_env_update, + ) + + p = sub_parsers.add_parser( + "env", + help="Create and manage conda environments.", + **kwargs, + ) + + env_parsers = p.add_subparsers( + metavar="command", + dest="cmd", + ) + main_env_config.configure_parser(env_parsers) + main_env_create.configure_parser(env_parsers) + main_export.configure_parser(env_parsers) + main_env_list.configure_parser(env_parsers) + main_env_remove.configure_parser(env_parsers) + main_env_update.configure_parser(env_parsers) + + p.set_defaults(func="conda.cli.main_env.execute") + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + parser.parse_args(["env", "--help"]) + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_config.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_config.py new file mode 100644 index 0000000000000000000000000000000000000000..02a5ddf4cf1c014c20a33343e6ab4249b09b8e74 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_config.py @@ -0,0 +1,44 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda-env config`. + +Allows for programmatically interacting with conda-env's configuration files (e.g., `~/.condarc`). +""" + +from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .main_env_vars import configure_parser as configure_vars_parser + + summary = "Configure a conda environment." + description = summary + epilog = dals( + """ + Examples:: + + conda env config vars list + conda env config --append channels conda-forge + + """ + ) + + p = sub_parsers.add_parser( + "config", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + p.set_defaults(func="conda.cli.main_env_config.execute") + config_subparser = p.add_subparsers() + configure_vars_parser(config_subparser) + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + parser.parse_args(["env", "config", "--help"]) + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_create.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_create.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa9af7bebce16333e87818c8e3e8d6db31ffa71 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_create.py @@ -0,0 +1,211 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda-env create`. + +Creates new conda environments with the specified packages. +""" + +from argparse import ( + ArgumentParser, + Namespace, + _SubParsersAction, +) +from pathlib import Path + +from .. import CondaError +from ..cli.main_config import set_keys +from ..common.configuration import DEFAULT_CONDARC_FILENAME +from ..notices import notices + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import ( + add_output_and_prompt_options, + add_parser_default_packages, + add_parser_environment_specifier, + add_parser_networking, + add_parser_platform, + add_parser_prefix, + add_parser_solver, + ) + + summary = "Create an environment based on an environment definition file." + description = dals( + f""" + {summary} + + If using an environment.yml file (the default), you can name the + environment in the first line of the file with 'name: envname' or + you can specify the environment name in the CLI command using the + -n/--name argument. The name specified in the CLI will override + the name specified in the environment.yml file. + + Unless you are in the directory containing the environment definition + file, use -f to specify the file path of the environment definition + file you want to use. + + """ + ) + epilog = dals( + """ + Examples:: + + conda env create + conda env create -n envname + conda env create folder/envname + conda env create -f /path/to/environment.yml + conda env create -f /path/to/requirements.txt -n envname + conda env create -f /path/to/requirements.txt -p /home/user/envname + + """ + ) + + p = sub_parsers.add_parser( + "create", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + p.add_argument( + "-f", + "--file", + action="store", + help="Environment definition file (default: environment.yml)", + default="environment.yml", + ) + + # Add name and prefix args + add_parser_prefix(p) + + # Add networking args + add_parser_networking(p) + + # Add environment spec plugin args + add_parser_environment_specifier(p) + + add_parser_default_packages(p) + add_output_and_prompt_options(p) + add_parser_solver(p) + add_parser_platform(p) + + p.set_defaults(func="conda.cli.main_env_create.execute") + + return p + + +@notices +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..auxlib.ish import dals + from ..base.context import context, determine_target_prefix + from ..common.serialize import json + from ..core.prefix_data import PrefixData + from ..env.env import print_result + from ..env.installers.base import get_installer + from ..exceptions import CondaEnvException, InvalidInstaller + from ..gateways.disk.delete import rm_rf + from .common import validate_file_exists + + # validate incoming arguments + validate_file_exists(args.file) + + # detect the file format and get the env representation + spec_hook = context.plugin_manager.get_environment_specifier( + source=args.file, + name=context.environment_specifier, + ) + spec = spec_hook.environment_spec(args.file) + env = spec.env + + # FIXME conda code currently requires args to have a name or prefix + # don't overwrite name if it's given. gh-254 + if args.prefix is None and args.name is None: + if env.name is None: # requirements.txt won't populate Environment.name + msg = dals( + """ + Unable to create environment + Please re-run this command with one of the following options: + * Provide an environment name via --name or -n + * Provide a path on disk via --prefix or -p + """ + ) + raise CondaEnvException(msg) + args.name = env.name + + prefix = determine_target_prefix(context, args) + prefix_data = PrefixData(prefix) + + if args.yes and not prefix_data.is_base() and prefix_data.exists(): + rm_rf(prefix) + + prefix_data.validate_path() + prefix_data.validate_name() + + # TODO, add capability + # common.ensure_override_channels_requires_channel(args) + # channel_urls = args.channel or () + + result = {"conda": None, "pip": None} + + args_packages = ( + context.create_default_packages if not args.no_default_packages else [] + ) + + if args.dry_run: + installer_type = "conda" + installer = get_installer(installer_type) + + pkg_specs = [*env.requested_packages, *args_packages] + + solved_env = installer.dry_run(pkg_specs, args, env) + if args.json: + print(json.dumps(solved_env.to_dict())) + else: + print(solved_env.to_yaml(), end="") + + else: + if args_packages: + installer_type = "conda" + installer = get_installer(installer_type) + result[installer_type] = installer.install(prefix, args_packages, args, env) + + # install conda packages + installer_type = "conda" + installer = get_installer(installer_type) + result[installer_type] = installer.install( + prefix, env.requested_packages, args, env + ) + + # install all other external packages + for installer_type, pkg_specs in env.external_packages.items(): + try: + installer = get_installer(installer_type) + result[installer_type] = installer.install(prefix, pkg_specs, args, env) + except InvalidInstaller: + raise CondaError( + dals( + f""" + Unable to install package for {installer_type}. + + Please double check and ensure your dependencies file has + the correct spelling. You might also try installing the + conda-env-{installer_type} package to see if provides + the required installer. + """ + ) + ) + + if context.subdir != context._native_subdir(): + set_keys( + ("subdir", context.subdir), + path=Path(prefix, DEFAULT_CONDARC_FILENAME), + ) + + if env.variables: + prefix_data.set_environment_env_vars(env.variables) + + prefix_data.set_nonadmin() + print_result(args, prefix, result) + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_list.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_list.py new file mode 100644 index 0000000000000000000000000000000000000000..048990df42cd2f0b7fc7e63b8029e68a0b960e8b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_list.py @@ -0,0 +1,53 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda-env list`, now aliased to `conda info --envs`. + +Lists available conda environments. +""" + +from argparse import ArgumentParser, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import add_parser_json + + summary = "An alias for `conda info --envs`. Lists all conda environments." + description = summary + epilog = dals( + """ + Examples:: + + conda env list + conda env list --json + conda env list --size + + """ + ) + p = sub_parsers.add_parser( + "list", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + add_parser_json(p) + + p.add_argument( + "--size", + action="store_true", + help="Show conda-managed disk usage for each environment (excludes untracked files created after installation).", + ) + + p.set_defaults( + func="conda.cli.main_info.execute", + # The following are the necessary default args for the `conda info` command + envs=True, + base=False, + unsafe_channels=False, + system=False, + all=False, + ) + + return p diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_remove.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_remove.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f70e8f4272e280c2a58b67c6d15b3568f9b345 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_remove.py @@ -0,0 +1,71 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda-env remove`. + +Removes the specified conda environment. +""" + +from argparse import ( + ArgumentParser, + _SubParsersAction, +) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import ( + add_output_and_prompt_options, + add_parser_frozen_env, + add_parser_prefix, + add_parser_solver, + ) + + summary = "Remove an environment." + description = dals( + f""" + {summary} + + Removes a provided environment. You must deactivate the existing + environment before you can remove it. + + """ + ) + epilog = dals( + """ + Examples:: + + conda env remove --name FOO + conda env remove -n FOO + + """ + ) + + p = sub_parsers.add_parser( + "remove", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + add_parser_frozen_env(p) + add_parser_prefix(p) + add_parser_solver(p) + add_output_and_prompt_options(p) + + p.set_defaults( + func="conda.cli.main_remove.execute", + all=True, + channel=None, + features=None, + override_channels=None, + use_local=None, + use_cache=None, + offline=None, + package_names=[], + force=True, + pinned=None, + keep_env=False, + ) + + return p diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_update.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_update.py new file mode 100644 index 0000000000000000000000000000000000000000..eda814582ae5ca691dc877f721a1da7bdef9f08b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_update.py @@ -0,0 +1,181 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda-env update`. + +Updates the conda environments with the specified packages. +""" + +import os +from argparse import ( + ArgumentParser, + Namespace, + _SubParsersAction, +) + +from .. import CondaError +from ..notices import notices + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import ( + add_parser_environment_specifier, + add_parser_frozen_env, + add_parser_json, + add_parser_prefix, + add_parser_solver, + ) + + summary = "Update the current environment based on environment file." + description = summary + epilog = dals( + """ + Examples:: + + conda env update + conda env update -n=foo + conda env update -f=/path/to/environment.yml + conda env update --name=foo --file=environment.yml + conda env update vader/deathstar + + """ + ) + + p = sub_parsers.add_parser( + "update", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + # Add environment spec plugin args + add_parser_environment_specifier(p) + + add_parser_frozen_env(p) + add_parser_prefix(p) + p.add_argument( + "-f", + "--file", + action="store", + help="environment definition (default: environment.yml)", + default="environment.yml", + ) + p.add_argument( + "--prune", + action="store_true", + default=False, + help="remove installed packages not defined in environment.yml", + ) + + add_parser_json(p) + add_parser_solver(p) + p.set_defaults(func="conda.cli.main_env_update.execute") + + return p + + +@notices +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..auxlib.ish import dals + from ..base.context import context, determine_target_prefix + from ..core.prefix_data import PrefixData + from ..env.env import print_result + from ..env.installers.base import get_installer + from ..exceptions import CondaEnvException, InvalidInstaller + from .common import validate_file_exists + + # validate incoming arguments + validate_file_exists(args.file) + + # detect the file format and get the env representation + spec_hook = context.plugin_manager.get_environment_specifier( + source=args.file, + name=context.environment_specifier, + ) + spec = spec_hook.environment_spec(args.file) + env = spec.env + + if not (args.name or args.prefix): + if not env.name: + # Note, this is a hack for get_prefix that assumes argparse results + # TODO Refactor common.get_prefix + name = os.environ.get("CONDA_DEFAULT_ENV", False) + if not name: + msg = dals( + """ + Unable to determine environment + + Please re-run this command with one of the following options: + + * Provide an environment name via --name or -n + * Provide an environment path via --prefix or -p + * Re-run this command inside an activated conda environment. + """ + ) + # TODO Add json support + raise CondaEnvException(msg) + + # Note: stubbing out the args object as all of the + # conda.cli.common code thinks that name will always + # be specified. + args.name = env.name + + prefix = determine_target_prefix(context, args) + prefix_data = PrefixData(prefix) + if prefix_data.is_environment(): + prefix_data.assert_writable() + if context.protect_frozen_envs: + prefix_data.assert_not_frozen() + + # CAN'T Check with this function since it assumes we will create prefix. + # cli_install.check_prefix(prefix, json=args.json) + + # TODO, add capability + # common.ensure_override_channels_requires_channel(args) + # channel_urls = args.channel or () + + # create installers before running any of them + # to avoid failure to import after the file being deleted + # e.g. due to conda_env being upgraded or Python version switched. + installers = {} + + # Ensure we have all the right external package installers before starting + # to install anything. + for installer_type in env.external_packages: + try: + installers[installer_type] = get_installer(installer_type) + except InvalidInstaller: + raise CondaError( + dals( + f""" + Unable to install package for {0}. + + Please double check and ensure you dependencies file has + the correct spelling. You might also try installing the + conda-env-{0} package to see if provides the required + installer. + """ + ) + ) + + result = {"conda": None, "pip": None} + # install conda packages + if env.requested_packages: + installer_type = "conda" + installer = get_installer(installer_type) + result[installer_type] = installer.install( + prefix, env.requested_packages, args, env + ) + # install all other external packages + for installer_type, specs in env.external_packages.items(): + installer = installers[installer_type] + result[installer_type] = installer.install(prefix, specs, args, env) + + if env.variables: + prefix_data.set_environment_env_vars(env.variables) + + prefix_data.set_nonadmin() + print_result(args, prefix, result) + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_vars.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..844a4c404711e0b58a0bbd59542316e9f5c89bf6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_env_vars.py @@ -0,0 +1,169 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda-env config vars`. + +Allows for configuring conda-env's vars. +""" + +from argparse import ( + ArgumentParser, + Namespace, + _SubParsersAction, +) +from os.path import lexists + +from ..base.context import context, determine_target_prefix +from ..core.prefix_data import PrefixData +from ..exceptions import EnvironmentLocationNotFound + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import add_parser_json, add_parser_prefix + + var_summary = ( + "Interact with environment variables associated with Conda environments." + ) + var_description = var_summary + var_epilog = dals( + """ + Examples:: + + conda env config vars list -n my_env + conda env config vars set MY_VAR=something OTHER_THING=ohhhhya + conda env config vars unset MY_VAR + + """ + ) + + var_parser = sub_parsers.add_parser( + "vars", + help=var_summary, + description=var_description, + epilog=var_epilog, + **kwargs, + ) + var_subparser = var_parser.add_subparsers() + + list_summary = "List environment variables for a conda environment." + list_description = list_summary + list_epilog = dals( + """ + Example:: + + conda env config vars list -n my_env + + """ + ) + + list_parser = var_subparser.add_parser( + "list", + help=list_summary, + description=list_description, + epilog=list_epilog, + ) + add_parser_prefix(list_parser) + add_parser_json(list_parser) + list_parser.set_defaults(func="conda.cli.main_env_vars.execute_list") + + set_summary = "Set environment variables for a conda environment." + set_description = set_summary + set_epilog = dals( + """ + Example:: + + conda env config vars set MY_VAR=weee + + """ + ) + + set_parser = var_subparser.add_parser( + "set", + help=set_summary, + description=set_description, + epilog=set_epilog, + ) + + set_parser.add_argument( + "vars", + action="store", + nargs="*", + help="Environment variables to set in the form = separated by spaces", + ) + add_parser_prefix(set_parser) + set_parser.set_defaults(func="conda.cli.main_env_vars.execute_set") + + unset_summary = "Unset environment variables for a conda environment." + unset_description = unset_summary + unset_epilog = dals( + """ + Example:: + + conda env config vars unset MY_VAR + + """ + ) + unset_parser = var_subparser.add_parser( + "unset", + help=unset_summary, + description=unset_description, + epilog=unset_epilog, + ) + unset_parser.add_argument( + "vars", + action="store", + nargs="*", + help="Environment variables to unset in the form separated by spaces", + ) + add_parser_prefix(unset_parser) + unset_parser.set_defaults(func="conda.cli.main_env_vars.execute_unset") + + +def execute_list(args: Namespace, parser: ArgumentParser) -> int: + from . import common + + prefix = determine_target_prefix(context, args) + if not lexists(prefix): + raise EnvironmentLocationNotFound(prefix) + + pd = PrefixData(prefix) + + env_vars = pd.get_environment_env_vars() + if args.json: + common.stdout_json(env_vars) + else: + for k, v in env_vars.items(): + print(f"{k} = {v}") + + return 0 + + +def execute_set(args: Namespace, parser: ArgumentParser) -> int: + prefix = determine_target_prefix(context, args) + pd = PrefixData(prefix) + if not lexists(prefix): + raise EnvironmentLocationNotFound(prefix) + + env_vars_to_add = {} + for var in args.vars: + var_def = var.split("=") + env_vars_to_add[var_def[0].strip()] = "=".join(var_def[1:]).strip() + pd.set_environment_env_vars(env_vars_to_add) + if prefix == context.active_prefix: + print("To make your changes take effect please reactivate your environment") + + return 0 + + +def execute_unset(args: Namespace, parser: ArgumentParser) -> int: + prefix = determine_target_prefix(context, args) + pd = PrefixData(prefix) + if not lexists(prefix): + raise EnvironmentLocationNotFound(prefix) + + vars_to_unset = [var.strip() for var in args.vars] + pd.unset_environment_env_vars(vars_to_unset) + if prefix == context.active_prefix: + print("To make your changes take effect please reactivate your environment") + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_export.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_export.py new file mode 100644 index 0000000000000000000000000000000000000000..0123ef5e3985fe16ad2bf27948e8b79a73c59ba8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_export.py @@ -0,0 +1,227 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda export`. + +Dumps specified environment package specifications to the screen. +""" + +from argparse import ( + ArgumentParser, + Namespace, + _SubParsersAction, +) + +from conda.base.constants import KNOWN_SUBDIRS + +from ..auxlib.ish import dals +from ..base.context import context +from ..common.constants import NULL +from ..models.environment import Environment +from ..plugins.environment_exporters.environment_yml import ( + ENVIRONMENT_JSON_FORMAT, + ENVIRONMENT_YAML_FORMAT, +) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from .helpers import LazyChoicesAction, add_parser_json, add_parser_prefix + + summary = "Export a given environment" + description = summary + epilog = dals( + """ + Examples:: + + conda export + conda export --file FILE_NAME + conda export --format yaml + conda export --file environment.yaml + """ + ) + + p = sub_parsers.add_parser( + "export", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + p.add_argument( + "-c", + "--channel", + action="append", + help="Additional channel to include in the export", + ) + + p.add_argument( + "-O", + "--override-channels", + action="store_true", + help="Do not include .condarc channels", + ) + # NOTE: This is a different platform option from the one in helpers.py + # This is because we want to: + # - Allow users to specify multiple platforms for export + # - Change the help so that it's clearer that this is for export + # + # The add_parser_platform in helpers.py is used to specify a single platform/subdir + # for the current environment. We may want to change the helper. + p.add_argument( + "--platform", + "--subdir", + action="append", + dest="export_platforms", + help="Target platform(s)/subdir(s) for export (e.g., linux-64, osx-64, win-64)", + ) + p.add_argument( + "--override-platforms", + action="store_true", + help="Override the platforms specified in the condarc", + ) + add_parser_prefix(p) + + p.add_argument( + "-f", + "--file", + default=None, + required=False, + help=( + "File name or path for the exported environment. " + "Note: This will silently overwrite any existing file " + "of the same name in the current directory." + ), + ) + + p.add_argument( + "--format", + default=NULL, + required=False, + action=LazyChoicesAction, + choices_func=lambda: sorted( + context.plugin_manager.get_exporter_format_mapping() + ), + help=( + "Format for the exported environment. " + "If not specified, format will be determined by file extension or default to YAML." + ), + ) + + p.add_argument( + "--no-builds", + default=False, + action="store_true", + required=False, + help="Remove build specification from dependencies", + ) + + p.add_argument( + "--ignore-channels", + default=False, + action="store_true", + required=False, + help="Do not include channel names with package names.", + ) + add_parser_json(p) + + p.add_argument( + "--from-history", + default=False, + action="store_true", + required=False, + help="Build environment spec from explicit specs in history", + ) + p.set_defaults(func="conda.cli.main_export.execute") + + return p + + +# TODO Make this aware of channels that were used to install packages +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import env_name + from ..exceptions import CondaValueError + from .common import stdout_json + + unknown = set(context.export_platforms) - set(KNOWN_SUBDIRS) + if unknown: + raise CondaValueError( + f"Could not find platform(s): {', '.join(sorted(unknown))}. " + f"Valid platforms include: {', '.join(sorted(KNOWN_SUBDIRS))}" + ) + + # Early format validation - fail fast if format is unsupported + target_format = args.format + environment_exporter = None + + # Handle --json flag for backwards compatibility + # If --json is specified without explicit --format AND no file, use JSON format + # If both --json and --format are specified, --format takes precedence + # If --json with file, --json only affects status messages + if target_format is not NULL: + # If explicit format provided, use it and find the appropriate exporter + pass + elif args.file: + # Try to detect format by filename + environment_exporter = context.plugin_manager.detect_environment_exporter( + args.file + ) + target_format = environment_exporter.name + elif args.json: + # Backwards compatibility: --json without --format and no file means JSON output + target_format = ENVIRONMENT_JSON_FORMAT + else: + # No file and no explicit format, default to environment-yaml + target_format = ENVIRONMENT_YAML_FORMAT + + # If no exporter was detected, try to get one by format + if not environment_exporter: + environment_exporter = ( + context.plugin_manager.get_environment_exporter_by_format(target_format) + ) + + # If user requested multiple platforms, we need an exporter that supports it + if ( + len(context.export_platforms) > 1 + and not environment_exporter.multiplatform_export + ): + raise CondaValueError( + f"Multiple platforms are not supported for the `{environment_exporter.name}` exporter" + ) + + prefix = context.target_prefix + + # Create models.Environment directly + env = Environment.from_prefix( + prefix=prefix, + name=env_name(prefix), + platform=context.subdir, + from_history=args.from_history, + no_builds=args.no_builds, + ignore_channels=args.ignore_channels, + channels=context.channels, + ) + + # Export using the appropriate method + envs = [env.extrapolate(platform) for platform in context.export_platforms] + if environment_exporter.multiplatform_export: + exported_content = environment_exporter.multiplatform_export(envs) + elif environment_exporter.export: + exported_content = environment_exporter.export(envs[0]) + else: + raise CondaValueError( + f"No export method found for {environment_exporter.name} exporter" + ) + + # Add trailing newline to the exported content + exported_content = exported_content.rstrip() + "\n" + + # Output the content + if args.file: + with open(args.file, "w") as fp: + fp.write(exported_content) + if args.json: + stdout_json({"success": True, "file": args.file, "format": target_format}) + else: + print(exported_content, end="") + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_info.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_info.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc0a970b099a787868fb46a3c3b060be7d1aeac --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_info.py @@ -0,0 +1,627 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda info`. + +Display information about current conda installation. +""" + +from __future__ import annotations + +import os +import re +import sys +from argparse import SUPPRESS, _StoreTrueAction +from functools import cached_property +from logging import getLogger +from os.path import exists, expanduser, isfile, join +from tempfile import gettempdir +from textwrap import wrap +from typing import TYPE_CHECKING, Literal + +from ..deprecations import deprecated +from ..exceptions import ArgumentError + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + from collections.abc import Iterable + from typing import Any + + from ..base.context import Context + from ..models.records import PackageRecord + +log = getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..common.constants import NULL + from .helpers import add_parser_json + + summary = "Display information about current conda install." + description = summary + epilog = "" + + p = sub_parsers.add_parser( + "info", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_json(p) + p.add_argument( + "--offline", + action="store_true", + default=NULL, + help=SUPPRESS, + ) + p.add_argument( + "-a", + "--all", + action="store_true", + help="Show all information.", + ) + p.add_argument( + "--base", + action="store_true", + help="Display base environment path.", + ) + p.add_argument( + "-e", + "--envs", + action="store_true", + help="List all known conda environments. Combine with `--json` to obtain more details.", + ) + p.add_argument( + "-l", + "--license", + action=deprecated.action("25.9", "26.3", _StoreTrueAction), + help=SUPPRESS, + ) + p.add_argument( + "-s", + "--system", + action="store_true", + help="List environment variables.", + ) + p.add_argument( + "--size", + action="store_true", + help="Show conda-managed disk usage for each environment (excludes untracked files created after installation).", + ) + p.add_argument( + "--root", + action=deprecated.action( + "25.9", + "26.3", + _StoreTrueAction, + addendum="Use `--base` instead.", + ), + help=SUPPRESS, + dest="base", + ) + p.add_argument( + "--unsafe-channels", + action="store_true", + help="Display list of channels with tokens exposed.", + ) + + p.set_defaults(func="conda.cli.main_info.execute") + + return p + + +def get_user_site() -> list[str]: # pragma: no cover + """ + Method used to populate ``site_dirs`` in ``conda info``. + + :returns: List of directories. + """ + + from ..common.compat import on_win + + site_dirs = [] + try: + if not on_win: + if exists(expanduser("~/.local/lib")): + python_re = re.compile(r"python\d\.\d") + for path in os.listdir(expanduser("~/.local/lib/")): + if python_re.match(path): + site_dirs.append(f"~/.local/lib/{path}") + else: + if "APPDATA" not in os.environ: + return site_dirs + APPDATA = os.environ["APPDATA"] + if exists(join(APPDATA, "Python")): + site_dirs = [ + join(APPDATA, "Python", i) + for i in os.listdir(join(APPDATA, "PYTHON")) + ] + except OSError as e: + log.debug("Error accessing user site directory.\n%r", e) + return site_dirs + + +IGNORE_FIELDS: set[str] = {"files", "auth", "preferred_env", "priority"} + +SKIP_FIELDS: set[str] = { + *IGNORE_FIELDS, + "name", + "version", + "build", + "build_number", + "channel", + "schannel", + "size", + "fn", + "depends", +} + + +def dump_record(prec: PackageRecord) -> dict[str, Any]: + """ + Returns a dictionary of key/value pairs from ``prec``. Keys included in ``IGNORE_FIELDS`` are not returned. + + :param prec: A ``PackageRecord`` object. + :returns: A dictionary of elements dumped from ``prec`` + """ + return {k: v for k, v in prec.dump().items() if k not in IGNORE_FIELDS} + + +def pretty_package(prec: PackageRecord) -> None: + """ + Pretty prints contents of a ``PackageRecord`` + + :param prec: A ``PackageRecord`` + """ + + from ..utils import human_bytes + + pkg = dump_record(prec) + d = { + "file name": prec.fn, + "name": pkg["name"], + "version": pkg["version"], + "build string": pkg["build"], + "build number": pkg["build_number"], + "channel": str(prec.channel), + "size": human_bytes(pkg["size"]), + } + for key in sorted(set(pkg.keys()) - SKIP_FIELDS): + d[key] = pkg[key] + + print() + header = "{} {} {}".format(d["name"], d["version"], d["build string"]) + print(header) + print("-" * len(header)) + for key in d: + print("%-12s: %s" % (key, d[key])) + print("dependencies:") + for dep in pkg["depends"]: + print(f" {dep}") + + +def get_info_dict() -> dict[str, Any]: + """ + Returns a dictionary of contextual information. + + :returns: Dictionary of conda information to be sent to stdout. + """ + + from .. import CONDA_PACKAGE_ROOT + from .. import __version__ as conda_version + from ..base.context import ( + DEFAULT_SOLVER, + context, + env_name, + sys_rc_path, + user_rc_path, + ) + from ..common.compat import on_win + from ..common.url import mask_anaconda_token + from ..core.index import Index + from ..models.channel import all_channel_urls, offline_keep + + try: + from conda_build import __version__ as conda_build_version + except ImportError as err: + # ImportError: conda-build is not installed + log.debug("Unable to import conda-build: %s", err) + conda_build_version = "not installed" + except Exception as err: + log.error("Error importing conda-build: %s", err) + conda_build_version = "error" + + virtual_pkg_index = Index().system_packages + virtual_pkgs = [[p.name, p.version, p.build] for p in virtual_pkg_index.values()] + + channels = list(all_channel_urls(context.channels)) + if not context.json: + channels = [c + ("" if offline_keep(c) else " (offline)") for c in channels] + channels = [mask_anaconda_token(c) for c in channels] + + netrc_file = os.environ.get("NETRC") + if not netrc_file: + user_netrc = expanduser("~/.netrc") + if isfile(user_netrc): + netrc_file = user_netrc + + active_prefix_name = env_name(context.active_prefix) + + solver = { + "name": context.solver, + "user_agent": context.solver_user_agent(), + "default": context.solver == DEFAULT_SOLVER, + } + + info_dict = dict( + platform=context.subdir, + conda_version=conda_version, + conda_env_version=conda_version, + conda_build_version=conda_build_version, + root_prefix=context.root_prefix, + conda_prefix=context.conda_prefix, + av_data_dir=context.av_data_dir, + av_metadata_url_base=context.signing_metadata_url_base, + root_writable=context.root_writable, + pkgs_dirs=context.pkgs_dirs, + envs_dirs=context.envs_dirs, + default_prefix=context.default_prefix, + active_prefix=context.active_prefix, + active_prefix_name=active_prefix_name, + conda_shlvl=context.shlvl, + channels=channels, + user_rc_path=user_rc_path, + rc_path=user_rc_path, + sys_rc_path=sys_rc_path, + # is_foreign=bool(foreign), + offline=context.offline, + envs=[], + python_version=".".join(map(str, sys.version_info)), + requests_version=context.requests_version, + user_agent=context.user_agent, + conda_location=CONDA_PACKAGE_ROOT, + config_files=context.config_files, + netrc_file=netrc_file, + virtual_pkgs=virtual_pkgs, + solver=solver, + tmp_dir=gettempdir(), + ) + if on_win: + from ..common._os.windows import is_admin_on_windows + + info_dict["is_windows_admin"] = is_admin_on_windows() + else: + info_dict["UID"] = os.geteuid() + info_dict["GID"] = os.getegid() + + env_var_keys = { + "CIO_TEST", + "CURL_CA_BUNDLE", + "REQUESTS_CA_BUNDLE", + "SSL_CERT_FILE", + "LD_PRELOAD", + } + + # add all relevant env vars, e.g. startswith('CONDA') or endswith('PATH') + env_var_keys.update(v for v in os.environ if v.upper().startswith("CONDA")) + env_var_keys.update(v for v in os.environ if v.upper().startswith("PYTHON")) + env_var_keys.update(v for v in os.environ if v.upper().endswith("PATH")) + env_var_keys.update(v for v in os.environ if v.upper().startswith("SUDO")) + + env_vars = { + ev: os.getenv(ev, os.getenv(ev.lower(), "")) for ev in env_var_keys + } + + proxy_keys = (v for v in os.environ if v.upper().endswith("PROXY")) + env_vars.update({ev: "" for ev in proxy_keys}) + + info_dict.update( + { + "sys.version": sys.version, + "sys.prefix": sys.prefix, + "sys.executable": sys.executable, + "site_dirs": get_user_site(), + "env_vars": env_vars, + } + ) + + return info_dict + + +def get_env_vars_str(info_dict: dict[str, Any]) -> str: + """ + Returns a printable string representing environment variables from the dictionary returned by ``get_info_dict``. + + :param info_dict: The returned dictionary from ``get_info_dict()``. + :returns: String to print. + """ + + builder = [] + builder.append("%23s:" % "environment variables") + env_vars = info_dict.get("env_vars", {}) + for key in sorted(env_vars): + value = wrap(env_vars[key]) + first_line = value[0] if len(value) else "" + other_lines = value[1:] if len(value) > 1 else () + builder.append("%25s=%s" % (key, first_line)) + for val in other_lines: + builder.append(" " * 26 + val) + return "\n".join(builder) + + +def get_main_info_display(info_dict: dict[str, Any]) -> dict[str, str]: + """ + Returns the data that can be used to display information for conda info + """ + from ..common.compat import on_win + + def flatten(lines: Iterable[str]) -> str: + return ("\n" + 26 * " ").join(map(str, lines)) + + def builder(): + if info_dict["active_prefix_name"]: + yield ("active environment", info_dict["active_prefix_name"]) + yield ("active env location", info_dict["active_prefix"]) + else: + yield ("active environment", info_dict["active_prefix"]) + + if info_dict["conda_shlvl"] >= 0: + yield ("shell level", info_dict["conda_shlvl"]) + + yield ("user config file", info_dict["user_rc_path"]) + yield ("populated config files", flatten(info_dict["config_files"])) + yield ("conda version", info_dict["conda_version"]) + yield ("conda-build version", info_dict["conda_build_version"]) + yield ("python version", info_dict["python_version"]) + yield ( + "solver", + f"{info_dict['solver']['name']}{' (default)' if info_dict['solver']['default'] else ''}", + ) + yield ( + "virtual packages", + flatten("=".join(pkg) for pkg in info_dict["virtual_pkgs"]), + ) + writable = "writable" if info_dict["root_writable"] else "read only" + yield ("base environment", f"{info_dict['root_prefix']} ({writable})") + yield ("conda av data dir", info_dict["av_data_dir"]) + yield ("conda av metadata url", info_dict["av_metadata_url_base"]) + yield ("channel URLs", flatten(info_dict["channels"])) + yield ("package cache", flatten(info_dict["pkgs_dirs"])) + yield ("envs directories", flatten(info_dict["envs_dirs"])) + yield ("temporary directory", info_dict["tmp_dir"]) + yield ("platform", info_dict["platform"]) + yield ("user-agent", info_dict["user_agent"]) + + if on_win: + yield ("administrator", info_dict["is_windows_admin"]) + else: + yield ("UID:GID", f"{info_dict['UID']}:{info_dict['GID']}") + + yield ("netrc file", info_dict["netrc_file"]) + yield ("offline mode", info_dict["offline"]) + + return {key: value for key, value in builder()} + + +def get_main_info_str(info_dict: dict[str, Any]) -> str: + """ + Returns a printable string of the contents of ``info_dict``. + + :param info_dict: The output of ``get_info_dict()``. + :returns: String to print. + """ + display_info = get_main_info_display(info_dict) + + return "\n".join( + ("", *(f"{key:>23} : {value}" for key, value in display_info.items()), "") + ) + + +InfoComponents = Literal["base", "channels", "envs", "system", "detail", "json_all"] +"""Possible components for the info command to render.""" + + +class InfoRenderer: + """ + Provides a ``render`` method for rendering ``InfoComponents`` + """ + + def __init__(self, context: Context, show_size: bool = False): + self._context = context + self._show_size = show_size + self._component_style_map = { + "base": None, + "channels": None, + "detail": "detail_view", + "envs": "envs_list", + "system": None, + "json_all": None, + } + + @cached_property + def _info_dict(self): + info_dict = get_info_dict() + info_dict["envs"] = self._info_dict_envs + info_dict["envs_details"] = self._info_dict_envs_details + return info_dict + + @cached_property + def _info_dict_envs(self) -> list[str]: + from ..core.envs_manager import list_all_known_prefixes + + return list_all_known_prefixes() + + @cached_property + def _info_dict_envs_details(self) -> dict[str, dict[str, str | bool | None | int]]: + from ..core.prefix_data import PrefixData + + result = {} + if active_prefix := self._context.active_prefix: + active_prefix_data = PrefixData(active_prefix) + else: + active_prefix_data = None + for prefix in self._info_dict_envs: + prefix_data = PrefixData(prefix) + if created := prefix_data.created: + created = created.isoformat() + if last_modified := prefix_data.last_modified: + last_modified = last_modified.isoformat() + result[prefix] = { + "name": prefix_data.name, + "created": created, + "last_modified": last_modified, + "active": prefix_data == active_prefix_data, + "base": prefix_data.is_base(), + "frozen": prefix_data.is_frozen(), + "writable": prefix_data.is_writable, + } + if self._show_size: + result[prefix]["size"] = prefix_data.size() + return result + + def render(self, components: Iterable[InfoComponents]): + """ + Iterates through the registered components, obtains the data to render via a + ``__component`` method and then renders it. + """ + from ..reporters import render + + for component in components: + style = self._component_style_map.get(component) + data_func = getattr(self, f"_{component}_component", None) + + if not data_func: + continue + + data = data_func() + + if data: + kwargs = {} + if component == "envs" and self._show_size: + kwargs["show_size"] = True + render(data, style=style, **kwargs) + + def _base_component(self) -> str | dict: + if self._context.json: + return {"root_prefix": self._context.root_prefix} + else: + return f"{self._context.root_prefix}\n" + + def _channels_component(self) -> str | dict: + if self._context.json: + return {"channels": self._context.channels} + else: + channels_str = "\n".join(self._context.channels) + return f"{channels_str}\n" + + def _detail_component(self) -> dict[str, str]: + return get_main_info_display(self._info_dict) + + def _envs_component(self): + if self._context.json: + return { + "envs": self._info_dict_envs, + "envs_details": self._info_dict_envs_details, + } + return self._info_dict_envs + + def _system_component(self) -> str: + from .find_commands import find_commands, find_executable + + output = [ + f"sys.version: {sys.version[:40]}...", + f"sys.prefix: {sys.prefix}", + f"sys.executable: {sys.executable}", + "conda location: {}".format(self._info_dict["conda_location"]), + ] + + for cmd in sorted(set(find_commands() + ("build",))): + output.append("conda-{}: {}".format(cmd, find_executable("conda-" + cmd))) + + site_dirs = self._info_dict["site_dirs"] + if site_dirs: + output.append(f"user site dirs: {site_dirs[0]}") + else: + output.append("user site dirs:") + + for site_dir in site_dirs[1:]: + output.append(f" {site_dir}") + + output.append("") + + for name, value in sorted(self._info_dict["env_vars"].items()): + output.append(f"{name}: {value}") + + output.append("") + + return "\n".join(output) + + def _json_all_component(self) -> dict[str, Any]: + return self._info_dict + + +@deprecated( + "25.9", + "26.3", + addendum="Use `conda.cli.main_info.iter_info_components` instead.", +) +def get_info_components(args: Namespace, context: Context) -> set[InfoComponents]: + return set(iter_info_components(args, context)) + + +def iter_info_components(args: Namespace, context: Context) -> Iterable[InfoComponents]: + """ + Determine which components to display. + + :param args: The parsed command line arguments. + :param context: The conda context. + :returns: An iterable of components to display. + """ + if args.base: + yield "base" + + if args.unsafe_channels: + yield "channels" + + if ( + (args.all or (not args.envs and not args.system)) + and not context.json + and not args.base + and not args.unsafe_channels + ): + yield "detail" + + if args.envs or (args.all and not context.json): + yield "envs" + yield "envs_details" + + if (args.system or args.all) and not context.json: + yield "system" + + if context.json and not args.base and not args.unsafe_channels and not args.envs: + yield "json_all" + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + """ + Implements ``conda info`` command. + + * ``conda info`` + * ``conda info --base`` + * ``conda info ...`` + * ``conda info --unsafe-channels`` + * ``conda info --envs`` + * ``conda info --system`` + """ + + from ..base.context import context + + if args.size and not args.envs: + raise ArgumentError("--size can only be used with --envs") + + components = iter_info_components(args, context) + show_size = getattr(args, "size", False) + renderer = InfoRenderer(context, show_size=show_size) + renderer.render(components) + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_init.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_init.py new file mode 100644 index 0000000000000000000000000000000000000000..f85ed0aa8bca0432131644a0e199e9739e767d7e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_init.py @@ -0,0 +1,190 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda init`. + +Prepares the user's profile for running conda, and sets up the conda shell interface. +""" + +from __future__ import annotations + +from argparse import SUPPRESS +from logging import getLogger +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + +log = getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..base.constants import COMPATIBLE_SHELLS + from ..common.compat import on_win + from ..common.constants import NULL + from .helpers import add_parser_json + + summary = "Initialize conda for shell interaction." + description = summary + epilog = dals( + """ + Key parts of conda's functionality require that it interact directly with the shell + within which conda is being invoked. The `conda activate` and `conda deactivate` commands + specifically are shell-level commands. That is, they affect the state (e.g. environment + variables) of the shell context being interacted with. Other core commands, like + `conda create` and `conda install`, also necessarily interact with the shell environment. + They're therefore implemented in ways specific to each shell. Each shell must be configured + to make use of them. + + The --condabin option adds the "$CONDA_PREFIX/condabin" directory to the PATH environment variable. + This directory only contains the conda executable and does not contain other executables from other + packages installed in the base environment. On most shells, a small snippet is added to the + shell profile. For CMD, the PATH environment variable is modified directly in the registry. + + This command makes changes to your system that are specific and customized for each shell. + To see the specific files and locations on your system that will be affected before, use + the '--dry-run' flag. To see the exact changes that are being or will be made to each + location, use the '--verbose' flag. + + IMPORTANT: After running `conda init`, most shells will need to be closed and restarted for + changes to take effect. + + """ + ) + + p = sub_parsers.add_parser( + "init", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + p.add_argument( + "--dev", + action="store_true", + help=SUPPRESS, + default=NULL, + ) + + p.add_argument( + "--all", + action="store_true", + help="Initialize all currently available shells.", + default=NULL, + ) + + setup_type_group = p.add_argument_group("setup type") + setup_type_group.add_argument( + "--install", + action="store_true", + help=SUPPRESS, + default=NULL, + ) + setup_type_group.add_argument( + "--condabin", + action="store_true", + help="Add 'condabin/' directory to PATH only. Does not install the shell function.", + default=NULL, + ) + setup_type_group.add_argument( + "--user", + action="store_true", + dest="user", + help="Initialize conda for the current user (default).", + default=True, + ) + setup_type_group.add_argument( + "--no-user", + action="store_false", + dest="user", + help="Don't initialize conda for the current user.", + ) + setup_type_group.add_argument( + "--system", + action="store_true", + help="Initialize conda for all users on the system.", + default=NULL, + ) + setup_type_group.add_argument( + "--reverse", + action="store_true", + help="Undo effects of last conda init.", + default=NULL, + ) + + p.add_argument( + "shells", + nargs="*", + choices=COMPATIBLE_SHELLS, + metavar="SHELLS", + help=( + "One or more shells to be initialized. If not given, the default value is 'bash' on " + "unix and 'cmd.exe' & 'powershell' on Windows. Use the '--all' flag to initialize all " + f"shells. Available shells: {sorted(COMPATIBLE_SHELLS)}" + ), + default=["cmd.exe", "powershell"] if on_win else ["bash"], + ) + + if on_win: + p.add_argument( + "--anaconda-prompt", + action="store_true", + help="Add an 'Anaconda Prompt' icon to your desktop.", + default=NULL, + ) + + add_parser_json(p) + p.add_argument( + "-d", + "--dry-run", + action="store_true", + help="Only display what would have been done.", + ) + p.set_defaults(func="conda.cli.main_init.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.constants import COMPATIBLE_SHELLS + from ..base.context import context + from ..common.compat import on_win + from ..core.initialize import ( + add_condabin_to_path, + initialize, + initialize_dev, + install, + ) + from ..exceptions import ArgumentError + + if args.install: + return install(context.conda_prefix) + + selected_shells: tuple[str, ...] + if args.all: + selected_shells = COMPATIBLE_SHELLS + else: + selected_shells = tuple(args.shells) + + if args.dev: + if len(selected_shells) != 1: + raise ArgumentError("--dev can only handle one shell at a time right now") + return initialize_dev(selected_shells[0]) + elif args.condabin: + for_user = args.user and not args.system + anaconda_prompt = on_win and args.anaconda_prompt + return add_condabin_to_path( + context.conda_prefix, selected_shells, for_user, args.system, args.reverse + ) + else: + for_user = args.user and not args.system + anaconda_prompt = on_win and args.anaconda_prompt + return initialize( + context.conda_prefix, + selected_shells, + for_user, + args.system, + anaconda_prompt, + args.reverse, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_install.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_install.py new file mode 100644 index 0000000000000000000000000000000000000000..d66dcf30ea12760546b82197de4d4b21dbe6fa10 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_install.py @@ -0,0 +1,167 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda install`. + +Installs the specified packages into an existing environment. +""" + +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING + +from ..notices import notices + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..common.constants import NULL + from .actions import NullCountAction + from .helpers import ( + add_parser_create_install_update, + add_parser_frozen_env, + add_parser_prune, + add_parser_solver, + add_parser_update_modifiers, + ) + + summary = "Install a list of packages into a specified conda environment." + description = dals( + f""" + {summary} + + This command accepts a list of package specifications (e.g, bitarray=0.8) + and installs a set of packages consistent with those specifications and + compatible with the underlying environment. If full compatibility cannot + be assured, an error is reported and the environment is not changed. + + Conda attempts to install the newest versions of the requested packages. To + accomplish this, it may update some packages that are already installed, or + install additional packages. To prevent existing packages from updating, + use the --freeze-installed option. This may force conda to install older + versions of the requested packages, and it does not prevent additional + dependency packages from being installed. + + If you wish to skip dependency checking altogether, use the '--no-deps' + option. This may result in an environment with incompatible packages, so + this option must be used with great caution. + + conda can also be called with a list of explicit conda package filenames + (e.g. ./lxml-3.2.0-py27_0.tar.bz2). Using conda in this mode implies the + --no-deps option, and should likewise be used with great caution. Explicit + filenames and package specifications cannot be mixed in a single command. + """ + ) + epilog = dals( + """ + Examples: + + Install the package 'scipy' into the currently-active environment:: + + conda install scipy + + Install a list of packages into an environment, myenv:: + + conda install -n myenv scipy curl wheel + + Install a specific version of 'python' into an environment, myenv:: + + conda install -p path/to/myenv python=3.11 + + """ + ) + + p = sub_parsers.add_parser( + "install", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + p.add_argument( + "--revision", + action="store", + help="Revert to the specified REVISION.", + metavar="REVISION", + ) + add_parser_frozen_env(p) + + solver_mode_options, package_install_options, _ = add_parser_create_install_update( + p + ) + + add_parser_prune(solver_mode_options) + add_parser_solver(solver_mode_options) + solver_mode_options.add_argument( + "--force-reinstall", + action="store_true", + default=NULL, + help="Ensure that any user-requested package for the current operation is uninstalled and " + "reinstalled, even if that package already exists in the environment.", + ) + add_parser_update_modifiers(solver_mode_options) + package_install_options.add_argument( + "--clobber", + action="store_true", + default=NULL, + help="Allow clobbering (i.e. overwriting) of overlapping file paths " + "within packages and suppress related warnings.", + ) + p.add_argument( + "--dev", + action=NullCountAction, + help="Use `sys.executable -m conda` in wrapper scripts instead of CONDA_EXE. " + "This is mainly for use during tests where we test new conda sources " + "against old Python versions.", + dest="dev", + default=NULL, + ) + p.set_defaults(func="conda.cli.main_install.execute") + + return p + + +@notices +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import context + from ..exceptions import CondaValueError + from .common import validate_environment_files_consistency + from .install import get_revision, install, install_revision + + if context.force: + print( + "\n\n" + "WARNING: The --force flag will be removed in a future conda release.\n" + " See 'conda install --help' for details about the --force-reinstall\n" + " and --clobber flags.\n" + "\n", + file=sys.stderr, + ) + + # Validate that input files are of the same format type + validate_environment_files_consistency(args.file) + + # Ensure that users do not provide incompatible arguments. + # revision and packages can not be specified together + if args.revision and (args.file or args.packages): + raise CondaValueError( + "too many arguments, must supply one of command line packages, --file or --revision" + ) + + # Ensure provided combination of command line arguments are valid + if args.revision: + get_revision(args.revision, json=context.json) + elif not (args.file or args.packages): + raise CondaValueError( + "too few arguments, must supply one of command line packages, --file or --revision" + ) + + if args.revision: + install_revision(args, parser) + else: + install(args, parser, "install") + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_list.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_list.py new file mode 100644 index 0000000000000000000000000000000000000000..a37563364ee82d89968e7a7ad0fafac44562e5dd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_list.py @@ -0,0 +1,439 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda list`. + +Lists all packages installed into an environment. +""" + +from __future__ import annotations + +import logging +import re +from os.path import isdir, isfile +from typing import TYPE_CHECKING + +from .. import __version__ + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + from typing import Any + +log = logging.getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..base.constants import CONDA_LIST_FIELDS + from .helpers import ( + add_parser_json, + add_parser_prefix, + add_parser_show_channel_urls, + comma_separated_stripped, + ) + + summary = "List installed packages in a conda environment." + description = summary + epilog = dals( + """ + Examples: + + List all packages in the current environment:: + + conda list + + List all packages in reverse order:: + + conda list --reverse + + List all packages installed into the environment 'myenv':: + + conda list -n myenv + + List all packages that begin with the letters "py", using regex:: + + conda list ^py + + List name and version only:: + + conda list --fields name,version + + Save packages for future use:: + + conda list --export > package-list.txt + + Reinstall packages from an export file:: + + conda create -n myenv --file package-list.txt + + """ + ) + + p = sub_parsers.add_parser( + "list", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_prefix(p) + add_parser_json(p) + add_parser_show_channel_urls(p) + p.add_argument( + "--fields", + type=comma_separated_stripped, + dest="list_fields", + help="Comma-separated list of fields to print. " + f"Valid values: {','.join(sorted(CONDA_LIST_FIELDS))}.", + ) + p.add_argument( + "--reverse", + action="store_true", + default=False, + help="List installed packages in reverse order.", + ) + p.add_argument( + "-c", + "--canonical", + action="store_true", + help="Output canonical names of packages only.", + ) + p.add_argument( + "-f", + "--full-name", + action="store_true", + help="Only search for full names, i.e., ^$. " + "--full-name NAME is identical to regex '^NAME$'.", + ) + p.add_argument( + "--explicit", + action="store_true", + help="List explicitly all installed conda packages with URL " + "(output may be used by conda create --file).", + ) + p.add_argument( + "--md5", + action="store_true", + help="Add MD5 hashsum when using --explicit.", + ) + p.add_argument( + "--sha256", + action="store_true", + help="Add SHA256 hashsum when using --explicit.", + ) + p.add_argument( + "-e", + "--export", + action="store_true", + help="Output explicit, machine-readable requirement strings instead of " + "human-readable lists of packages. This output may be used by " + "conda create --file.", + ) + p.add_argument( + "-r", + "--revisions", + action="store_true", + help="List the revision history.", + ) + p.add_argument( + "--size", + action="store_true", + help="Show package and environment sizes.", + ) + p.add_argument( + "--no-pip", + action="store_false", + default=True, + dest="pip", + help="Do not include pip-only installed packages.", + ) + p.add_argument( + "--auth", + action="store_false", + default=True, + dest="remove_auth", + help="In explicit mode, leave authentication details in package URLs. " + "They are removed by default otherwise.", + ) + p.add_argument( + "regex", + action="store", + nargs="?", + help="List only packages matching this regular expression.", + ) + p.set_defaults(func="conda.cli.main_list.execute") + + return p + + +def print_export_header(subdir): + print("# This file may be used to create an environment using:") + print("# $ conda create --name --file ") + print(f"# platform: {subdir}") + print(f"# created-by: conda {__version__}") + + +def get_packages(installed, regex): + pat = re.compile(regex, re.I) if regex else None + for prefix_rec in sorted(installed, key=lambda x: x.name.lower()): + if pat and pat.search(prefix_rec.name) is None: + continue + yield prefix_rec + + +def list_packages( + prefix, + regex=None, + format="human", + reverse=False, + show_channel_urls=None, + reload_records=True, + fields=None, + regex_is_full_name=False, + show_size=False, +) -> tuple[int, list[str] | list[dict[str, Any]]]: + from ..base.constants import ( + CONDA_LIST_FIELDS, + DEFAULT_CONDA_LIST_FIELDS, + DEFAULTS_CHANNEL_NAME, + ) + from ..base.context import context + from ..core.prefix_data import PrefixData + from ..exceptions import CondaValueError, PackageNotInstalledError + from ..utils import human_bytes + from .common import disp_features + + exitcode = 0 + + prefix_data = PrefixData(prefix, interoperability=True) + if reload_records: + prefix_data.load() + if regex: + if regex_is_full_name: + record = prefix_data.get(regex, None) + prefix_records = (record,) if record else () + else: + prefix_records = sorted( + get_packages(prefix_data.iter_records(), regex), + key=lambda x: x.name, + ) + else: + prefix_records = sorted(prefix_data.iter_records(), key=lambda x: x.name) + show_channel_urls = show_channel_urls or context.show_channel_urls + fields = list(fields or context.list_fields) + if show_size and "size" not in fields: + fields.append("size") + + if invalid_fields := set(fields).difference(CONDA_LIST_FIELDS): + raise CondaValueError( + f"Invalid fields passed: {sorted(invalid_fields)}. " + f"Valid options are {list(CONDA_LIST_FIELDS)}." + ) + packages = [] + titles = [CONDA_LIST_FIELDS[field] for field in fields] + if tuple(fields[:4]) == DEFAULT_CONDA_LIST_FIELDS: + widths = [23, 15, 15, 1] + [len(title) for title in titles[4:]] + else: + widths = [len(title) for title in titles] + for prec in prefix_records: + if format == "canonical": + if context.json: + package = prec.dist_fields_dump() + if show_size: + package["size"] = prec.package_size(prefix_data.prefix_path) + packages.append(package) + else: + packages.append(prec.dist_str()) + continue + if format == "export": + packages.append(prec.spec) + continue + + # this is for format == "human" + row = [] + for idx, field in enumerate(fields): + if field == "features": + features = set(prec.get("features") or ()) + value = disp_features(features) + elif field == "channel_name": + channel_name = prec.get("channel_name") + if ( + show_channel_urls + or show_channel_urls is None + and channel_name != DEFAULTS_CHANNEL_NAME + ): + value = str(channel_name) + else: + value = "" + elif field == "dist_str": + value = prec.dist_str() + elif field == "size": + value = human_bytes(prec.package_size(prefix_data.prefix_path)) + else: + value = str(prec.get(field, None) or "").strip() + if value == "None": + value = "" + row.append(value) + if (value_length := len(value)) > widths[idx]: + widths[idx] = value_length + + packages.append(row) + + if regex and not packages: + if regex_is_full_name: + raise PackageNotInstalledError(prefix, regex) + raise CondaValueError(f"No packages match '{regex}'.") + + if reverse: + packages = reversed(packages) + + if format == "human": + template_line = " ".join([f"%-{width}s" for width in widths]) + result = [ + f"# packages in environment at {prefix}:", + ] + if show_size: + env_size = human_bytes(prefix_data.size()) + result.append(f"# environment size: {env_size}") + result.extend( + [ + "#", + f"# {template_line}" % tuple(titles), + ] + ) + widths[0] += 2 # account for the '# ' prefix in the header line + template_line = " ".join([f"%-{width}s" for width in widths]) + result.extend([template_line % tuple(package) for package in packages]) + else: + result = list(packages) + return exitcode, result + + +def print_packages( + prefix, + regex=None, + format="human", + reverse=False, + piplist=False, + json=False, + show_channel_urls=None, + fields=None, + regex_is_full_name=False, + show_size=False, +) -> int: + from ..base.context import context + from .common import stdout_json + + if not isdir(prefix): + from ..exceptions import EnvironmentLocationNotFound + + raise EnvironmentLocationNotFound(prefix) + + if not json: + if format == "export": + print_export_header(context.subdir) + + exitcode, output = list_packages( + prefix, + regex, + format=format, + reverse=reverse, + show_channel_urls=show_channel_urls, + fields=fields, + regex_is_full_name=regex_is_full_name, + show_size=show_size, + ) + if context.json: + stdout_json(output) + + else: + print("\n".join([str(line).rstrip() for line in output])) + + return exitcode + + +def print_explicit(prefix, add_md5=False, remove_auth=True, add_sha256=False): + from ..base.constants import EXPLICIT_MARKER, UNKNOWN_CHANNEL + from ..base.context import context + from ..common import url as common_url + from ..core.prefix_data import PrefixData + + if add_md5 and add_sha256: + raise ValueError("Only one of add_md5 and add_sha256 can be chosen") + if not isdir(prefix): + from ..exceptions import EnvironmentLocationNotFound + + raise EnvironmentLocationNotFound(prefix) + print_export_header(context.subdir) + print(EXPLICIT_MARKER) + for prefix_record in PrefixData(prefix).iter_records_sorted(): + url = prefix_record.get("url") + if not url or url.startswith(UNKNOWN_CHANNEL): + print("# no URL for: {}".format(prefix_record["fn"])) + continue + if remove_auth: + url = common_url.remove_auth(common_url.split_anaconda_token(url)[0]) + if add_md5 or add_sha256: + hash_key = "md5" if add_md5 else "sha256" + hash_value = prefix_record.get(hash_key) + print(url + (f"#{hash_value}" if hash_value else "")) + else: + print(url) + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import context + from ..core.prefix_data import PrefixData + from ..history import History + from .common import stdout_json + + prefix_data = PrefixData.from_context() + prefix_data.assert_environment() + prefix = str(prefix_data.prefix_path) + + if args.md5 and args.sha256: + from ..exceptions import ArgumentError + + raise ArgumentError( + "Only one of --md5 and --sha256 can be specified at the same time" + ) + + regex = args.regex + + if args.revisions: + h = History(prefix) + if isfile(h.path): + if not context.json: + h.print_log() + else: + stdout_json(h.object_log()) + else: + from ..exceptions import PathNotFoundError + + raise PathNotFoundError(h.path) + return 0 + + if args.explicit: + print_explicit(prefix, args.md5, args.remove_auth, args.sha256) + return 0 + + if args.canonical: + format = "canonical" + elif args.export: + format = "export" + else: + format = "human" + + if context.json: + format = "canonical" + + return print_packages( + prefix, + regex, + format, + reverse=args.reverse, + piplist=args.pip, + json=context.json, + show_channel_urls=context.show_channel_urls, + regex_is_full_name=args.full_name, + show_size=args.size, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_mock_activate.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_mock_activate.py new file mode 100644 index 0000000000000000000000000000000000000000..86404e5582fc5ae72ce1a950b9f118e98895e33f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_mock_activate.py @@ -0,0 +1,32 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Mock CLI implementation for `conda activate`. + +A mock implementation of the activate shell command for better UX. +""" + +from __future__ import annotations + +from argparse import SUPPRESS +from typing import TYPE_CHECKING + +from .. import CondaError + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + p = sub_parsers.add_parser( + "activate", + help="Activate a conda environment.", + **kwargs, + ) + p.set_defaults(func="conda.cli.main_mock_activate.execute") + p.add_argument("args", action="store", nargs="*", help=SUPPRESS) + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + raise CondaError("Run 'conda init' before 'conda activate'") diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_mock_deactivate.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_mock_deactivate.py new file mode 100644 index 0000000000000000000000000000000000000000..4b89bfde8825867ea2f88dae3be65e317f8469a4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_mock_deactivate.py @@ -0,0 +1,30 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Mock CLI implementation for `conda deactivate`. + +A mock implementation of the deactivate shell command for better UX. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .. import CondaError + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + p = sub_parsers.add_parser( + "deactivate", + help="Deactivate the current active conda environment.", + **kwargs, + ) + p.set_defaults(func="conda.cli.main_mock_deactivate.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + raise CondaError("Run 'conda init' before 'conda deactivate'") diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_notices.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_notices.py new file mode 100644 index 0000000000000000000000000000000000000000..ab964930cdcfa14614b5fa99f402a24a65b4b8fd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_notices.py @@ -0,0 +1,64 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda notices`. + +Manually retrieves channel notifications, caches them and displays them. +""" + +from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import add_parser_channels, add_parser_json + + summary = "Retrieve latest channel notifications." + description = dals( + f""" + {summary} + + Conda channel maintainers have the option of setting messages that + users will see intermittently. Some of these notices are informational + while others are messages concerning the stability of the channel. + + """ + ) + epilog = dals( + """ + Examples:: + + conda notices + + conda notices -c defaults + + """ + ) + + p = sub_parsers.add_parser( + "notices", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_channels(p) + add_parser_json(p) + + p.set_defaults(func="conda.cli.main_notices.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + """Command that retrieves channel notifications, caches them and displays them.""" + from ..exceptions import CondaError + from ..notices import core as notices + + try: + channel_notice_set = notices.retrieve_notices() + except OSError as exc: + raise CondaError(f"Unable to retrieve notices: {exc}") + + notices.display_notices(channel_notice_set) + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_package.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_package.py new file mode 100644 index 0000000000000000000000000000000000000000..2309fca0674dc5de7130f13d85500abedc1826d3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_package.py @@ -0,0 +1,303 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda package`. + +Provides some low-level tools for creating conda packages. +""" + +import hashlib +import os +import re +import tarfile +import tempfile +from argparse import ArgumentParser, Namespace, _SubParsersAction +from os.path import abspath, basename, dirname, isdir, isfile, islink, join + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from .helpers import add_parser_prefix + + summary = "Create low-level conda packages. (EXPERIMENTAL)" + description = summary + epilog = "" + + p = sub_parsers.add_parser( + "package", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_prefix(p) + p.add_argument( + "-w", + "--which", + metavar="PATH", + nargs="+", + action="store", + help="Given some file's PATH, print which conda package the file came from.", + ) + p.add_argument( + "-r", + "--reset", + action="store_true", + help="Remove all untracked files and exit.", + ) + p.add_argument( + "-u", + "--untracked", + action="store_true", + help="Display all untracked files and exit.", + ) + p.add_argument( + "--pkg-name", + action="store", + default="unknown", + help="Designate package name of the package being created.", + ) + p.add_argument( + "--pkg-version", + action="store", + default="0.0", + help="Designate package version of the package being created.", + ) + p.add_argument( + "--pkg-build", + action="store", + default=0, + help="Designate package build number of the package being created.", + ) + p.set_defaults(func="conda.cli.main_package.execute") + + return p + + +def remove(prefix, files): + """Remove files for a given prefix.""" + dst_dirs = set() + for f in files: + dst = join(prefix, f) + dst_dirs.add(dirname(dst)) + os.unlink(dst) + + for path in sorted(dst_dirs, key=len, reverse=True): + try: + os.rmdir(path) + except OSError: # directory might not be empty + pass + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import context + from ..misc import untracked + + prefix = context.target_prefix + + if args.which: + for path in args.which: + for prec in which_package(path): + print("%-50s %s" % (path, prec.dist_str())) + return 0 + + print("# prefix:", prefix) + + if args.reset: + remove(prefix, untracked(prefix)) + return 0 + + if args.untracked: + files = sorted(untracked(prefix)) + print("# untracked files: %d" % len(files)) + for fn in files: + print(fn) + return 0 + + make_tarbz2( + prefix, + name=args.pkg_name.lower(), + version=args.pkg_version, + build_number=int(args.pkg_build), + ) + return 0 + + +def get_installed_version(prefix, name): + from ..core.prefix_data import PrefixData + + for info in PrefixData(prefix).iter_records(): + if info["name"] == name: + return str(info["version"]) + return None + + +def create_info(name, version, build_number, requires_py): + from ..base.context import context + + d = dict( + name=name, + version=version, + platform=context.platform, + arch=context.arch_name, + build_number=int(build_number), + build=str(build_number), + depends=[], + ) + if requires_py: + d["build"] = ("py%d%d_" % requires_py) + d["build"] + d["depends"].append("python %d.%d*" % requires_py) + return d + + +shebang_pat = re.compile(r"^#!.+$", re.M) + + +def fix_shebang(tmp_dir, path): + from ..base.constants import PREFIX_PLACEHOLDER + + if open(path, "rb").read(2) != "#!": + return False + + with open(path) as fi: + data = fi.read() + m = shebang_pat.match(data) + if not (m and "python" in m.group()): + return False + + data = shebang_pat.sub(f"#!{PREFIX_PLACEHOLDER}/bin/python", data, count=1) + tmp_path = join(tmp_dir, basename(path)) + with open(tmp_path, "w") as fo: + fo.write(data) + os.chmod(tmp_path, int("755", 8)) + return True + + +def _add_info_dir(t, tmp_dir, files, has_prefix, info): + from ..common.serialize import json + + info_dir = join(tmp_dir, "info") + os.mkdir(info_dir) + with open(join(info_dir, "files"), "w") as fo: + for f in files: + fo.write(f + "\n") + + with open(join(info_dir, "index.json"), "w") as fo: + json.dump(info, fo, sort_keys=True) + + if has_prefix: + with open(join(info_dir, "has_prefix"), "w") as fo: + for f in has_prefix: + fo.write(f + "\n") + + for fn in os.listdir(info_dir): + t.add(join(info_dir, fn), "info/" + fn) + + +def create_conda_pkg(prefix, files, info, tar_path, update_info=None): + """Create a conda package and return a list of warnings.""" + from ..gateways.disk.delete import rmtree + + files = sorted(files) + warnings = [] + has_prefix = [] + tmp_dir = tempfile.mkdtemp() + t = tarfile.open(tar_path, "w:bz2") + h = hashlib.new("sha1") + for f in files: + if f.startswith("/") or f.endswith("/") or "\\" in f or f == "": + raise ValueError( + f"Invalid file path: {f}. " + "Must be not empty. Cannot start or end with '/'. Cannot contain '\\'." + ) + path = join(prefix, f) + if f.startswith("bin/") and fix_shebang(tmp_dir, path): + path = join(tmp_dir, basename(path)) + has_prefix.append(f) + t.add(path, f) + h.update(f.encode("utf-8")) + h.update(b"\x00") + if islink(path): + link = os.readlink(path) + if isinstance(link, str): + h.update(bytes(link, "utf-8")) + else: + h.update(link) + if link.startswith("/"): + warnings.append(f"found symlink to absolute path: {f} -> {link}") + elif isfile(path): + h.update(open(path, "rb").read()) + if path.endswith(".egg-link"): + warnings.append(f"found egg link: {f}") + + info["file_hash"] = h.hexdigest() + if update_info: + update_info(info) + _add_info_dir(t, tmp_dir, files, has_prefix, info) + t.close() + rmtree(tmp_dir) + return warnings + + +def make_tarbz2(prefix, name="unknown", version="0.0", build_number=0, files=None): + from ..base.constants import CONDA_PACKAGE_EXTENSION_V1 + from ..misc import untracked + + if files is None: + files = untracked(prefix) + print("# files: %d" % len(files)) + if len(files) == 0: + print("# failed: nothing to do") + return None + + if any("/site-packages/" in f for f in files): + python_version = get_installed_version(prefix, "python") + if python_version is None: + raise ValueError("Python must be installed in target prefix.") + requires_py = tuple(int(x) for x in python_version[:3].split(".")) + else: + requires_py = False + + info = create_info(name, version, build_number, requires_py) + tarbz2_fn = ("{name}-{version}-{build}".format(**info)) + CONDA_PACKAGE_EXTENSION_V1 + create_conda_pkg(prefix, files, info, tarbz2_fn) + print("# success") + print(tarbz2_fn) + return tarbz2_fn + + +def which_package(path): + """Return the package containing the path. + + Provided the path of a (presumably) conda installed file, iterate over + the conda packages the file came from. Usually the iteration yields + only one package. + """ + from ..common.path import paths_equal + from ..core.prefix_data import PrefixData + + path = abspath(path) + prefix = which_prefix(path) + if prefix is None: + from ..exceptions import CondaVerificationError + + raise CondaVerificationError(f"could not determine conda prefix from: {path}") + + for prec in PrefixData(prefix).iter_records(): + if any(paths_equal(join(prefix, f), path) for f in prec["files"] or ()): + yield prec + + +def which_prefix(path): + """Return the prefix for the provided path. + + Provided the path of a (presumably) conda installed file, return the + environment prefix in which the file in located. + """ + prefix = abspath(path) + while True: + if isdir(join(prefix, "conda-meta")): + # we found the it, so let's return it + return prefix + if prefix == dirname(prefix): + # we cannot chop off any more directories, so we didn't find it + return None + prefix = dirname(prefix) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_pip.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_pip.py new file mode 100644 index 0000000000000000000000000000000000000000..7de9f1f9f1861076ecceb93fa2a7e033393f5cf5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_pip.py @@ -0,0 +1,33 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""PEP 621 compatible entry point used when `conda init` has not updated the user shell profile.""" + +import os +import sys +from logging import getLogger + +log = getLogger(__name__) + + +def pip_installed_post_parse_hook(args, p): + from .. import CondaError + + if args.cmd not in ("init", "info"): + raise CondaError( + "Conda has not been initialized.\n" + "\n" + "To enable full conda functionality, please run 'conda init'.\n" + "For additional information, see 'conda init --help'.\n" + ) + + +def main(*args, **kwargs): + from .main import main + + os.environ["CONDA_PIP_UNINITIALIZED"] = "true" + kwargs["post_parse_hook"] = pip_installed_post_parse_hook + return main(*args, **kwargs) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_remove.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_remove.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc67e305fe2e82ec9a83cb9ea68fda444208f57 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_remove.py @@ -0,0 +1,234 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda remove`. + +Removes the specified packages from an existing environment. +""" + +import logging +from argparse import ArgumentParser, Namespace, _SubParsersAction + +from ..reporters import confirm_yn + +log = logging.getLogger(__name__) + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..common.constants import NULL + from .actions import NullCountAction + from .helpers import ( + add_output_and_prompt_options, + add_parser_channels, + add_parser_frozen_env, + add_parser_networking, + add_parser_prefix, + add_parser_prune, + add_parser_pscheck, + add_parser_solver, + ) + + summary = "Remove a list of packages from a specified conda environment. " + description = dals( + f""" + {summary} + + Use `--all` flag to remove all packages and the environment itself. + + This command will also remove any package that depends on any of the + specified packages as well---unless a replacement can be found without + that dependency. If you wish to skip this dependency checking and remove + just the requested packages, add the '--force' option. Note however that + this may result in a broken environment, so use this with caution. + """ + ) + epilog = dals( + """ + Examples: + + Remove the package 'scipy' from the currently-active environment:: + + conda remove scipy + + Remove a list of packages from an environment 'myenv':: + + conda remove -n myenv scipy curl wheel + + Remove all packages from environment `myenv` and the environment itself:: + + conda remove -n myenv --all + + Remove all packages from the environment `myenv` but retain the environment:: + + conda remove -n myenv --all --keep-env + + """ + ) + + p = sub_parsers.add_parser( + "remove", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_frozen_env(p) + add_parser_pscheck(p) + + add_parser_prefix(p) + add_parser_channels(p) + + solver_mode_options = p.add_argument_group("Solver Mode Modifiers") + solver_mode_options.add_argument( + "--features", + action="store_true", + help="Remove features (instead of packages).", + ) + solver_mode_options.add_argument( + "--force-remove", + "--force", + action="store_true", + help="Forces removal of a package without removing packages that depend on it. " + "Using this option will usually leave your environment in a broken and " + "inconsistent state.", + dest="force_remove", + ) + solver_mode_options.add_argument( + "--no-pin", + action="store_true", + dest="ignore_pinned", + default=NULL, + help="Ignore pinned package(s) that apply to the current operation. " + "These pinned packages might come from a .condarc file or a file in " + "/conda-meta/pinned.", + ) + add_parser_prune(solver_mode_options) + add_parser_solver(solver_mode_options) + + add_parser_networking(p) + add_output_and_prompt_options(p) + + p.add_argument( + "--all", + action="store_true", + help="Remove all packages, i.e., the entire environment.", + ) + p.add_argument( + "--keep-env", + action="store_true", + help="Used with `--all`, delete all packages but keep the environment.", + ) + p.add_argument( + "package_names", + metavar="package_name", + action="store", + nargs="*", + help="Package names to remove from the environment.", + ) + p.add_argument( + "--dev", + action=NullCountAction, + help="Use `sys.executable -m conda` in wrapper scripts instead of CONDA_EXE. " + "This is mainly for use during tests where we test new conda sources " + "against old Python versions.", + dest="dev", + default=NULL, + ) + + p.set_defaults(func="conda.cli.main_remove.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import context + from ..core.envs_manager import unregister_env + from ..core.link import PrefixSetup, UnlinkLinkTransaction + from ..core.prefix_data import PrefixData + from ..exceptions import ( + CondaEnvException, + CondaEnvironmentError, + CondaValueError, + PackagesNotFoundError, + ) + from ..gateways.disk.delete import path_is_clean, rm_rf + from ..models.match_spec import MatchSpec + from .common import check_non_admin, specs_from_args + from .install import handle_txn + + if not (args.all or args.package_names): + raise CondaValueError( + 'no package names supplied,\n try "conda remove -h" for more details' + ) + + prefix_data = PrefixData.from_context() + prefix_data.assert_environment() + if context.protect_frozen_envs: + prefix_data.assert_not_frozen() + check_non_admin() + prefix = str(prefix_data.prefix_path) + + if args.all and prefix_data == PrefixData(context.default_prefix): + msg = "Cannot remove current environment. Deactivate and run conda remove again" + raise CondaEnvironmentError(msg) + + if args.all and prefix_data == PrefixData(context.default_activation_prefix): + raise CondaEnvException( + "Cannot remove an environment if it is configured as `default_activation_env`." + ) + + if args.all and path_is_clean(prefix): + return 0 + + if args.all: + if prefix_data.is_base(): + raise CondaEnvironmentError( + "cannot remove root environment, add -n NAME or -p PREFIX option" + ) + if not args.json: + print(f"\nRemove all packages in environment {prefix}:\n") + + if "package_names" in args: + stp = PrefixSetup( + target_prefix=prefix, + unlink_precs=tuple(PrefixData(prefix).iter_records()), + link_precs=(), + remove_specs=(), + update_specs=(), + neutered_specs={}, + ) + txn = UnlinkLinkTransaction(stp) + try: + handle_txn(txn, prefix, args, False, True) + except PackagesNotFoundError: + if not args.json: + print( + f"No packages found in {prefix}. Continuing environment removal" + ) + if not context.dry_run: + if not args.keep_env: + if not args.json: + confirm_yn( + f"Everything found within the environment ({prefix}), including " + "any conda environment configurations and any non-conda files, will " + "be deleted. Do you wish to continue?\n", + default="no", + dry_run=False, + ) + rm_rf(prefix) + unregister_env(prefix) + + return 0 + + else: + if args.features: + specs = tuple(MatchSpec(track_features=f) for f in set(args.package_names)) + else: + specs = specs_from_args(args.package_names) + channel_urls = () + subdirs = () + solver_backend = context.plugin_manager.get_cached_solver_backend() + solver = solver_backend(prefix, channel_urls, subdirs, specs_to_remove=specs) + txn = solver.solve_for_transaction() + handle_txn(txn, prefix, args, False, True) + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_rename.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_rename.py new file mode 100644 index 0000000000000000000000000000000000000000..e38e38520dd80ad1233e66dfc0ddf75ba57c9f96 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_rename.py @@ -0,0 +1,176 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda rename`. + +Renames an existing environment by cloning it and then removing the original environment. +""" + +from __future__ import annotations + +import os +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING + +from conda.deprecations import deprecated +from conda.exceptions import CondaEnvException + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from .helpers import add_output_and_prompt_options, add_parser_prefix + + summary = "Rename an existing environment." + description = dals( + f""" + {summary} + + This command renames a conda environment via its name (-n/--name) or + its prefix (-p/--prefix). + + The base environment and the currently-active environment cannot be renamed. + """ + ) + epilog = dals( + """ + Examples:: + + conda rename -n test123 test321 + + conda rename --name test123 test321 + + conda rename -p path/to/test123 test321 + + conda rename --prefix path/to/test123 test321 + + """ + ) + + p = sub_parsers.add_parser( + "rename", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + # Add name and prefix args + add_parser_prefix(p) + + p.add_argument("destination", help="New name for the conda environment.") + + add_output_and_prompt_options(p) + + p.set_defaults(func="conda.cli.main_rename.execute") + + return p + + +@deprecated("25.9", "26.3", addendum="Use PrefixData.validate_path()") +def check_protected_dirs(prefix: str | Path, json: bool = False) -> None: + """Ensure that the new prefix does not contain protected directories.""" + from conda.core.prefix_data import PrefixData + + if PrefixData(Path(prefix).parent).is_environment(): + raise CondaEnvException( + f"The specified prefix '{prefix}' " + "appears to be a top level directory within an existing conda environment " + "(i.e., {history_file} exists). Creating an environment in this location " + "has the potential to irreversibly corrupt your conda installation and/or " + "other conda environments, please choose a different location for your " + "new conda environment. Aborting.", + json, + ) + + +@deprecated( + "25.9", + "26.3", + addendum="Use PrefixData.validate_path(), PrefixData.validate_name()", +) +def validate_src() -> str: + """ + Ensure that we are receiving at least one valid value for the environment + to be renamed and that the "base" environment is not being renamed + """ + from ..base.context import context + from .install import validate_prefix_exists + + prefix = Path(context.target_prefix) + validate_prefix_exists(prefix) + + if prefix.samefile(context.root_prefix): + raise CondaEnvException("The 'base' environment cannot be renamed") + if context.active_prefix and prefix.samefile(context.active_prefix): + raise CondaEnvException("Cannot rename the active environment") + else: + check_protected_dirs(prefix) + + return str(prefix) + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + """Executes the command for renaming an existing environment.""" + from ..base.constants import DRY_RUN_PREFIX + from ..base.context import context + from ..cli import install + from ..core.prefix_data import PrefixData + from ..gateways.disk.delete import rm_rf + from ..gateways.disk.update import rename_context + + # Validate source + source_prefix_data = PrefixData.from_context() + source_prefix_data.assert_environment() + if source_prefix_data.is_base(): + raise CondaEnvException("The 'base' environment cannot be renamed") + if context.active_prefix and source_prefix_data.prefix_path.samefile( + context.active_prefix + ): + raise CondaEnvException("Cannot rename the active environment") + + if source_prefix_data == PrefixData(context.default_activation_prefix): + raise CondaEnvException( + "Cannot rename an environment if it is configured as `default_activation_env`." + ) + + source = str(source_prefix_data.prefix_path) + + # Validate destination + if os.sep in args.destination: + dest_prefix_data = PrefixData(args.destination) + dest_prefix_data.validate_path(expand_path=True) + else: + dest_prefix_data = PrefixData.from_name(args.destination) + destination = str(dest_prefix_data.prefix_path) + if not args.yes and dest_prefix_data.exists(): + raise CondaEnvException( + f"The environment '{dest_prefix_data.prefix_path}' already exists. Override with --yes." + ) + + def clone_and_remove() -> None: + actions: tuple[partial, ...] = ( + partial( + install.clone, + source, + destination, + quiet=context.quiet, + json=context.json, + ), + partial(rm_rf, source), + ) + + # We now either run collected actions or print dry run statement + for func in actions: + if args.dry_run: + print(f"{DRY_RUN_PREFIX} {func.func.__name__} {','.join(func.args)}") + else: + func() + + if args.yes: + with rename_context(destination, dry_run=args.dry_run): + clone_and_remove() + else: + clone_and_remove() + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_run.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_run.py new file mode 100644 index 0000000000000000000000000000000000000000..2450d140120f62142115f43a692d4a271e7592fe --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_run.py @@ -0,0 +1,153 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda run`. + +Runs the provided command within the specified environment. +""" + +import os +import sys +from argparse import REMAINDER, ArgumentParser, Namespace, _SubParsersAction +from logging import getLogger + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..common.constants import NULL + from .actions import NullCountAction + from .helpers import add_parser_prefix, add_parser_verbose + + summary = "Run an executable in a conda environment." + description = summary + epilog = dals( + """ + Example:: + + $ conda create -y -n my-python-env python=3 + $ conda run -n my-python-env python --version + + Use '--' to separate `conda run`'s options from the executable's options:: + + $ conda run -n my-python-env -- python -v + $ conda run -v -n my-python-env -- tar -tvf file.tar + """ + ) + + p = sub_parsers.add_parser( + "run", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + add_parser_prefix(p) + add_parser_verbose(p) + + p.add_argument( + "--dev", + action=NullCountAction, + help="Sets `CONDA_EXE` to `python -m conda`, assuming the current " + "working directory contains the root of conda development sources. " + "This is mainly for use during tests where we test new conda sources " + "against old Python versions.", + dest="dev", + default=NULL, + ) + + p.add_argument( + "--debug-wrapper-scripts", + action=NullCountAction, + help="When this is set, where implemented, the shell wrapper scripts" + "will use the echo command to print debugging information to " + "stderr (standard error).", + dest="debug_wrapper_scripts", + default=NULL, + ) + p.add_argument( + "--cwd", + help="Current working directory for command to run in. Defaults to " + "the user's current working directory if no directory is specified.", + default=os.getcwd(), + ) + p.add_argument( + "-s", + "--no-capture-output", + "--live-stream", + action="store_true", + help="Don't capture stdout/stderr (standard out/standard error).", + default=False, + ) + + p.add_argument( + "executable_call", + nargs=REMAINDER, + help="Executable name, with additional arguments to be passed to the executable " + "on invocation. Use '--' to separate conda options from executable options.", + ) + + p.set_defaults(func="conda.cli.main_run.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..base.context import context + from ..common.compat import encode_environment + from ..core.prefix_data import PrefixData + from ..exceptions import ArgumentError + from ..gateways.disk.delete import rm_rf + from ..gateways.subprocess import subprocess_call + from ..utils import wrap_subprocess_call + + prefix_data = PrefixData.from_context() + prefix_data.assert_environment() + + # Used to separate subcommand from 'conda run' options + # e.g. conda run -v -- tar -tvf file.tar + if args.executable_call and args.executable_call[0] == "--": + args.executable_call = args.executable_call[1:] + + if not args.executable_call: + raise ArgumentError("No command specified. Please provide a command to run.") + + # create run script + script, command = wrap_subprocess_call( + context.root_prefix, + str(prefix_data.prefix_path), + args.dev, + args.debug_wrapper_scripts, + args.executable_call, + ) + + # run script + response = subprocess_call( + command, + env=encode_environment(os.environ.copy()), + path=args.cwd, + raise_on_error=False, + capture_output=not args.no_capture_output, + ) + + # display stdout/stderr if it was captured + if not args.no_capture_output: + if response.stdout: + print(response.stdout, file=sys.stdout, end="") + if response.stderr: + print(response.stderr, file=sys.stderr, end="") + + # log error + if response.rc != 0: + log = getLogger(__name__) + log.error( + f"`conda run {' '.join(args.executable_call)}` failed. (See above for error)" + ) + + # remove script + if "CONDA_TEST_SAVE_TEMPS" not in os.environ: + rm_rf(script) + else: + log = getLogger(__name__) + log.warning(f"CONDA_TEST_SAVE_TEMPS :: retaining main_run script {script}") + + return response.rc diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_search.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_search.py new file mode 100644 index 0000000000000000000000000000000000000000..df990a32a838d83467e4726c0e8b32ba5d469733 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_search.py @@ -0,0 +1,343 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda search`. + +Query channels for packages matching the provided package spec. +""" + +from __future__ import annotations + +from argparse import SUPPRESS +from collections import defaultdict +from datetime import datetime, timezone +from typing import TYPE_CHECKING + +from .helpers import _ValidatePackages + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + from ..models.records import PackageRecord + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..common.constants import NULL + from .helpers import ( + add_parser_channels, + add_parser_json, + add_parser_known, + add_parser_networking, + ) + + summary = "Search for packages and display associated information using the MatchSpec format." + description = dals( + f""" + {summary} + + MatchSpec is a query language for conda packages. + """ + ) + epilog = dals( + """ + Examples: + + Search for a specific package named 'scikit-learn':: + + conda search scikit-learn + + Search for packages containing 'scikit' in the package name:: + + conda search *scikit* + + Note that your shell may expand '*' before handing the command over to conda. + Therefore, it is sometimes necessary to use single or double quotes around the query:: + + conda search '*scikit' + conda search "*scikit*" + + Search for packages for 64-bit Linux (by default, packages for your current + platform are shown):: + + conda search numpy[subdir=linux-64] + + Search for a specific version of a package:: + + conda search 'numpy>=1.12' + + Search for a package on a specific channel:: + + conda search conda-forge::numpy + conda search 'numpy[channel=conda-forge, subdir=osx-64]' + """ + ) + + p = sub_parsers.add_parser( + "search", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + p.add_argument( + "--envs", + action="store_true", + help="Search all of the current user's environments. If run as Administrator " + "(on Windows) or UID 0 (on unix), search all known environments on the system.", + ) + p.add_argument( + "-i", + "--info", + action="store_true", + help="Provide detailed information about each package.", + ) + p.add_argument( + "--subdir", + "--platform", + action="store", + dest="subdir", + help="Search the given subdir. Should be formatted like 'osx-64', 'linux-32', " + "'win-64', and so on. The default is to search the current platform.", + default=NULL, + ) + p.add_argument( + "--skip-flexible-search", + action="store_true", + help="Do not perform flexible search if initial search fails.", + ) + p.add_argument( + "match_spec", + default="*", + nargs="?", + action=_ValidatePackages, + help=SUPPRESS, + ) + p.add_argument( + "--canonical", + action="store_true", + help=SUPPRESS, + ) + p.add_argument( + "-f", + "--full-name", + action="store_true", + help=SUPPRESS, + ) + p.add_argument( + "--names-only", + action="store_true", + help=SUPPRESS, + ) + add_parser_known(p) + p.add_argument( + "-o", + "--outdated", + action="store_true", + help=SUPPRESS, + ) + p.add_argument( + "--spec", + action="store_true", + help=SUPPRESS, + ) + p.add_argument( + "--reverse-dependency", + action="store_true", + # help="Perform a reverse dependency search. Use 'conda search package --info' " + # "to see the dependencies of a package.", + help=SUPPRESS, # TODO: re-enable once we have --reverse-dependency working again + ) + + add_parser_channels(p) + add_parser_networking(p) + add_parser_json(p) + p.set_defaults(func="conda.cli.main_search.execute") + + return p + + +def execute(args: Namespace, parser: ArgumentParser) -> int: + """ + Implements `conda search` commands. + + `conda search ` searches channels for packages. + `conda search --envs` searches environments for packages. + + """ + from ..base.context import context + from ..cli.common import stdout_json + from ..core.envs_manager import query_all_prefixes + from ..core.subdir_data import SubdirData + from ..models.match_spec import MatchSpec + from ..models.records import PackageRecord + from ..models.version import VersionOrder + from ..reporters import get_spinner + + spec = MatchSpec(args.match_spec) + if spec.get_exact_value("subdir"): + subdirs = (spec.get_exact_value("subdir"),) + else: + subdirs = context.subdirs + + if args.envs: + with get_spinner(f"Searching environments for {spec}"): + prefix_matches = query_all_prefixes(spec) + ordered_result = tuple( + { + "location": prefix, + "package_records": tuple( + sorted( + ( + PackageRecord.from_objects(prefix_rec) + for prefix_rec in prefix_recs + ), + key=lambda prec: prec._pkey, + ) + ), + } + for prefix, prefix_recs in prefix_matches + ) + if context.json: + stdout_json(ordered_result) + elif args.info: + for pkg_group in ordered_result: + for prec in pkg_group["package_records"]: + pretty_record(prec) + else: + builder = [ + "# %-13s %15s %15s %-20s %-20s" + % ( + "Name", + "Version", + "Build", + "Channel", + "Location", + ) + ] + for pkg_group in ordered_result: + for prec in pkg_group["package_records"]: + builder.append( + "%-15s %15s %15s %-20s %-20s" + % ( + prec.name, + prec.version, + prec.build, + prec.channel.name, + pkg_group["location"], + ) + ) + print("\n".join(builder)) + return 0 + + with get_spinner("Loading channels"): + spec_channel = spec.get_exact_value("channel") + channel_urls = (spec_channel,) if spec_channel else context.channels + + matches = sorted( + SubdirData.query_all(spec, channel_urls, subdirs), + key=lambda rec: (rec.name, VersionOrder(rec.version), rec.build), + ) + if not matches and not args.skip_flexible_search and spec.get_exact_value("name"): + flex_spec = MatchSpec(spec, name=f"*{spec.name}*") + if not context.json: + print(f"No match found for: {spec}. Search: {flex_spec}") + matches = sorted( + SubdirData.query_all(flex_spec, channel_urls, subdirs), + key=lambda rec: (rec.name, VersionOrder(rec.version), rec.build), + ) + + if not matches: + from ..exceptions import PackagesNotFoundError + from ..models.channel import all_channel_urls + + raise PackagesNotFoundError([spec], all_channel_urls(context.channels, subdirs)) + + if context.json: + json_obj = defaultdict(list) + for match in matches: + json_obj[match.name].append(match) + stdout_json(json_obj) + + elif args.info: + for record in matches: + pretty_record(record) + + else: + builder = [ + "# %-18s %15s %15s %-20s" + % ( + "Name", + "Version", + "Build", + "Channel", + ) + ] + for record in matches: + builder.append( + "%-20s %15s %15s %-20s" + % ( + record.name, + record.version, + record.build, + record.channel.name, + ) + ) + print("\n".join(builder)) + return 0 + + +def _pretty_record_format(record: PackageRecord) -> str: + """ + Format a `PackageRecord` for `pretty_record()` + """ + + from ..common.io import dashlist + from ..utils import human_bytes + + def push_line(display_name, attr_name): + value = getattr(record, attr_name, None) + if value is not None: + builder.append("%-12s: %s" % (display_name, value)) + + builder = [] + builder.append(f"{record.name} {record.version} {record.build}") + builder.append("-" * len(builder[0])) + + push_line("file name", "fn") + push_line("name", "name") + push_line("version", "version") + push_line("build", "build") + push_line("build number", "build_number") + size = getattr(record, "size", None) + if size is not None: + builder.append("%-12s: %s" % ("size", human_bytes(size))) + push_line("license", "license") + push_line("subdir", "subdir") + push_line("url", "url") + push_line("md5", "md5") + if record.timestamp and isinstance(record.timestamp, (int, float)): + date_str = datetime.fromtimestamp(record.timestamp, timezone.utc).strftime( + "%Y-%m-%d %H:%M:%S %Z" + ) + builder.append("%-12s: %s" % ("timestamp", date_str)) + if record.track_features: + builder.append( + "%-12s: %s" % ("track_features", dashlist(record.track_features)) + ) + if record.constrains: + builder.append("%-12s: %s" % ("constraints", dashlist(record.constrains))) + builder.append( + "%-12s: %s" + % ("dependencies", dashlist(record.depends) if record.depends else "[]") + ) + builder.append("\n") + return "\n".join(builder) + + +def pretty_record(record: PackageRecord, print=print) -> None: + """ + Pretty prints a `PackageRecord`. + + :param record: The `PackageRecord` object to print. + """ + print(_pretty_record_format(record)) diff --git a/miniconda3/lib/python3.13/site-packages/conda/cli/main_update.py b/miniconda3/lib/python3.13/site-packages/conda/cli/main_update.py new file mode 100644 index 0000000000000000000000000000000000000000..d5dda1f4456bb6cc32181899dc8dae88bd483840 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/cli/main_update.py @@ -0,0 +1,129 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""CLI implementation for `conda update`. + +Updates the specified packages in an existing environment. +""" + +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING + +from ..notices import notices + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + + +def configure_parser(sub_parsers: _SubParsersAction, **kwargs) -> ArgumentParser: + from ..auxlib.ish import dals + from ..common.constants import NULL + from .helpers import ( + add_parser_create_install_update, + add_parser_frozen_env, + add_parser_prune, + add_parser_solver, + add_parser_update_modifiers, + ) + + summary = "Update conda packages to the latest compatible version." + description = dals( + f""" + {summary} + + This command accepts a list of package names and updates them to the latest + versions that are compatible with all other packages in the environment. + + Conda attempts to install the newest versions of the requested packages. To + accomplish this, it may update some packages that are already installed, or + install additional packages. To prevent existing packages from updating, + use the --no-update-deps option. This may force conda to install older + versions of the requested packages, and it does not prevent additional + dependency packages from being installed. + """ + ) + epilog = dals( + """ + Examples: + + conda update -n myenv scipy + + """ + ) + + p = sub_parsers.add_parser( + "update", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + add_parser_frozen_env(p) + solver_mode_options, package_install_options, _ = add_parser_create_install_update( + p + ) + + add_parser_prune(solver_mode_options) + add_parser_solver(solver_mode_options) + solver_mode_options.add_argument( + "--force-reinstall", + action="store_true", + default=NULL, + help="Ensure that any user-requested package for the current operation is uninstalled and " + "reinstalled, even if that package already exists in the environment.", + ) + add_parser_update_modifiers(solver_mode_options) + + package_install_options.add_argument( + "--clobber", + action="store_true", + default=NULL, + help="Allow clobbering of overlapping file paths within packages, " + "and suppress related warnings.", + ) + p.set_defaults(func="conda.cli.main_update.execute") + + return p + + +@notices +def execute(args: Namespace, parser: ArgumentParser) -> int: + from ..auxlib.ish import dals + from ..base.constants import UpdateModifier + from ..base.context import context + from ..exceptions import CondaValueError + from .common import validate_environment_files_consistency + from .install import install + + if context.force: + print( + "\n\n" + "WARNING: The --force flag will be removed in a future conda release.\n" + " See 'conda update --help' for details about the --force-reinstall\n" + " and --clobber flags.\n" + "\n", + file=sys.stderr, + ) + + # Ensure provided combination of command line argments are valid + # One of --file or packages or --update-all must be specified + if not ( + args.file + or args.packages + or context.update_modifier == UpdateModifier.UPDATE_ALL + ): + raise CondaValueError( + dals( + """ + no package names supplied + # Example: conda update -n myenv scipy + """ + ) + ) + + # Validate that input files are of the same format type + validate_environment_files_consistency(args.file) + + install(args, parser, "update") + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c55dee5851a0463b8f2cf767899fc9396c4b09b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/__init__.py @@ -0,0 +1,11 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Code in ``conda.common`` is not conda-specific. Technically, it sits *aside* the application +stack and not *within* the stack. It is able to stand independently on its own. +The *only* allowed imports of conda code in ``conda.common`` modules are imports of other +``conda.common`` modules. + +If objects are needed from other parts of conda, they should be passed directly as arguments to +functions and methods. +""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/_logic.py b/miniconda3/lib/python3.13/site-packages/conda/common/_logic.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3e0e92b3fa7e8cc0c1076d31b18ede40e51d35 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/_logic.py @@ -0,0 +1,781 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import sys +from array import array +from itertools import combinations +from logging import DEBUG, getLogger + +from .constants import TRACE + +log = getLogger(__name__) + + +TRUE = sys.maxsize +FALSE = -TRUE + + +class _ClauseList: + """Storage for the CNF clauses, represented as a list of tuples of ints.""" + + def __init__(self): + self._clause_list = [] + # Methods append and extend are directly bound for performance reasons, + # to avoid call overhead and lookups. + self.append = self._clause_list.append + self.extend = self._clause_list.extend + + def get_clause_count(self): + """Return number of stored clauses.""" + return len(self._clause_list) + + def save_state(self): + """ + Get state information to be able to revert temporary additions of + supplementary clauses. _ClauseList: state is simply the number of clauses. + """ + return len(self._clause_list) + + def restore_state(self, saved_state): + """ + Restore state saved via `save_state`. + Removes clauses that were added after the state has been saved. + """ + len_clauses = saved_state + self._clause_list[len_clauses:] = [] + + def as_list(self): + """Return clauses as a list of tuples of ints.""" + return self._clause_list + + def as_array(self): + """Return clauses as a flat int array, each clause being terminated by 0.""" + clause_array = array("i") + for c in self._clause_list: + clause_array.extend(c) + clause_array.append(0) + return clause_array + + +class _ClauseArray: + """ + Storage for the CNF clauses, represented as a flat int array. + Each clause is terminated by int(0). + """ + + def __init__(self): + self._clause_array = array("i") + # Methods append and extend are directly bound for performance reasons, + # to avoid call overhead and lookups. + self._array_append = self._clause_array.append + self._array_extend = self._clause_array.extend + + def extend(self, clauses): + for clause in clauses: + self.append(clause) + + def append(self, clause): + self._array_extend(clause) + self._array_append(0) + + def get_clause_count(self): + """ + Return number of stored clauses. + This is an O(n) operation since we don't store the number of clauses + explicitly due to performance reasons (Python interpreter overhead in + self.append). + """ + return self._clause_array.count(0) + + def save_state(self): + """ + Get state information to be able to revert temporary additions of + supplementary clauses. _ClauseArray: state is the length of the int + array, NOT number of clauses. + """ + return len(self._clause_array) + + def restore_state(self, saved_state): + """ + Restore state saved via `save_state`. + Removes clauses that were added after the state has been saved. + """ + len_clause_array = saved_state + self._clause_array[len_clause_array:] = array("i") + + def as_list(self): + """Return clauses as a list of tuples of ints.""" + clause = [] + for v in self._clause_array: + if v == 0: + yield tuple(clause) + clause.clear() + else: + clause.append(v) + + def as_array(self): + """Return clauses as a flat int array, each clause being terminated by 0.""" + return self._clause_array + + +class _SatSolver: + """Simple wrapper to call a SAT solver given a _ClauseList/_ClauseArray instance.""" + + def __init__(self, **run_kwargs): + self._run_kwargs = run_kwargs or {} + self._clauses = _ClauseList() + # Bind some methods of _clauses to reduce lookups and call overhead. + self.add_clause = self._clauses.append + self.add_clauses = self._clauses.extend + + def get_clause_count(self): + return self._clauses.get_clause_count() + + def as_list(self): + return self._clauses.as_list() + + def save_state(self): + return self._clauses.save_state() + + def restore_state(self, saved_state): + return self._clauses.restore_state(saved_state) + + def run(self, m, **kwargs): + run_kwargs = self._run_kwargs.copy() + run_kwargs.update(kwargs) + solver = self.setup(m, **run_kwargs) + sat_solution = self.invoke(solver) + solution = self.process_solution(sat_solution) + return solution + + def setup(self, m, **kwargs): + """Create a solver instance, add the clauses to it, and return it.""" + raise NotImplementedError() + + def invoke(self, solver): + """Start the actual SAT solving and return the calculated solution.""" + raise NotImplementedError() + + def process_solution(self, sat_solution): + """ + Process the solution returned by self.invoke. + Returns a list of satisfied variables or None if no solution is found. + """ + raise NotImplementedError() + + +class _PycoSatSolver(_SatSolver): + def setup(self, m, limit=0, **kwargs): + from pycosat import itersolve + + # NOTE: The iterative solving isn't actually used here, we just call + # itersolve to separate setup from the actual run. + return itersolve(self._clauses.as_list(), vars=m, prop_limit=limit) + # If we add support for passing the clauses as an integer stream to the + # solvers, we could also use self._clauses.as_array like this: + # return itersolve(self._clauses.as_array(), vars=m, prop_limit=limit) + + def invoke(self, iter_sol): + try: + sat_solution = next(iter_sol) + except StopIteration: + sat_solution = "UNSAT" + del iter_sol + return sat_solution + + def process_solution(self, sat_solution): + if sat_solution in ("UNSAT", "UNKNOWN"): + return None + return sat_solution + + +class _PyCryptoSatSolver(_SatSolver): + def setup(self, m, threads=1, **kwargs): + from pycryptosat import Solver + + solver = Solver(threads=threads) + solver.add_clauses(self._clauses.as_list()) + return solver + + def invoke(self, solver): + sat, sat_solution = solver.solve() + if not sat: + sat_solution = None + return sat_solution + + def process_solution(self, solution): + if not solution: + return None + # The first element of the solution is always None. + solution = [i for i, b in enumerate(solution) if b] + return solution + + +class _PySatSolver(_SatSolver): + def setup(self, m, **kwargs): + from pysat.solvers import Glucose4 + + solver = Glucose4() + solver.append_formula(self._clauses.as_list()) + return solver + + def invoke(self, solver): + if not solver.solve(): + sat_solution = None + else: + sat_solution = solver.get_model() + solver.delete() + return sat_solution + + def process_solution(self, sat_solution): + if sat_solution is None: + solution = None + else: + solution = sat_solution + return solution + + +_sat_solver_str_to_cls = { + "pycosat": _PycoSatSolver, + "pycryptosat": _PyCryptoSatSolver, + "pysat": _PySatSolver, +} + +_sat_solver_cls_to_str = {cls: string for string, cls in _sat_solver_str_to_cls.items()} + + +# Code that uses special cases (generates no clauses) is in ADTs/FEnv.h in +# minisatp. Code that generates clauses is in Hardware_clausify.cc (and are +# also described in the paper, "Translating Pseudo-Boolean Constraints into +# SAT," Eén and Sörensson). +class Clauses: + def __init__(self, m=0, sat_solver_str=_sat_solver_cls_to_str[_PycoSatSolver]): + self.unsat = False + self.m = m + + try: + sat_solver_cls = _sat_solver_str_to_cls[sat_solver_str] + except KeyError: + raise NotImplementedError(f"Unknown SAT solver: {sat_solver_str}") + self._sat_solver = sat_solver_cls() + + # Bind some methods of _sat_solver to reduce lookups and call overhead. + self.add_clause = self._sat_solver.add_clause + self.add_clauses = self._sat_solver.add_clauses + + def get_clause_count(self): + return self._sat_solver.get_clause_count() + + def as_list(self): + return self._sat_solver.as_list() + + def new_var(self): + m = self.m + 1 + self.m = m + return m + + def assign(self, vals): + if isinstance(vals, tuple): + x = self.new_var() + self.add_clauses((-x,) + y for y in vals[0]) + self.add_clauses((x,) + y for y in vals[1]) + return x + return vals + + def Combine(self, args, polarity): + if any(v == FALSE for v in args): + return FALSE + args = [v for v in args if v != TRUE] + nv = len(args) + if nv == 0: + return TRUE + if nv == 1: + return args[0] + if all(isinstance(v, tuple) for v in args): + return (sum((v[0] for v in args), []), sum((v[1] for v in args), [])) + else: + return self.All(map(self.assign, args), polarity) + + def Eval(self, func, args, polarity): + saved_state = self._sat_solver.save_state() + vals = func(*args, polarity=polarity) + # eval without assignment: + if isinstance(vals, tuple): + self.add_clauses(vals[0]) + self.add_clauses(vals[1]) + elif vals not in {TRUE, FALSE}: + self.add_clause((vals if polarity else -vals,)) + else: + self._sat_solver.restore_state(saved_state) + self.unsat = self.unsat or (vals == TRUE) != polarity + + def Prevent(self, func, *args): + self.Eval(func, args, polarity=False) + + def Require(self, func, *args): + self.Eval(func, args, polarity=True) + + def Not(self, x, polarity=None, add_new_clauses=False): + return -x + + def And(self, f, g, polarity, add_new_clauses=False): + if f == FALSE or g == FALSE: + return FALSE + if f == TRUE: + return g + if g == TRUE: + return f + if f == g: + return f + if f == -g: + return FALSE + if g < f: + f, g = g, f + if add_new_clauses: + # This is equivalent to running self.assign(pval, nval) on + # the (pval, nval) tuple we return below. Duplicating the code here + # is an important performance tweak to avoid the costly generator + # expressions and tuple additions in self.assign. + x = self.new_var() + if polarity in (True, None): + self.add_clauses( + [ + ( + -x, + f, + ), + ( + -x, + g, + ), + ] + ) + if polarity in (False, None): + self.add_clauses([(x, -f, -g)]) + return x + pval = [(f,), (g,)] if polarity in (True, None) else [] + nval = [(-f, -g)] if polarity in (False, None) else [] + return pval, nval + + def Or(self, f, g, polarity, add_new_clauses=False): + if f == TRUE or g == TRUE: + return TRUE + if f == FALSE: + return g + if g == FALSE: + return f + if f == g: + return f + if f == -g: + return TRUE + if g < f: + f, g = g, f + if add_new_clauses: + x = self.new_var() + if polarity in (True, None): + self.add_clauses([(-x, f, g)]) + if polarity in (False, None): + self.add_clauses( + [ + ( + x, + -f, + ), + ( + x, + -g, + ), + ] + ) + return x + pval = [(f, g)] if polarity in (True, None) else [] + nval = [(-f,), (-g,)] if polarity in (False, None) else [] + return pval, nval + + def Xor(self, f, g, polarity, add_new_clauses=False): + if f == FALSE: + return g + if f == TRUE: + return self.Not(g, polarity, add_new_clauses=add_new_clauses) + if g == FALSE: + return f + if g == TRUE: + return -f + if f == g: + return FALSE + if f == -g: + return TRUE + if g < f: + f, g = g, f + if add_new_clauses: + x = self.new_var() + if polarity in (True, None): + self.add_clauses([(-x, f, g), (-x, -f, -g)]) + if polarity in (False, None): + self.add_clauses([(x, -f, g), (x, f, -g)]) + return x + pval = [(f, g), (-f, -g)] if polarity in (True, None) else [] + nval = [(-f, g), (f, -g)] if polarity in (False, None) else [] + return pval, nval + + def ITE(self, c, t, f, polarity, add_new_clauses=False): + if c == TRUE: + return t + if c == FALSE: + return f + if t == TRUE: + return self.Or(c, f, polarity, add_new_clauses=add_new_clauses) + if t == FALSE: + return self.And(-c, f, polarity, add_new_clauses=add_new_clauses) + if f == FALSE: + return self.And(c, t, polarity, add_new_clauses=add_new_clauses) + if f == TRUE: + return self.Or(t, -c, polarity, add_new_clauses=add_new_clauses) + if t == c: + return self.Or(c, f, polarity, add_new_clauses=add_new_clauses) + if t == -c: + return self.And(-c, f, polarity, add_new_clauses=add_new_clauses) + if f == c: + return self.And(c, t, polarity, add_new_clauses=add_new_clauses) + if f == -c: + return self.Or(t, -c, polarity, add_new_clauses=add_new_clauses) + if t == f: + return t + if t == -f: + return self.Xor(c, f, polarity, add_new_clauses=add_new_clauses) + if t < f: + t, f, c = f, t, -c + # Basically, c ? t : f is equivalent to (c AND t) OR (NOT c AND f) + # The third clause in each group is redundant but assists the unit + # propagation in the SAT solver. + if add_new_clauses: + x = self.new_var() + if polarity in (True, None): + self.add_clauses([(-x, -c, t), (-x, c, f), (-x, t, f)]) + if polarity in (False, None): + self.add_clauses([(x, -c, -t), (x, c, -f), (x, -t, -f)]) + return x + pval = [(-c, t), (c, f), (t, f)] if polarity in (True, None) else [] + nval = [(-c, -t), (c, -f), (-t, -f)] if polarity in (False, None) else [] + return pval, nval + + def All(self, iter, polarity=None): + vals = set() + for v in iter: + if v == TRUE: + continue + if v == FALSE or -v in vals: + return FALSE + vals.add(v) + nv = len(vals) + if nv == 0: + return TRUE + elif nv == 1: + return next(v for v in vals) + pval = [(v,) for v in vals] if polarity in (True, None) else [] + nval = [tuple(-v for v in vals)] if polarity in (False, None) else [] + return pval, nval + + def Any(self, iter, polarity): + vals = set() + for v in iter: + if v == FALSE: + continue + elif v == TRUE or -v in vals: + return TRUE + vals.add(v) + nv = len(vals) + if nv == 0: + return FALSE + elif nv == 1: + return next(v for v in vals) + pval = [tuple(vals)] if polarity in (True, None) else [] + nval = [(-v,) for v in vals] if polarity in (False, None) else [] + return pval, nval + + def AtMostOne_NSQ(self, vals, polarity): + combos = [] + for v1, v2 in combinations(map(self.Not, vals), 2): + combos.append(self.Or(v1, v2, polarity)) + return self.Combine(combos, polarity) + + def AtMostOne_BDD(self, vals, polarity=None): + literals = list(vals) + coeffs = [1] * len(literals) + return self.LinearBound(literals, coeffs, 0, 1, True, polarity) + + def ExactlyOne_NSQ(self, vals, polarity): + vals = list(vals) + v1 = self.AtMostOne_NSQ(vals, polarity) + v2 = self.Any(vals, polarity) + return self.Combine((v1, v2), polarity) + + def ExactlyOne_BDD(self, vals, polarity): + literals = list(vals) + coeffs = [1] * len(literals) + return self.LinearBound(literals, coeffs, 1, 1, True, polarity) + + def LB_Preprocess(self, literals, coeffs): + equation = [] + offset = 0 + for coeff, literal in zip(coeffs, literals): + if literal == TRUE: + offset += coeff + continue + if literal == FALSE or coeff == 0: + continue + if coeff < 0: + offset += coeff + coeff, literal = -coeff, -literal + equation.append((coeff, literal)) + coeffs, literals = tuple(zip(*sorted(equation))) or ((), ()) + return literals, coeffs, offset + + def BDD(self, literals, coeffs, nterms, lo, hi, polarity): + # The equation (coeffs x literals) is sorted in + # order of increasing coefficients. + # Then we take advantage of the following recurrence: + # l <= S + cN xN <= u + # => IF xN THEN l - cN <= S <= u - cN + # ELSE l <= S <= u + # we use memoization to prune common subexpressions + total = sum(c for c in coeffs[:nterms]) + target = (nterms - 1, 0, total) + call_stack = [target] + ret = {} + call_stack_append = call_stack.append + call_stack_pop = call_stack.pop + ret_get = ret.get + ITE = self.ITE + + csum = 0 + while call_stack: + ndx, csum, total = call_stack[-1] + lower_limit = lo - csum + upper_limit = hi - csum + if lower_limit <= 0 and upper_limit >= total: + ret[call_stack_pop()] = TRUE + continue + if lower_limit > total or upper_limit < 0: + ret[call_stack_pop()] = FALSE + continue + LA = literals[ndx] + LC = coeffs[ndx] + ndx -= 1 + total -= LC + hi_key = (ndx, csum if LA < 0 else csum + LC, total) + thi = ret_get(hi_key) + if thi is None: + call_stack_append(hi_key) + continue + lo_key = (ndx, csum + LC if LA < 0 else csum, total) + tlo = ret_get(lo_key) + if tlo is None: + call_stack_append(lo_key) + continue + # NOTE: The following ITE call is _the_ hotspot of the Python-side + # computations for the overall minimization run. For performance we + # avoid calling self.assign here via add_new_clauses=True. + # If we want to translate parts of the code to a compiled language, + # self.BDD (+ its downward call stack) is the prime candidate! + ret[call_stack_pop()] = ITE( + abs(LA), thi, tlo, polarity, add_new_clauses=True + ) + return ret[target] + + def LinearBound(self, literals, coeffs, lo, hi, preprocess, polarity): + if preprocess: + literals, coeffs, offset = self.LB_Preprocess(literals, coeffs) + lo -= offset + hi -= offset + nterms = len(coeffs) + if nterms and coeffs[-1] > hi: + nprune = sum(c > hi for c in coeffs) + log.log( + TRACE, "Eliminating %d/%d terms for bound violation", nprune, nterms + ) + nterms -= nprune + else: + nprune = 0 + # Tighten bounds + total = sum(c for c in coeffs[:nterms]) + if preprocess: + lo = max([lo, 0]) + hi = min([hi, total]) + if lo > hi: + return FALSE + if nterms == 0: + res = TRUE if lo == 0 else FALSE + else: + res = self.BDD(literals, coeffs, nterms, lo, hi, polarity) + if nprune: + prune = self.All([-a for a in literals[nterms:]], polarity) + res = self.Combine((res, prune), polarity) + return res + + def _run_sat(self, m, limit=0): + if log.isEnabledFor(DEBUG): + log.debug("Invoking SAT with clause count: %s", self.get_clause_count()) + solution = self._sat_solver.run(m, limit=limit) + return solution + + def sat(self, additional=None, includeIf=False, limit=0): + """ + Calculate a SAT solution for the current clause set. + + Returned is the list of those solutions. When the clauses are + unsatisfiable, an empty list is returned. + + """ + if self.unsat: + return None + if not self.m: + return [] + saved_state = self._sat_solver.save_state() + if additional: + + def preproc(eqs): + def preproc_(cc): + for c in cc: + if c == FALSE: + continue + yield c + if c == TRUE: + break + + for cc in eqs: + cc = tuple(preproc_(cc)) + if not cc: + yield cc + break + if cc[-1] != TRUE: + yield cc + + additional = list(preproc(additional)) + if additional: + if not additional[-1]: + return None + self.add_clauses(additional) + solution = self._run_sat(self.m, limit=limit) + if additional and (solution is None or not includeIf): + self._sat_solver.restore_state(saved_state) + return solution + + def minimize(self, literals, coeffs, bestsol=None, trymax=False): + """ + Minimize the objective function given by (coeff, integer) pairs in + zip(coeffs, literals). + The actual minimization is multiobjective: first, we minimize the + largest active coefficient value, then we minimize the sum. + """ + if bestsol is None or len(bestsol) < self.m: + log.debug("Clauses added, recomputing solution") + bestsol = self.sat() + if bestsol is None or self.unsat: + log.debug("Constraints are unsatisfiable") + return bestsol, sum(abs(c) for c in coeffs) + 1 if coeffs else 1 + if not coeffs: + log.debug("Empty objective, trivial solution") + return bestsol, 0 + + literals, coeffs, offset = self.LB_Preprocess(literals, coeffs) + maxval = max(coeffs) + + def peak_val(sol, objective_dict): + return max(objective_dict.get(s, 0) for s in sol) + + def sum_val(sol, objective_dict): + return sum(objective_dict.get(s, 0) for s in sol) + + lo = 0 + try0 = 0 + for peak in (True, False) if maxval > 1 else (False,): + if peak: + log.log(TRACE, "Beginning peak minimization") + objval = peak_val + else: + log.log(TRACE, "Beginning sum minimization") + objval = sum_val + + objective_dict = {a: c for c, a in zip(coeffs, literals)} + bestval = objval(bestsol, objective_dict) + + # If we got lucky and the initial solution is optimal, we still + # need to generate the constraints at least once + hi = bestval + m_orig = self.m + if log.isEnabledFor(DEBUG): + # This is only used for the log message below. + nz = self.get_clause_count() + saved_state = self._sat_solver.save_state() + if trymax and not peak: + try0 = hi - 1 + + log.log(TRACE, "Initial range (%d,%d)", lo, hi) + while True: + if try0 is None: + mid = (lo + hi) // 2 + else: + mid = try0 + if peak: + prevent = tuple(a for c, a in zip(coeffs, literals) if c > mid) + require = tuple( + a for c, a in zip(coeffs, literals) if lo <= c <= mid + ) + self.Prevent(self.Any, prevent) + if require: + self.Require(self.Any, require) + else: + self.Require(self.LinearBound, literals, coeffs, lo, mid, False) + + if log.isEnabledFor(DEBUG): + log.log( + TRACE, + "Bisection attempt: (%d,%d), (%d+%d) clauses", + lo, + mid, + nz, + self.get_clause_count() - nz, + ) + newsol = self.sat() + if newsol is None: + lo = mid + 1 + log.log(TRACE, "Bisection failure, new range=(%d,%d)", lo, hi) + if lo > hi: + # FIXME: This is not supposed to happen! + # TODO: Investigate and fix the cause. + break + # If this was a failure of the first test after peak minimization, + # then it means that the peak minimizer is "tight" and we don't need + # any further constraints. + else: + done = lo == mid + bestsol = newsol + bestval = objval(newsol, objective_dict) + hi = bestval + log.log(TRACE, "Bisection success, new range=(%d,%d)", lo, hi) + if done: + break + self.m = m_orig + # Since we only ever _add_ clauses and only remove then via + # restore_state, it's fine to test on equality only. + if self._sat_solver.save_state() != saved_state: + self._sat_solver.restore_state(saved_state) + self.unsat = False + try0 = None + + log.debug("Final %s objective: %d" % ("peak" if peak else "sum", bestval)) + if bestval == 0: + break + elif peak: + # Now that we've minimized the peak value, we can drop any terms + # with coefficients larger than this. Furthermore, since we know + # at least one peak will be active, our lower bound for the sum + # equals the peak. + literals = [a for c, a in zip(coeffs, literals) if c <= bestval] + coeffs = [c for c in coeffs if c <= bestval] + try0 = sum_val(bestsol, objective_dict) + lo = bestval + else: + log.debug("New peak objective: %d" % peak_val(bestsol, objective_dict)) + + return bestsol, bestval diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/_os/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/common/_os/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c63f283f3859bd4d368a431a62fc2fc45827046 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/_os/__init__.py @@ -0,0 +1,15 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from logging import getLogger + +from ..compat import on_win + +if on_win: + from .windows import get_free_space_on_windows as get_free_space + from .windows import is_admin_on_windows as is_admin +else: + from .unix import get_free_space_on_unix as get_free_space # noqa + from .unix import is_admin_on_unix as is_admin # noqa + + +log = getLogger(__name__) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/_os/linux.py b/miniconda3/lib/python3.13/site-packages/conda/common/_os/linux.py new file mode 100644 index 0000000000000000000000000000000000000000..969c90f8b1d029be96944d07d6f6173c2f6f3569 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/_os/linux.py @@ -0,0 +1,63 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from __future__ import annotations + +import os +from functools import cache +from logging import getLogger +from os.path import exists + +from ..compat import on_linux + +log = getLogger(__name__) + + +@cache +def linux_get_libc_version() -> tuple[str, str] | tuple[None, None]: + """If on linux, returns (libc_family, version), otherwise (None, None).""" + if not on_linux: + return None, None + + for name in ("CS_GNU_LIBC_VERSION", "CS_GNU_LIBPTHREAD_VERSION"): + try: + # check if os.confstr returned None + if value := os.confstr(name): + family, version = value.strip().split(" ") + break + except ValueError: + # ValueError: name is not defined in os.confstr_names + # ValueError: value is not of the form " " + pass + else: + family, version = "glibc", "2.5" + log.warning( + "Failed to detect libc family and version, assuming %s/%s", + family, + version, + ) + + # NPTL is just the name of the threading library, even though the + # version refers to that of uClibc. os.readlink() can help to try to + # figure out a better name instead. + if family == "NPTL": # pragma: no cover + for clib in ( + entry.path for entry in os.scandir("/lib") if entry.name[:7] == "libc.so" + ): + clib = os.readlink(clib) + if exists(clib): + if clib.startswith("libuClibc"): + if version.startswith("0."): + family = "uClibc" + else: + family = "uClibc-ng" + break + else: + # This could be some other C library; it is unlikely though. + family = "uClibc" + log.warning( + "Failed to detect non-glibc family, assuming %s/%s", + family, + version, + ) + + return family, version diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/_os/osx.py b/miniconda3/lib/python3.13/site-packages/conda/common/_os/osx.py new file mode 100644 index 0000000000000000000000000000000000000000..971be9b54f833b0d392de43e1f6e2231868bcc1f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/_os/osx.py @@ -0,0 +1,21 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import platform +from subprocess import check_output + + +def mac_ver() -> str: + """ + Returns macOS version, without compatibility modes for 11.x. + https://github.com/conda/conda/issues/13832 + If Python was compiled against macOS <=10.15, we might get 10.16 instead of 11.0. + For these cases, we must set SYSTEM_VERSION_COMPAT=0 and call sw_vers directly. + """ + distribution_version = platform.mac_ver()[0] + if distribution_version == "10.16": + return check_output( + ["/usr/bin/sw_vers", "-productVersion"], + env={"SYSTEM_VERSION_COMPAT": "0"}, + text=True, + ).strip() + return distribution_version diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/_os/unix.py b/miniconda3/lib/python3.13/site-packages/conda/common/_os/unix.py new file mode 100644 index 0000000000000000000000000000000000000000..33b6a7830dd91556b9bf9d719795fb994532a2ae --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/_os/unix.py @@ -0,0 +1,16 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import os +from logging import getLogger + +log = getLogger(__name__) + + +def get_free_space_on_unix(dir_name): + st = os.statvfs(dir_name) + return st.f_bavail * st.f_frsize + + +def is_admin_on_unix(): + # http://stackoverflow.com/a/1026626/2127762 + return os.geteuid() == 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/_os/windows.py b/miniconda3/lib/python3.13/site-packages/conda/common/_os/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..38d9f3a747b35edbd7dbd188db507c92413c059d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/_os/windows.py @@ -0,0 +1,191 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from enum import IntEnum +from logging import getLogger + +from ..compat import ensure_binary, on_win + +log = getLogger(__name__) + +if on_win: + from ctypes import ( + POINTER, + Structure, + WinError, + byref, + c_char_p, + c_int, + c_ulong, + c_ulonglong, + c_void_p, + c_wchar_p, + pointer, + sizeof, + windll, + ) + from ctypes.wintypes import BOOL, DWORD, HANDLE, HINSTANCE, HKEY, HWND + + PHANDLE = POINTER(HANDLE) + PDWORD = POINTER(DWORD) + SEE_MASK_NOCLOSEPROCESS = 0x00000040 + INFINITE = -1 + + WaitForSingleObject = windll.kernel32.WaitForSingleObject + WaitForSingleObject.argtypes = (HANDLE, DWORD) + WaitForSingleObject.restype = DWORD + + CloseHandle = windll.kernel32.CloseHandle + CloseHandle.argtypes = (HANDLE,) + CloseHandle.restype = BOOL + + class ShellExecuteInfo(Structure): + """ + https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-shellexecuteexa + https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/ns-shellapi-_shellexecuteinfoa + """ + + _fields_ = [ + ("cbSize", DWORD), + ("fMask", c_ulong), + ("hwnd", HWND), + ("lpVerb", c_char_p), + ("lpFile", c_char_p), + ("lpParameters", c_char_p), + ("lpDirectory", c_char_p), + ("nShow", c_int), + ("hInstApp", HINSTANCE), + ("lpIDList", c_void_p), + ("lpClass", c_char_p), + ("hKeyClass", HKEY), + ("dwHotKey", DWORD), + ("hIcon", HANDLE), + ("hProcess", HANDLE), + ] + + def __init__(self, **kwargs): + Structure.__init__(self) + self.cbSize = sizeof(self) + for field_name, field_value in kwargs.items(): + if isinstance(field_value, str): + field_value = ensure_binary(field_value) + setattr(self, field_name, field_value) + + PShellExecuteInfo = POINTER(ShellExecuteInfo) + ShellExecuteEx = windll.Shell32.ShellExecuteExA + ShellExecuteEx.argtypes = (PShellExecuteInfo,) + ShellExecuteEx.restype = BOOL + + +class SW(IntEnum): + HIDE = 0 + MAXIMIZE = 3 + MINIMIZE = 6 + RESTORE = 9 + SHOW = 5 + SHOWDEFAULT = 10 + SHOWMAXIMIZED = 3 + SHOWMINIMIZED = 2 + SHOWMINNOACTIVE = 7 + SHOWNA = 8 + SHOWNOACTIVATE = 4 + SHOWNORMAL = 1 + + +class ERROR(IntEnum): + ZERO = 0 + FILE_NOT_FOUND = 2 + PATH_NOT_FOUND = 3 + BAD_FORMAT = 11 + ACCESS_DENIED = 5 + ASSOC_INCOMPLETE = 27 + DDE_BUSY = 30 + DDE_FAIL = 29 + DDE_TIMEOUT = 28 + DLL_NOT_FOUND = 32 + NO_ASSOC = 31 + OOM = 8 + SHARE = 26 + + +def get_free_space_on_windows(dir_name): + result = None + free_bytes = c_ulonglong(0) + try: + windll.kernel32.GetDiskFreeSpaceExW( + c_wchar_p(dir_name), + None, + None, + pointer(free_bytes), + ) + result = free_bytes.value + except Exception as e: + log.info("%r", e) + return result + + +def is_admin_on_windows(): # pragma: unix no cover + # http://stackoverflow.com/a/1026626/2127762 + result = False + try: + result = windll.shell32.IsUserAnAdmin() != 0 + except Exception as e: # pragma: no cover + log.info("%r", e) + # result = 'unknown' + return result + + +def _wait_and_close_handle(process_handle): + """Waits until spawned process finishes and closes the handle for it.""" + try: + WaitForSingleObject(process_handle, INFINITE) + CloseHandle(process_handle) + except Exception as e: + log.info("%r", e) + + +def run_as_admin(args, wait=True): + """ + Run command line argument list (`args`) with elevated privileges. + + If `wait` is True, the process will block until completion. + + NOTES: + - no stdin / stdout / stderr pipe support + - does not automatically quote arguments (i.e. for paths that may contain spaces) + See: + - http://stackoverflow.com/a/19719292/1170370 on 20160407 MCS. + - msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx + - https://github.com/ContinuumIO/menuinst/blob/master/menuinst/windows/win_elevate.py + - https://github.com/saltstack/salt-windows-install/blob/master/deps/salt/python/App/Lib/site-packages/win32/Demos/pipes/runproc.py # NOQA + - https://github.com/twonds/twisted/blob/master/twisted/internet/_dumbwin32proc.py + - https://stackoverflow.com/a/19982092/2127762 + - https://www.codeproject.com/Articles/19165/Vista-UAC-The-Definitive-Guide + - https://github.com/JustAMan/pyWinClobber/blob/master/win32elevate.py + """ + arg0 = args[0] + param_str = " ".join(args[1:] if len(args) > 1 else ()) + hprocess = None + error_code = None + try: + execute_info = ShellExecuteInfo( + fMask=SEE_MASK_NOCLOSEPROCESS, + hwnd=None, + lpVerb="runas", + lpFile=arg0, + lpParameters=param_str, + lpDirectory=None, + nShow=SW.HIDE, + ) + successful = ShellExecuteEx(byref(execute_info)) + hprocess = execute_info.hProcess + except Exception as e: + successful = False + error_code = e + log.info("%r", e) + + if not successful: + error_code = WinError() + elif wait: + _wait_and_close_handle(execute_info.hProcess) + + return hprocess, error_code diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/compat.py b/miniconda3/lib/python3.13/site-packages/conda/common/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..1f7d85bff1f24e38db35f4f4982310c9003e5d8f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/compat.py @@ -0,0 +1,111 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common compatibility code.""" +# Try to keep compat small because it's imported by everything +# What is compat, and what isn't? +# If a piece of code is "general" and used in multiple modules, it goes here. +# If it's only used in one module, keep it in that module, preferably near the top. +# This module should contain ONLY stdlib imports. + +import builtins +import sys + +on_win = bool(sys.platform == "win32") +on_mac = bool(sys.platform == "darwin") +on_linux = bool(sys.platform == "linux") + +# Control some tweakables that will be removed finally. +ENCODE_ENVIRONMENT = True + + +def encode_for_env_var(value) -> str: + """Environment names and values need to be string.""" + if isinstance(value, str): + return value + elif isinstance(value, bytes): + return value.decode() + return str(value) + + +def encode_environment(env): + if ENCODE_ENVIRONMENT: + env = {encode_for_env_var(k): encode_for_env_var(v) for k, v in env.items()} + return env + + +from collections.abc import Iterable + + +def isiterable(obj): + return not isinstance(obj, str) and isinstance(obj, Iterable) + + +# ############################# +# other +# ############################# + +from collections import OrderedDict as odict # noqa: F401 + + +def open_utf8( + file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True +): + if "b" in mode: + return builtins.open( + file, + str(mode), + buffering=buffering, + errors=errors, + newline=newline, + closefd=closefd, + ) + else: + return builtins.open( + file, + str(mode), + buffering=buffering, + encoding=encoding or "utf-8", + errors=errors, + newline=newline, + closefd=closefd, + ) + + +NoneType = type(None) +primitive_types = (str, int, float, complex, bool, NoneType) + + +def ensure_binary(value): + try: + return value.encode("utf-8") + except AttributeError: # pragma: no cover + # AttributeError: '<>' object has no attribute 'encode' + # In this case assume already binary type and do nothing + return value + + +def ensure_text_type(value) -> str: + try: + return value.decode("utf-8") + except AttributeError: # pragma: no cover + # AttributeError: '<>' object has no attribute 'decode' + # In this case assume already text_type and do nothing + return value + except UnicodeDecodeError: # pragma: no cover + from charset_normalizer import from_bytes + + return str(from_bytes(value).best()) + except UnicodeEncodeError: # pragma: no cover + # it's already str, so ignore? + # not sure, surfaced with tests/models/test_match_spec.py test_tarball_match_specs + # using py27 + return value + + +def ensure_utf8_encoding(value): + try: + return value.encode("utf-8") + except AttributeError: + return value + except UnicodeEncodeError: + return value diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/configuration.py b/miniconda3/lib/python3.13/site-packages/conda/common/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9c88d865eae3c49ce7ca93d71989dc822d297b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/configuration.py @@ -0,0 +1,1786 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +A generalized application configuration utility. + +Features include: + - lazy eval + - merges configuration files + - parameter type validation, with custom validation + - parameter aliases + +Easily extensible to other source formats, e.g. json and ini + +""" + +from __future__ import annotations + +import copy +import sys +from abc import ABCMeta, abstractmethod +from collections import defaultdict +from collections.abc import Mapping +from enum import Enum, EnumMeta +from functools import cache, wraps +from itertools import chain +from logging import getLogger +from os import environ +from os.path import expandvars +from pathlib import Path +from re import IGNORECASE, VERBOSE, compile +from string import Template +from typing import TYPE_CHECKING + +from boltons.setutils import IndexedSet +from frozendict import deepfreeze, frozendict +from frozendict import getFreezeConversionMap as _getFreezeConversionMap +from frozendict import register as _register +from ruamel.yaml.comments import CommentedMap, CommentedSeq +from ruamel.yaml.reader import ReaderError +from ruamel.yaml.scanner import ScannerError + +from .. import CondaError, CondaMultiError +from ..auxlib.collection import AttrDict, first, last +from ..auxlib.exceptions import ThisShouldNeverHappenError +from ..auxlib.type_coercion import TypeCoercionError, typify, typify_data_structure +from ..base.constants import CMD_LINE_SOURCE, ENV_VARS_SOURCE +from ..common.iterators import unique +from .compat import isiterable, primitive_types +from .constants import NULL +from .serialize import yaml + +if Enum not in _getFreezeConversionMap(): + # leave enums as is, deepfreeze will flatten it into a dict + # see https://github.com/Marco-Sulla/python-frozendict/issues/98 + _register(Enum, lambda x: x) + +del _getFreezeConversionMap +del _register + +if TYPE_CHECKING: + from collections.abc import Hashable, Iterable, Sequence + from re import Match + from typing import Any, Final + + from ..common.path import PathsType + +log = getLogger(__name__) + +EMPTY_MAP = frozendict() + + +def pretty_list(iterable, padding=" "): # TODO: move elsewhere in conda.common + if not isiterable(iterable): + iterable = [iterable] + try: + return "\n".join(f"{padding}- {item}" for item in iterable) + except TypeError: + return pretty_list([iterable], padding) + + +def pretty_map(dictionary, padding=" "): + return "\n".join(f"{padding}{key}: {value}" for key, value in dictionary.items()) + + +def expand_environment_variables(unexpanded): + if isinstance(unexpanded, (str, bytes)): + return expandvars(unexpanded) + else: + return unexpanded + + +class ConfigurationError(CondaError): + pass + + +class ConfigurationLoadError(ConfigurationError): + def __init__(self, path, message_addition="", **kwargs): + message = "Unable to load configuration file.\n path: %(path)s\n" + super().__init__(message + message_addition, path=path, **kwargs) + + +class ValidationError(ConfigurationError): + def __init__(self, parameter_name, parameter_value, source, msg=None, **kwargs): + self.parameter_name = parameter_name + self.parameter_value = parameter_value + self.source = source + super().__init__(msg, **kwargs) + + +class MultipleKeysError(ValidationError): + def __init__(self, source, keys, preferred_key): + self.source = source + self.keys = keys + msg = ( + f"Multiple aliased keys in file {source}:\n" + f"{pretty_list(keys)}\n" + f"Must declare only one. Prefer '{preferred_key}'" + ) + super().__init__(preferred_key, None, source, msg=msg) + + +class InvalidTypeError(ValidationError): + def __init__( + self, parameter_name, parameter_value, source, wrong_type, valid_types, msg=None + ): + self.wrong_type = wrong_type + self.valid_types = valid_types + if msg is None: + msg = ( + f"Parameter {parameter_name} = {parameter_value!r} declared in {source} has type {wrong_type}.\n" + f"Valid types:\n{pretty_list(valid_types)}" + ) + super().__init__(parameter_name, parameter_value, source, msg=msg) + + +class CustomValidationError(ValidationError): + def __init__(self, parameter_name, parameter_value, source, custom_message): + super().__init__( + parameter_name, + parameter_value, + source, + msg=( + f"Parameter {parameter_name} = {parameter_value!r} declared in " + f"{source} is invalid.\n{custom_message}" + ), + ) + + +class MultiValidationError(CondaMultiError, ConfigurationError): + def __init__(self, errors, *args, **kwargs): + super().__init__(errors, *args, **kwargs) + + +def raise_errors(errors): + if not errors: + return True + elif len(errors) == 1: + raise errors[0] + else: + raise MultiValidationError(errors) + + +class ParameterFlag(Enum): + final = "final" + top = "top" + bottom = "bottom" + + def __str__(self): + return f"{self.value}" + + @classmethod + def from_name(cls, name): + return cls[name] + + @classmethod + def from_value(cls, value): + return cls(value) + + @classmethod + def from_string(cls, string): + try: + string = string.strip("!#") + return cls.from_value(string) + except (ValueError, AttributeError): + return None + + +class RawParameter(metaclass=ABCMeta): + def __init__(self, source, key, raw_value): + self.source = source + self.key = key + try: + self._raw_value = raw_value.decode("utf-8") + except AttributeError: + # AttributeError: raw_value is not encoded + self._raw_value = raw_value + + def __repr__(self): + return str(vars(self)) + + @abstractmethod + def value(self, parameter_obj): + raise NotImplementedError() + + @abstractmethod + def keyflag(self): + raise NotImplementedError() + + @abstractmethod + def valueflags(self, parameter_obj): + raise NotImplementedError() + + @classmethod + def make_raw_parameters(cls, source, from_map): + if from_map: + return {key: cls(source, key, from_map[key]) for key in from_map} + return EMPTY_MAP + + +class EnvRawParameter(RawParameter): + source = ENV_VARS_SOURCE + + def value(self, parameter_obj): + # note: this assumes that EnvRawParameters will only have flat configuration of either + # primitive or sequential type + if hasattr(parameter_obj, "string_delimiter"): + if not isinstance(self._raw_value, str): + raise TypeError("Value is not a string.") + string_delimiter = getattr(parameter_obj, "string_delimiter") + # TODO: add stripping of !important, !top, and !bottom + return tuple( + EnvRawParameter(EnvRawParameter.source, self.key, v) + for v in (vv.strip() for vv in self._raw_value.split(string_delimiter)) + if v + ) + else: + return self.__important_split_value[0].strip() + + def keyflag(self): + return ParameterFlag.final if len(self.__important_split_value) >= 2 else None + + def valueflags(self, parameter_obj): + if hasattr(parameter_obj, "string_delimiter"): + string_delimiter = getattr(parameter_obj, "string_delimiter") + # TODO: add stripping of !important, !top, and !bottom + return tuple("" for _ in self._raw_value.split(string_delimiter)) + else: + return self.__important_split_value[0].strip() + + @property + def __important_split_value(self): + return self._raw_value.split("!important") + + @classmethod + def make_raw_parameters(cls, appname): + keystart = f"{appname.upper()}_" + raw_env = { + k.replace(keystart, "", 1).lower(): v + for k, v in environ.items() + if k.startswith(keystart) + } + return super().make_raw_parameters(EnvRawParameter.source, raw_env) + + +class ArgParseRawParameter(RawParameter): + source = CMD_LINE_SOURCE + + def value(self, parameter_obj): + # note: this assumes ArgParseRawParameter will only have flat configuration of either + # primitive or sequential type + if isiterable(self._raw_value): + children_values = [] + for i in range(len(self._raw_value)): + children_values.append( + ArgParseRawParameter(self.source, self.key, self._raw_value[i]) + ) + return tuple(children_values) + else: + return deepfreeze(self._raw_value) + + def keyflag(self): + return None + + def valueflags(self, parameter_obj): + return None if isinstance(parameter_obj, PrimitiveLoadedParameter) else () + + @classmethod + def make_raw_parameters(cls, args_from_argparse): + return super().make_raw_parameters( + ArgParseRawParameter.source, args_from_argparse + ) + + +class YamlRawParameter(RawParameter): + # this class should encapsulate all direct use of ruamel.yaml in this module + + def __init__(self, source, key, raw_value, key_comment): + self._key_comment = key_comment + super().__init__(source, key, raw_value) + + if isinstance(self._raw_value, CommentedSeq): + value_comments = self._get_yaml_list_comments(self._raw_value) + self._value_flags = tuple( + ParameterFlag.from_string(s) for s in value_comments + ) + children_values = [] + for i in range(len(self._raw_value)): + children_values.append( + YamlRawParameter( + self.source, self.key, self._raw_value[i], value_comments[i] + ) + ) + self._value = tuple(children_values) + elif isinstance(self._raw_value, CommentedMap): + value_comments = self._get_yaml_map_comments(self._raw_value) + self._value_flags = { + k: ParameterFlag.from_string(v) + for k, v in value_comments.items() + if v is not None + } + children_values = {} + for k, v in self._raw_value.items(): + children_values[k] = YamlRawParameter( + self.source, self.key, v, value_comments[k] + ) + self._value = frozendict(children_values) + elif isinstance(self._raw_value, primitive_types): + self._value_flags = None + self._value = self._raw_value + else: + print(type(self._raw_value), self._raw_value, file=sys.stderr) + raise ThisShouldNeverHappenError() # pragma: no cover + + def value(self, parameter_obj): + return self._value + + def keyflag(self): + return ParameterFlag.from_string(self._key_comment) + + def valueflags(self, parameter_obj): + return self._value_flags + + @staticmethod + def _get_yaml_key_comment(commented_dict, key): + try: + return commented_dict.ca.items[key][2].value.strip() + except (AttributeError, KeyError): + return None + + @classmethod + def _get_yaml_list_comments(cls, value): + # value is a ruamel.yaml CommentedSeq, len(value) is the number of lines in the sequence, + # value.ca is the comment object for the sequence and the comments themselves are stored as + # a sparse dict + list_comments = [] + for i in range(len(value)): + try: + list_comments.append(cls._get_yaml_list_comment_item(value.ca.items[i])) + except (AttributeError, IndexError, KeyError, TypeError): + list_comments.append(None) + return tuple(list_comments) + + @staticmethod + def _get_yaml_list_comment_item(item): + # take the pre_item comment if available + # if not, take the first post_item comment if available + if item[0]: + return item[0].value.strip() or None + else: + return item[1][0].value.strip() or None + + @staticmethod + def _get_yaml_map_comments(value): + map_comments = {} + for key in value: + try: + map_comments[key] = value.ca.items[key][2].value.strip() or None + except (AttributeError, KeyError): + map_comments[key] = None + return map_comments + + @classmethod + def make_raw_parameters(cls, source, from_map): + if from_map: + return { + key: cls( + source, key, from_map[key], cls._get_yaml_key_comment(from_map, key) + ) + for key in from_map + } + return EMPTY_MAP + + @classmethod + @cache + def make_raw_parameters_from_file(cls, filepath): + """ + Read the provided file path and convert the contents into configuration parameters. + + This function will cache the result for each filepath. In order to re-read the same + file path with updated content, be sure to clear this cache. + + For example:: + + YamlRawParameter.cache_clear() + """ + with open(filepath) as fh: + try: + yaml_obj = yaml.loads(fh) + except ScannerError as err: + mark = err.problem_mark + raise ConfigurationLoadError( + filepath, + " reason: invalid yaml at line %(line)s, column %(column)s", + line=mark.line, + column=mark.column, + ) + except ReaderError as err: + raise ConfigurationLoadError( + filepath, + " reason: invalid yaml at position %(position)s", + position=err.position, + ) + return cls.make_raw_parameters(filepath, yaml_obj) or EMPTY_MAP + + @classmethod + def cache_clear(cls) -> None: + cls.make_raw_parameters_from_file.cache_clear() + + +class DefaultValueRawParameter(RawParameter): + """Wraps a default value as a RawParameter, for usage in ParameterLoader.""" + + def __init__(self, source, key, raw_value): + super().__init__(source, key, raw_value) + + if isinstance(self._raw_value, Mapping): + children_values = {} + for k, v in self._raw_value.items(): + children_values[k] = DefaultValueRawParameter(self.source, self.key, v) + self._value = frozendict(children_values) + elif isiterable(self._raw_value): + children_values = [] + for i in range(len(self._raw_value)): + children_values.append( + DefaultValueRawParameter(self.source, self.key, self._raw_value[i]) + ) + self._value = tuple(children_values) + elif isinstance(self._raw_value, ConfigurationObject): + self._value = self._raw_value + for attr_name, attr_value in vars(self._raw_value).items(): + self._value.__setattr__( + attr_name, + DefaultValueRawParameter(self.source, self.key, attr_value), + ) + elif isinstance(self._raw_value, Enum): + self._value = self._raw_value + elif isinstance(self._raw_value, primitive_types): + self._value = self._raw_value + else: + raise ThisShouldNeverHappenError() # pragma: no cover + + def value(self, parameter_obj): + return self._value + + def keyflag(self): + return None + + def valueflags(self, parameter_obj): + if isinstance(self._raw_value, Mapping): + return frozendict() + elif isiterable(self._raw_value): + return () + elif isinstance(self._raw_value, ConfigurationObject): + return None + elif isinstance(self._raw_value, Enum): + return None + elif isinstance(self._raw_value, primitive_types): + return None + else: + raise ThisShouldNeverHappenError() # pragma: no cover + + +class LoadedParameter(metaclass=ABCMeta): + # (type) describes the type of parameter + _type = None + # (Parameter or type) if the LoadedParameter holds a collection, describes the element held in + # the collection. if not, describes the primitive type held by the LoadedParameter. + _element_type = None + + def __init__(self, name, value, key_flag, value_flags, validation=None): + """ + Represents a Parameter that has been loaded with configuration value. + + Args: + name (str): name of the loaded parameter + value (LoadedParameter or primitive): the value of the loaded parameter + key_flag (ParameterFlag or None): priority flag for the parameter itself + value_flags (Any or None): priority flags for the parameter values + validation (callable): Given a parameter value as input, return a boolean indicating + validity, or alternately return a string describing an invalid value. + """ + self._name = name + self.value = value + self.key_flag = key_flag + self.value_flags = value_flags + self._validation = validation + + def __eq__(self, other): + if type(other) is type(self): + return self.value == other.value + return False + + def __hash__(self): + return hash(self.value) + + def collect_errors(self, instance, typed_value, source="<>"): + """ + Validate a LoadedParameter typed value. + + Args: + instance (Configuration): the instance object used to create the LoadedParameter. + typed_value (Any): typed value to validate. + source (str): string description for the source of the typed_value. + """ + errors = [] + if not isinstance(typed_value, self._type): + errors.append( + InvalidTypeError( + self._name, typed_value, source, type(self.value), self._type + ) + ) + elif self._validation is not None: + result = self._validation(typed_value) + if result is False: + errors.append(ValidationError(self._name, typed_value, source)) + elif isinstance(result, str): + errors.append( + CustomValidationError(self._name, typed_value, source, result) + ) + return errors + + def expand(self): + """ + Recursively expands any environment values in the Loaded Parameter. + + Returns LoadedParameter + """ + # This is similar to conda.auxlib.type_coercion.typify_data_structure + # It could be DRY-er but that would break SRP. + if isinstance(self.value, Mapping): + new_value = type(self.value)((k, v.expand()) for k, v in self.value.items()) + elif isiterable(self.value): + new_value = type(self.value)(v.expand() for v in self.value) + elif isinstance(self.value, ConfigurationObject): + for attr_name, attr_value in vars(self.value).items(): + if isinstance(attr_value, LoadedParameter): + self.value.__setattr__(attr_name, attr_value.expand()) + return self.value + else: + new_value = expand_environment_variables(self.value) + self.value = new_value + return self + + @abstractmethod + def merge(self, matches): + """ + Recursively merges matches into one LoadedParameter. + + Args: + matches (List): list of matches of this parameter. + + Returns: LoadedParameter + """ + raise NotImplementedError() + + def typify(self, source): + """ + Recursively types a LoadedParameter. + + Args: + source (str): string describing the source of the LoadedParameter. + + Returns: a primitive, sequence, or map representing the typed value. + """ + element_type = self._element_type + try: + return LoadedParameter._typify_data_structure( + self.value, source, element_type + ) + except TypeCoercionError as e: + msg = str(e) + if issubclass(element_type, Enum): + choices = ", ".join( + map("'{}'".format, element_type.__members__.values()) + ) + msg += f"\nValid choices for {self._name}: {choices}" + raise CustomValidationError(self._name, e.value, source, msg) + + @staticmethod + def _typify_data_structure(value, source, type_hint=None): + if isinstance(value, Mapping): + return type(value)((k, v.typify(source)) for k, v in value.items()) + elif isiterable(value): + return type(value)(v.typify(source) for v in value) + elif isinstance(value, ConfigurationObject): + for attr_name, attr_value in vars(value).items(): + if isinstance(attr_value, LoadedParameter): + value.__setattr__(attr_name, attr_value.typify(source)) + return value + elif ( + isinstance(value, str) + and isinstance(type_hint, type) + and issubclass(type_hint, str) + ): + # This block is necessary because if we fall through to typify(), we end up calling + # .strip() on the str, when sometimes we want to preserve preceding and trailing + # whitespace. + return type_hint(value) + else: + return typify(value, type_hint) + + @staticmethod + def _match_key_is_important(loaded_parameter): + return loaded_parameter.key_flag is ParameterFlag.final + + @staticmethod + def _first_important_matches(matches): + idx = first( + enumerate(matches), + lambda x: LoadedParameter._match_key_is_important(x[1]), + apply=lambda x: x[0], + ) + return matches if idx is None else matches[: idx + 1] + + +class PrimitiveLoadedParameter(LoadedParameter): + """ + LoadedParameter type that holds a single python primitive value. + + The python primitive types are str, int, float, complex, bool, and NoneType. In addition, + python 2 has long and unicode types. + """ + + def __init__( + self, name, element_type, value, key_flag, value_flags, validation=None + ): + """ + Args: + element_type (type or tuple[type]): Type-validation of parameter's value. + value (primitive value): primitive python value. + """ + self._type = element_type + self._element_type = element_type + super().__init__(name, value, key_flag, value_flags, validation) + + def __eq__(self, other): + if type(other) is type(self): + return self.value == other.value + return False + + def __hash__(self): + return hash(self.value) + + def merge(self, matches): + important_match = first( + matches, LoadedParameter._match_key_is_important, default=None + ) + if important_match is not None: + return important_match + + last_match = last(matches, lambda x: x is not None, default=None) + if last_match is not None: + return last_match + raise ThisShouldNeverHappenError() # pragma: no cover + + +class MapLoadedParameter(LoadedParameter): + """LoadedParameter type that holds a map (i.e. dict) of LoadedParameters.""" + + _type = frozendict + + def __init__( + self, name, value, element_type, key_flag, value_flags, validation=None + ): + """ + Args: + value (Mapping): Map of string keys to LoadedParameter values. + element_type (Parameter): The Parameter type that is held in value. + value_flags (Mapping): Map of priority value flags. + """ + self._element_type = element_type + super().__init__(name, value, key_flag, value_flags, validation) + + def collect_errors(self, instance, typed_value, source="<>"): + errors = super().collect_errors(instance, typed_value, self.value) + + # recursively validate the values in the map + if isinstance(self.value, Mapping): + for key, value in self.value.items(): + errors.extend(value.collect_errors(instance, typed_value[key], source)) + return errors + + def merge(self, parameters: Sequence[MapLoadedParameter]) -> MapLoadedParameter: + # get all values up to and including first important_match + # but if no important_match, then all matches are important_matches + parameters = LoadedParameter._first_important_matches(parameters) + + # ensure all parameter values are Mappings + for parameter in parameters: + if not isinstance(parameter.value, Mapping): + raise InvalidTypeError( + self.name, + parameter.value, + parameter.source, + parameter.value.__class__.__name__, + self._type.__name__, + ) + + # map keys with final values, + # first key has higher precedence than later ones + final_map = { + key: value + for parameter in reversed(parameters) + for key, value in parameter.value.items() + if parameter.value_flags.get(key) == ParameterFlag.final + } + + # map each value by recursively calling merge on any entries with the same key, + # last key has higher precedence than earlier ones + grouped_map = {} + for parameter in parameters: + for key, value in parameter.value.items(): + grouped_map.setdefault(key, []).append(value) + merged_map = { + key: values[0].merge(values) for key, values in grouped_map.items() + } + + # update merged_map with final_map values + merged_value = frozendict({**merged_map, **final_map}) + + # create new parameter for the merged values + return MapLoadedParameter( + self._name, + merged_value, + self._element_type, + self.key_flag, + self.value_flags, + validation=self._validation, + ) + + +class SequenceLoadedParameter(LoadedParameter): + """LoadedParameter type that holds a sequence (i.e. list) of LoadedParameters.""" + + _type = tuple + + def __init__( + self, name, value, element_type, key_flag, value_flags, validation=None + ): + """ + Args: + value (Sequence): Sequence of LoadedParameter values. + element_type (Parameter): The Parameter type that is held in the sequence. + value_flags (Sequence): Sequence of priority value_flags. + """ + self._element_type = element_type + super().__init__(name, value, key_flag, value_flags, validation) + + def collect_errors(self, instance, typed_value, source="<>"): + errors = super().collect_errors(instance, typed_value, self.value) + # recursively collect errors on the elements in the sequence + for idx, element in enumerate(self.value): + errors.extend(element.collect_errors(instance, typed_value[idx], source)) + return errors + + def merge(self, matches): + # get matches up to and including first important_match + # but if no important_match, then all matches are important_matches + relevant_matches_and_values = tuple( + (match, match.value) + for match in LoadedParameter._first_important_matches(matches) + ) + for match, value in relevant_matches_and_values: + if not isinstance(value, tuple): + raise InvalidTypeError( + self.name, + value, + match.source, + value.__class__.__name__, + self._type.__name__, + ) + + # get individual lines from important_matches that were marked important + # these will be prepended to the final result + def get_marked_lines(match, marker): + return ( + tuple( + line + for line, flag in zip(match.value, match.value_flags) + if flag is marker + ) + if match + else () + ) + + top_lines = chain.from_iterable( + get_marked_lines(m, ParameterFlag.top) + for m, _ in relevant_matches_and_values + ) + + # also get lines that were marked as bottom, but reverse the match order so that lines + # coming earlier will ultimately be last + bottom_lines = tuple( + chain.from_iterable( + get_marked_lines(match, ParameterFlag.bottom) + for match, _ in reversed(relevant_matches_and_values) + ) + ) + + # now, concat all lines, while reversing the matches + # reverse because elements closer to the end of search path take precedence + all_lines = chain.from_iterable( + v for _, v in reversed(relevant_matches_and_values) + ) + + # stack top_lines + all_lines, then de-dupe + top_deduped = tuple(unique((*top_lines, *all_lines))) + + # take the top-deduped lines, reverse them, and concat with reversed bottom_lines + # this gives us the reverse of the order we want, but almost there + # NOTE: for a line value marked both top and bottom, the bottom marker will win out + # for the top marker to win out, we'd need one additional de-dupe step + bottom_deduped = tuple( + unique((*reversed(bottom_lines), *reversed(top_deduped))) + ) + # just reverse, and we're good to go + merged_values = tuple(reversed(bottom_deduped)) + + return SequenceLoadedParameter( + self._name, + merged_values, + self._element_type, + self.key_flag, + self.value_flags, + validation=self._validation, + ) + + +class ObjectLoadedParameter(LoadedParameter): + """LoadedParameter type that holds a mapping (i.e. object) of LoadedParameters.""" + + _type = object + + def __init__( + self, name, value, element_type, key_flag, value_flags, validation=None + ): + """ + Args: + value (Sequence): Object with LoadedParameter fields. + element_type (object): The Parameter type that is held in the sequence. + value_flags (Sequence): Sequence of priority value_flags. + """ + self._element_type = element_type + super().__init__(name, value, key_flag, value_flags, validation) + + def collect_errors(self, instance, typed_value, source="<>"): + errors = super().collect_errors(instance, typed_value, self.value) + + # recursively validate the values in the object fields + if isinstance(self.value, ConfigurationObject): + for key, value in vars(self.value).items(): + if isinstance(value, LoadedParameter): + errors.extend( + value.collect_errors(instance, typed_value[key], source) + ) + return errors + + def merge( + self, parameters: Sequence[ObjectLoadedParameter] + ) -> ObjectLoadedParameter: + # get all parameters up to and including first important_match + # but if no important_match, then all parameters are important_matches + parameters = LoadedParameter._first_important_matches(parameters) + + # map keys with final values, + # first key has higher precedence than later ones + final_map = { + key: value + for parameter in reversed(parameters) + for key, value in vars(parameter.value).items() + if ( + isinstance(value, LoadedParameter) + and parameter.value_flags.get(key) == ParameterFlag.final + ) + } + + # map each value by recursively calling merge on any entries with the same key, + # last key has higher precedence than earlier ones + grouped_map = {} + for parameter in parameters: + for key, value in vars(parameter.value).items(): + grouped_map.setdefault(key, []).append(value) + merged_map = { + key: values[0].merge(values) for key, values in grouped_map.items() + } + + # update merged_map with final_map values + merged_value = copy.deepcopy(self._element_type) + for key, value in {**merged_map, **final_map}.items(): + merged_value.__setattr__(key, value) + + # create new parameter for the merged values + return ObjectLoadedParameter( + self._name, + merged_value, + self._element_type, + self.key_flag, + self.value_flags, + validation=self._validation, + ) + + +class ConfigurationObject: + """Dummy class to mark whether a Python object has config parameters within.""" + + def to_json(self): + """ + Return a serializable object with defaults filled in + """ + serializable = {} + + for attr, value in vars(self).items(): + serializable[attr] = value + + return serializable + + +class Parameter(metaclass=ABCMeta): + # (type) describes the type of parameter + _type = None + # (Parameter or type) if the Parameter is holds a collection, describes the element held in + # the collection. if not, describes the primitive type held by the Parameter. + _element_type = None + + def __init__(self, default, validation=None): + """ + The Parameter class represents an unloaded configuration parameter, holding type, default + and validation information until the parameter is loaded with a configuration. + + Args: + default (Any): the typed, python representation default value given if the Parameter + is not found in a Configuration. + validation (callable): Given a parameter value as input, return a boolean indicating + validity, or alternately return a string describing an invalid value. + """ + self._default = default + self._validation = validation + + @property + def default(self): + """Returns a DefaultValueRawParameter that wraps the actual default value.""" + wrapped_default = DefaultValueRawParameter("default", "default", self._default) + return self.load("default", wrapped_default) + + def get_all_matches(self, name, names, instance): + """ + Finds all matches of a Parameter in a Configuration instance + + Args: + name (str): canonical name of the parameter to search for + names (tuple(str)): alternative aliases of the parameter + instance (Configuration): instance of the configuration to search within + + Returns (List(RawParameter)): matches of the parameter found in the configuration. + """ + matches = [] + multikey_exceptions = [] + for filepath, raw_parameters in instance.raw_data.items(): + match, error = ParameterLoader.raw_parameters_from_single_source( + name, names, raw_parameters + ) + if match is not None: + matches.append(match) + if error: + multikey_exceptions.append(error) + return matches, multikey_exceptions + + @abstractmethod + def load(self, name, match): + """ + Loads a Parameter with the value in a RawParameter. + + Args: + name (str): name of the parameter to pass through + match (RawParameter): the value of the RawParameter match + + Returns a LoadedParameter + """ + raise NotImplementedError() + + def typify(self, name, source, value): + element_type = self._element_type + try: + return typify_data_structure(value, element_type) + except TypeCoercionError as e: + msg = str(e) + if issubclass(element_type, Enum): + choices = ", ".join( + map("'{}'".format, element_type.__members__.values()) + ) + msg += f"\nValid choices for {name}: {choices}" + raise CustomValidationError(name, e.value, source, msg) + + +class PrimitiveParameter(Parameter): + """ + Parameter type for a Configuration class that holds a single python primitive value. + + The python primitive types are str, int, float, complex, bool, and NoneType. In addition, + python 2 has long and unicode types. + """ + + def __init__(self, default, element_type=None, validation=None): + """ + Args: + default (primitive value): default value if the Parameter is not found. + element_type (type or tuple[type]): Type-validation of parameter's value. If None, + type(default) is used. + """ + self._type = type(default) if element_type is None else element_type + self._element_type = self._type + super().__init__(default, validation) + + def load(self, name, match): + return PrimitiveLoadedParameter( + name, + self._type, + match.value(self._element_type), + match.keyflag(), + match.valueflags(self._element_type), + validation=self._validation, + ) + + +class MapParameter(Parameter): + """Parameter type for a Configuration class that holds a map (i.e. dict) of Parameters.""" + + _type = frozendict + + def __init__(self, element_type, default=frozendict(), validation=None): + """ + Args: + element_type (Parameter): The Parameter type held in the MapParameter. + default (Mapping): The parameter's default value. If None, will be an empty dict. + """ + self._element_type = element_type + default = default and frozendict(default) or frozendict() + super().__init__(default, validation=validation) + + def get_all_matches(self, name, names, instance): + # it also config settings like `proxy_servers: ~` + matches, exceptions = super().get_all_matches(name, names, instance) + matches = tuple(m for m in matches if m._raw_value is not None) + return matches, exceptions + + def load(self, name, match): + value = match.value(self._element_type) + if value is None: + return MapLoadedParameter( + name, + frozendict(), + self._element_type, + match.keyflag(), + frozendict(), + validation=self._validation, + ) + + if not isinstance(value, Mapping): + raise InvalidTypeError( + name, value, match.source, value.__class__.__name__, self._type.__name__ + ) + + loaded_map = {} + for key, child_value in match.value(self._element_type).items(): + loaded_child_value = self._element_type.load(name, child_value) + loaded_map[key] = loaded_child_value + + return MapLoadedParameter( + name, + frozendict(loaded_map), + self._element_type, + match.keyflag(), + match.valueflags(self._element_type), + validation=self._validation, + ) + + +class SequenceParameter(Parameter): + """Parameter type for a Configuration class that holds a sequence (i.e. list) of Parameters.""" + + _type = tuple + + def __init__(self, element_type, default=(), validation=None, string_delimiter=","): + """ + Args: + element_type (Parameter): The Parameter type that is held in the sequence. + default (Sequence): default value, empty tuple if not given. + string_delimiter (str): separation string used to parse string into sequence. + """ + self._element_type = element_type + self.string_delimiter = string_delimiter + super().__init__(default, validation) + + def get_all_matches(self, name, names, instance): + # this is necessary to handle argparse `action="append"`, which can't be set to a + # default value of NULL + # it also config settings like `channels: ~` + matches, exceptions = super().get_all_matches(name, names, instance) + matches = tuple(m for m in matches if m._raw_value is not None) + return matches, exceptions + + def load(self, name, match): + value = match.value(self) + if value is None: + return SequenceLoadedParameter( + name, + (), + self._element_type, + match.keyflag(), + (), + validation=self._validation, + ) + + if not isiterable(value): + raise InvalidTypeError( + name, value, match.source, value.__class__.__name__, self._type.__name__ + ) + + loaded_sequence = [] + for child_value in value: + loaded_child_value = self._element_type.load(name, child_value) + loaded_sequence.append(loaded_child_value) + + return SequenceLoadedParameter( + name, + tuple(loaded_sequence), + self._element_type, + match.keyflag(), + match.valueflags(self._element_type), + validation=self._validation, + ) + + +class ObjectParameter(Parameter): + """Parameter type for a Configuration class that holds an object with Parameter fields.""" + + _type = object + + def __init__(self, element_type, default=ConfigurationObject(), validation=None): + """ + Args: + element_type (object): The object type with parameter fields held in ObjectParameter. + default (Sequence): default value, empty tuple if not given. + """ + self._element_type = element_type + super().__init__(default, validation) + + def get_all_matches(self, name, names, instance): + # it also config settings like `proxy_servers: ~` + matches, exceptions = super().get_all_matches(name, names, instance) + matches = tuple(m for m in matches if m._raw_value is not None) + return matches, exceptions + + def load(self, name, match): + value = match.value(self._element_type) + if value is None: + return ObjectLoadedParameter( + name, + None, + self._element_type, + match.keyflag(), + None, + validation=self._validation, + ) + + if not isinstance(value, (Mapping, ConfigurationObject)): + raise InvalidTypeError( + name, value, match.source, value.__class__.__name__, self._type.__name__ + ) + + # for a default object, extract out the instance variables + if isinstance(value, ConfigurationObject): + value = vars(value) + + object_parameter_attrs = { + attr_name: parameter_type + for attr_name, parameter_type in vars(self._element_type).items() + if isinstance(parameter_type, Parameter) + } + + # recursively load object fields + loaded_attrs = {} + for attr_name, parameter_type in object_parameter_attrs.items(): + if raw_child_value := value.get(attr_name): + loaded_child_value = parameter_type.load(name, raw_child_value) + else: + loaded_child_value = parameter_type.default + loaded_attrs[attr_name] = loaded_child_value + + # copy object and replace Parameter with LoadedParameter fields + object_copy = copy.deepcopy(self._element_type) + for attr_name, loaded_child_parameter in loaded_attrs.items(): + object_copy.__setattr__(attr_name, loaded_child_parameter) + + return ObjectLoadedParameter( + name, + object_copy, + self._element_type, + match.keyflag(), + match.valueflags(self._element_type), + validation=self._validation, + ) + + +class ParameterLoader: + """ + ParameterLoader class contains the top level logic needed to load a parameter from start to + finish. + """ + + def __init__(self, parameter_type, aliases=(), expandvars=False): + """ + Args: + parameter_type (Parameter): the type of Parameter that is stored in the loader. + aliases (tuple(str)): alternative aliases for the Parameter + expandvars (bool): whether or not to recursively expand environmental variables. + """ + self._name = None + self._names = None + self.type = parameter_type + self.aliases = aliases + self._expandvars = expandvars + + def _set_name(self, name): + # this is an explicit method, and not a descriptor/setter + # it's meant to be called by the Configuration metaclass + self._name = name + _names = frozenset(x for x in chain(self.aliases, (name,))) + self._names = _names + return name + + @property + def name(self): + if self._name is None: + # The Configuration metaclass should call the `_set_name` method. + raise ThisShouldNeverHappenError() # pragma: no cover + return self._name + + @property + def names(self): + if self._names is None: + # The Configuration metaclass should call the `_set_name` method. + raise ThisShouldNeverHappenError() # pragma: no cover + return self._names + + def __get__(self, instance, instance_type): + # strategy is "extract and merge," which is actually just map and reduce + # extract matches from each source in SEARCH_PATH + # then merge matches together + if self.name in instance._cache_: + return instance._cache_[self.name] + + # step 1/2: load config and find top level matches + raw_matches, errors = self.type.get_all_matches(self.name, self.names, instance) + + # step 3: parse RawParameters into LoadedParameters + matches = [self.type.load(self.name, match) for match in raw_matches] + + # step 4: merge matches + merged = matches[0].merge(matches) if matches else self.type.default + + # step 5: typify + # We need to expand any environment variables before type casting. + # Otherwise e.g. `my_bool_var: $BOOL` with BOOL=True would raise a TypeCoercionError. + expanded = merged.expand() if self._expandvars else merged + try: + result = expanded.typify("<>") + except CustomValidationError as e: + errors.append(e) + else: + errors.extend(expanded.collect_errors(instance, result, "<>")) + raise_errors(errors) + instance._cache_[self.name] = result + return result + + def _raw_parameters_from_single_source(self, raw_parameters): + return ParameterLoader.raw_parameters_from_single_source( + self.name, self.names, raw_parameters + ) + + @staticmethod + def raw_parameters_from_single_source(name, names, raw_parameters): + # while supporting parameter name aliases, we enforce that only one definition is given + # per data source + keys = names & frozenset(raw_parameters.keys()) + matches = {key: raw_parameters[key] for key in keys} + numkeys = len(keys) + if numkeys == 0: + return None, None + elif numkeys == 1: + return next(iter(matches.values())), None + elif name in keys: + return matches[name], MultipleKeysError( + raw_parameters[next(iter(keys))].source, keys, name + ) + else: + return None, MultipleKeysError( + raw_parameters[next(iter(keys))].source, keys, name + ) + + +class ConfigurationType(type): + """metaclass for Configuration""" + + def __init__(cls, name, bases, attr): + super().__init__(name, bases, attr) + + # call _set_name for each parameter found during class creation + cls.parameter_names = tuple( + p._set_name(name) + for name, p in cls.__dict__.items() + if isinstance(p, ParameterLoader) + ) + + # Build parameter_names_and_aliases by extracting parameter loaders directly + cls._set_parameter_names_and_aliases() + + @property + def _parameter_loaders(cls) -> dict[str, ParameterLoader]: + return { + name: param + for name, param in cls.__dict__.items() + if isinstance(param, ParameterLoader) + } + + def __call__(cls, *args, **kwargs): + self = super().__call__(*args, **kwargs) + self._parameter_loaders = cls._parameter_loaders + return self + + +DEFAULT_CONDARC_FILENAME: Final = ".condarc" +ALTERNATIVE_CONDARC_FILENAME: Final = "condarc" +CONDARC_FILENAMES = (DEFAULT_CONDARC_FILENAME, ALTERNATIVE_CONDARC_FILENAME) +YAML_EXTENSIONS = (".yml", ".yaml") +_RE_CUSTOM_EXPANDVARS = compile( + rf""" + # delimiter and a Python identifier + \$(?P{Template.idpattern}) | + + # delimiter and a braced identifier + \${{(?P{Template.idpattern})}} | + + # delimiter padded identifier + %(?P{Template.idpattern})% + """, + flags=IGNORECASE | VERBOSE, +) + + +def custom_expandvars( + template: str, mapping: Mapping[str, Any] = {}, /, **kwargs +) -> str: + """Expand variables in a string. + + Inspired by `string.Template` and modified to mirror `os.path.expandvars` functionality + allowing custom variables without mutating `os.environ`. + + Expands POSIX and Windows CMD environment variables as follows: + + - $VARIABLE → value of VARIABLE + - ${VARIABLE} → value of VARIABLE + - %VARIABLE% → value of VARIABLE + + Invalid substitutions are left as-is: + + - $MISSING → $MISSING + - ${MISSING} → ${MISSING} + - %MISSING% → %MISSING% + - $$ → $$ + - %% → %% + - $ → $ + - % → % + """ + mapping = {**mapping, **kwargs} + + def convert(match: Match): + return str( + mapping.get( + match.group("named") or match.group("braced") or match.group("padded"), + match.group(), # fallback to the original string + ) + ) + + return _RE_CUSTOM_EXPANDVARS.sub(convert, template) + + +class Configuration(metaclass=ConfigurationType): + def __init__(self, search_path=(), app_name=None, argparse_args=None, **kwargs): + # Currently, __init__ does a **full** disk reload of all files. + # A future improvement would be to cache files that are already loaded. + self.raw_data = {} + self._cache_ = {} + self._reset_callbacks = IndexedSet() + self._validation_errors = defaultdict(list) + + self._set_search_path(search_path, **kwargs) + self._set_env_vars(app_name) + self._set_argparse_args(argparse_args) + + @classmethod + def _set_parameter_names_and_aliases(cls): + """Build parameter_names_and_aliases from the class's parameter loaders.""" + cls.parameter_names_and_aliases = tuple( + alias_name + for p in cls._parameter_loaders.values() + for alias_name in (p._names or ()) + ) + + @staticmethod + def _expand_search_path( + search_path: PathsType, + **kwargs, + ) -> Iterable[Path]: + for search in search_path: + # use custom_expandvars instead of os.path.expandvars so additional variables can be + # passed in without mutating os.environ + if isinstance(search, Path): + path = search + else: + template = custom_expandvars(str(search), environ, **kwargs) + path = Path(template).expanduser() + + if path.is_file() and ( + path.name in CONDARC_FILENAMES or path.suffix in YAML_EXTENSIONS + ): + yield path + elif path.is_dir(): + yield from ( + subpath + for subpath in sorted(path.iterdir()) + if subpath.is_file() and subpath.suffix in YAML_EXTENSIONS + ) + + @classmethod + def _load_search_path( + cls, + search_path: Iterable[Path], + ) -> Iterable[tuple[Path, dict]]: + for path in search_path: + try: + yield path, YamlRawParameter.make_raw_parameters_from_file(path) + except ConfigurationLoadError as err: + log.warning( + "Ignoring configuration file (%s) due to error:\n%s", + path, + err, + ) + + def _set_search_path(self, search_path: PathsType, **kwargs): + self._search_path = IndexedSet(self._expand_search_path(search_path, **kwargs)) + + self._set_raw_data(dict(self._load_search_path(self._search_path))) + + self._reset_cache() + return self + + def _set_env_vars(self, app_name=None): + self._app_name = app_name + + # remove existing source so "insert" order is correct + source = EnvRawParameter.source + if source in self.raw_data: + del self.raw_data[source] + + if app_name: + self.raw_data[source] = EnvRawParameter.make_raw_parameters(app_name) + + self._reset_cache() + return self + + def _set_argparse_args(self, argparse_args): + # the argparse_args we store internally in this class as self._argparse_args + # will be a mapping type, not a non-`dict` object like argparse_args is natively + if hasattr(argparse_args, "__dict__"): + # the argparse_args from argparse will be an object with a __dict__ attribute + # and not a mapping type like this method will turn it into + items = vars(argparse_args).items() + elif not argparse_args: + # argparse_args can be initialized as `None` + items = () + else: + # we're calling this method with argparse_args that are a mapping type, likely + # already having been processed by this method before + items = argparse_args.items() + + self._argparse_args = argparse_args = AttrDict( + {k: v for k, v in items if v is not NULL} + ) + + # remove existing source so "insert" order is correct + source = ArgParseRawParameter.source + if source in self.raw_data: + del self.raw_data[source] + + self.raw_data[source] = ArgParseRawParameter.make_raw_parameters(argparse_args) + + self._reset_cache() + return self + + def _set_raw_data(self, raw_data: Mapping[Hashable, dict]): + self.raw_data.update(raw_data) + self._reset_cache() + return self + + def name_for_alias(self, alias: str, ignore_private: bool = True) -> str | None: + """ + Find the canonical parameter name for a given alias. + + This method searches through all configuration parameters to find the canonical + parameter name that corresponds to the given alias. It's useful for resolving + parameter aliases to their primary names in configuration contexts. + + Args: + alias (str): The parameter alias to look up. + ignore_private (bool, optional): If True (default), exclude private parameters + (those starting with underscore) from the search. If False, include all + parameters regardless of privacy. + + Returns: + str | None: The canonical parameter name if the alias is found, otherwise None. + + Example: + >>> config = Configuration() + >>> config.name_for_alias("channel_priority") + 'channel_priority' + >>> config.name_for_alias("unknown_alias") + None + """ + return next( + ( + p._name + for p in self._parameter_loaders.values() + if alias in p.aliases + and (not ignore_private or not p._name.startswith("_")) + ), + None, + ) + + def _get_parameter_loader(self, parameter_name): + """Get parameter loader with fallback for missing parameters.""" + loaders = self._parameter_loaders + if parameter_name in loaders: + return loaders[parameter_name] + + # Try with underscore prefix for private parameters + private_name = "_" + parameter_name + if private_name in loaders: + return loaders[private_name] + + # Last resort: search through __dict__ for any ParameterLoader + for name, param in self.__class__.__dict__.items(): + if isinstance(param, ParameterLoader) and param._name == parameter_name: + return param + if isinstance(param, ParameterLoader) and parameter_name in getattr( + param, "_names", () + ): + return param + + return None + + def _reset_cache(self): + self._cache_ = {} + for callback in self._reset_callbacks: + callback() + return self + + def register_reset_callaback(self, callback): + self._reset_callbacks.add(callback) + + def check_source(self, source): + # this method ends up duplicating much of the logic of Parameter.__get__ + # I haven't yet found a way to make it more DRY though + typed_values = {} + validation_errors = [] + raw_parameters = self.raw_data[source] + for key in self.parameter_names: + parameter = self._get_parameter_loader(key) + if parameter is None: + continue # Skip parameters that can't be found + + match, multikey_error = parameter._raw_parameters_from_single_source( + raw_parameters + ) + if multikey_error: + validation_errors.append(multikey_error) + + if match is not None: + loaded_parameter = parameter.type.load(key, match) + # untyped_value = loaded_parameter.value + # if untyped_value is None: + # if isinstance(parameter, SequenceLoadedParameter): + # untyped_value = () + # elif isinstance(parameter, MapLoadedParameter): + # untyped_value = {} + try: + typed_value = loaded_parameter.typify(match.source) + except CustomValidationError as e: + validation_errors.append(e) + else: + collected_errors = loaded_parameter.collect_errors( + self, typed_value, match.source + ) + if collected_errors: + validation_errors.extend(collected_errors) + else: + typed_values[match.key] = typed_value + else: + # this situation will happen if there is a multikey_error and none of the + # matched keys is the primary key + pass + return typed_values, validation_errors + + def validate_all(self): + validation_errors = list( + chain.from_iterable( + self.check_source(source)[1] for source in self.raw_data + ) + ) + raise_errors(validation_errors) + self.validate_configuration() + + @staticmethod + def _collect_validation_error(func, *args, **kwargs): + try: + func(*args, **kwargs) + except ConfigurationError as e: + return (e.errors if hasattr(e, "errors") else e,) + return () + + def validate_configuration(self): + errors = chain.from_iterable( + Configuration._collect_validation_error(getattr, self, name) + for name in self.parameter_names + ) + post_errors = self.post_build_validation() + raise_errors(tuple(chain.from_iterable((errors, post_errors)))) + + def post_build_validation(self): + return () + + def collect_all(self) -> dict[str | Path, dict]: + typed_values = {} + validation_errors = {} + for source in self.raw_data: + typed_values[source], validation_errors[source] = self.check_source(source) + raise_errors(tuple(chain.from_iterable(validation_errors.values()))) + return {k: v for k, v in typed_values.items() if v} + + def describe_parameter(self, parameter_name): + # TODO, in Parameter base class, rename element_type to value_type + if parameter_name not in self.parameter_names: + parameter_name = "_" + parameter_name + + parameter_loader = self._get_parameter_loader(parameter_name) + if parameter_loader is None: + raise KeyError(parameter_name) + + parameter = parameter_loader.type + if not isinstance(parameter, Parameter): + raise TypeError( + f"Name '{parameter_name}' did not return a Parameter object." + ) + + # dedupe leading underscore from name + name = parameter_loader.name.lstrip("_") + aliases = tuple(alias for alias in parameter_loader.aliases if alias != name) + + description = self.get_descriptions().get(name, "") + et = parameter._element_type + if type(et) == EnumMeta: # noqa: E721 + et = [et] + if not isiterable(et): + et = [et] + + if isinstance(parameter._element_type, Parameter) or isinstance( + parameter._element_type, ConfigurationObject + ): + element_types = tuple( + _et.__class__.__name__.lower().replace("parameter", "") for _et in et + ) + else: + element_types = tuple(_et.__name__ for _et in et) + + details = { + "parameter_type": parameter.__class__.__name__.lower().replace( + "parameter", "" + ), + "name": name, + "aliases": aliases, + "element_types": element_types, + "default_value": parameter.default.typify("<>"), + "description": description.replace("\n", " ").strip(), + } + if isinstance(parameter, SequenceParameter): + details["string_delimiter"] = parameter.string_delimiter + return details + + def list_parameters(self, aliases: bool = False): + if aliases: + return tuple( + dict.fromkeys( + name for p in self._parameter_loaders.values() for name in p._names + ) + ) + return tuple(sorted(name.lstrip("_") for name in self.parameter_names)) + + def typify_parameter(self, parameter_name, value, source): + # return a tuple with correct parameter name and typed-value + if parameter_name not in self.parameter_names: + parameter_name = "_" + parameter_name + + parameter_loader = self._get_parameter_loader(parameter_name) + if parameter_loader is None: + raise KeyError(parameter_name) + + parameter = parameter_loader.type + if not isinstance(parameter, Parameter): + raise TypeError( + f"Name '{parameter_name}' did not return a Parameter object." + ) + + return parameter.typify(parameter_name, source, value) + + def get_descriptions(self): + raise NotImplementedError() + + +def unique_sequence_map(*, unique_key: str): + """ + Used to validate properties on :class:`Configuration` subclasses defined as a + ``SequenceParameter(MapParameter())`` where the map contains a single key that + should be regarded as unique. This decorator will handle removing duplicates and + merging to a single sequence. + """ + + def inner_wrap(func): + @wraps(func) + def wrapper(*args, **kwargs): + sequence_map = func(*args, **kwargs) + new_sequence_mapping = {} + + for mapping in sequence_map: + unique_key_value = mapping.get(unique_key) + + if unique_key_value is None: + log.error( + f'Configuration: skipping {mapping} for "{func.__name__}"; unique key ' + f'"{unique_key}" not present on mapping' + ) + continue + + if unique_key_value in new_sequence_mapping: + log.error( + f'Configuration: skipping {mapping} for "{func.__name__}"; value ' + f'"{unique_key_value}" already present' + ) + continue + + new_sequence_mapping[unique_key_value] = mapping + + return tuple(new_sequence_mapping.values()) + + return wrapper + + return inner_wrap diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/constants.py b/miniconda3/lib/python3.13/site-packages/conda/common/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..07b72de81e5653703d9818e5689f67d272f77460 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/constants.py @@ -0,0 +1,14 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common constants.""" + +from ..auxlib import NULL + +# Use this NULL object when needing to distinguish a value from None +# For example, when parsing json, you may need to determine if a json key was given and set +# to null, or the key didn't exist at all. There could be a bit of potential confusion here, +# because in python null == None, while here I'm defining NULL to mean 'not defined'. +NULL = NULL + +# Custom "trace" logging level for output more verbose than debug logs (logging.DEBUG == 10). +TRACE = 5 diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/io.py b/miniconda3/lib/python3.13/site-packages/conda/common/io.py new file mode 100644 index 0000000000000000000000000000000000000000..2e7e56da0922941e91ac400525f797676bce2de8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/io.py @@ -0,0 +1,547 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common I/O utilities.""" + +import logging +import os +import signal +import sys +from collections import defaultdict +from concurrent.futures import Executor, Future, ThreadPoolExecutor, as_completed +from contextlib import contextmanager +from enum import Enum +from errno import EPIPE, ESHUTDOWN +from functools import partial, wraps +from io import BytesIO, StringIO +from logging import CRITICAL, WARN, Formatter, StreamHandler, getLogger +from os.path import dirname, isdir, isfile, join +from threading import Lock +from time import time + +from ..auxlib.decorators import memoizemethod +from ..auxlib.logz import NullHandler +from ..auxlib.type_coercion import boolify +from ..common.serialize import json +from ..deprecations import deprecated +from .compat import encode_environment, on_win +from .constants import NULL +from .path import expand + +log = getLogger(__name__) +IS_INTERACTIVE = hasattr(sys.stdout, "isatty") and sys.stdout.isatty() + + +class DeltaSecondsFormatter(Formatter): + """ + Logging formatter with additional attributes for run time logging. + + Attributes: + `delta_secs`: + Elapsed seconds since last log/format call (or creation of logger). + `relative_created_secs`: + Like `relativeCreated`, time relative to the initialization of the + `logging` module but conveniently scaled to seconds as a `float` value. + """ + + def __init__(self, fmt=None, datefmt=None): + self.prev_time = time() + super().__init__(fmt=fmt, datefmt=datefmt) + + def format(self, record): + now = time() + prev_time = self.prev_time + self.prev_time = max(self.prev_time, now) + record.delta_secs = now - prev_time + record.relative_created_secs = record.relativeCreated / 1000 + return super().format(record) + + +if boolify(os.environ.get("CONDA_TIMED_LOGGING")): + _FORMATTER = DeltaSecondsFormatter( + "%(relative_created_secs) 7.2f %(delta_secs) 7.2f " + "%(levelname)s %(name)s:%(funcName)s(%(lineno)d): %(message)s" + ) +else: + _FORMATTER = Formatter( + "%(levelname)s %(name)s:%(funcName)s(%(lineno)d): %(message)s" + ) + + +def dashlist(iterable, indent=2): + return "".join("\n" + " " * indent + "- " + str(x) for x in iterable) + + +class ContextDecorator: + """Base class for a context manager class (implementing __enter__() and __exit__()) that also + makes it a decorator. + """ + + # TODO: figure out how to improve this pattern so e.g. swallow_broken_pipe doesn't have to be instantiated + + def __call__(self, f): + @wraps(f) + def decorated(*args, **kwds): + with self: + return f(*args, **kwds) + + return decorated + + +class SwallowBrokenPipe(ContextDecorator): + # Ignore BrokenPipeError and errors related to stdout or stderr being + # closed by a downstream program. + + def __enter__(self): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + if ( + exc_val + and isinstance(exc_val, EnvironmentError) + and getattr(exc_val, "errno", None) + and exc_val.errno in (EPIPE, ESHUTDOWN) + ): + return True + + +swallow_broken_pipe = SwallowBrokenPipe() + + +class CaptureTarget(Enum): + """Constants used for contextmanager captured. + + Used similarly like the constants PIPE, STDOUT for stdlib's subprocess.Popen. + """ + + STRING = -1 + STDOUT = -2 + + +@contextmanager +def env_vars(var_map=None, callback=None, stack_callback=None): + if var_map is None: + var_map = {} + + new_var_map = encode_environment(var_map) + saved_vars = {} + for name, value in new_var_map.items(): + saved_vars[name] = os.environ.get(name, NULL) + os.environ[name] = value + try: + if callback: + callback() + if stack_callback: + stack_callback(True) + yield + finally: + for name, value in saved_vars.items(): + if value is NULL: + del os.environ[name] + else: + os.environ[name] = value + if callback: + callback() + if stack_callback: + stack_callback(False) + + +@contextmanager +def env_var(name, value, callback=None, stack_callback=None): + d = {name: value} + with env_vars(d, callback=callback, stack_callback=stack_callback) as es: + yield es + + +@contextmanager +def env_unmodified(callback=None): + with env_vars(callback=callback) as es: + yield es + + +@contextmanager +def captured(stdout=CaptureTarget.STRING, stderr=CaptureTarget.STRING): + r"""Capture outputs of sys.stdout and sys.stderr. + + If stdout is STRING, capture sys.stdout as a string, + if stdout is None, do not capture sys.stdout, leaving it untouched, + otherwise redirect sys.stdout to the file-like object given by stdout. + + Behave correspondingly for stderr with the exception that if stderr is STDOUT, + redirect sys.stderr to stdout target and set stderr attribute of yielded object to None. + + .. code-block:: pycon + + >>> from conda.common.io import captured + >>> with captured() as c: + ... print("hello world!") + ... + >>> c.stdout + 'hello world!\n' + + Args: + stdout: capture target for sys.stdout, one of STRING, None, or file-like object + stderr: capture target for sys.stderr, one of STRING, STDOUT, None, or file-like object + + Yields: + CapturedText: has attributes stdout, stderr which are either strings, None or the + corresponding file-like function argument. + """ + + def write_wrapper(self, to_write): + # NOTE: This function is not thread-safe. Using within multi-threading may cause spurious + # behavior of not returning sys.stdout and sys.stderr back to their 'proper' state + # This may have to deal with a *lot* of text. + if hasattr(self, "mode") and "b" in self.mode: + wanted = bytes + elif isinstance(self, BytesIO): + wanted = bytes + else: + wanted = str + if not isinstance(to_write, wanted): + if hasattr(to_write, "decode"): + decoded = to_write.decode("utf-8") + self.old_write(decoded) + elif hasattr(to_write, "encode"): + b = to_write.encode("utf-8") + self.old_write(b) + else: + self.old_write(to_write) + + class CapturedText: + pass + + # sys.stdout.write(u'unicode out') + # sys.stdout.write(bytes('bytes out', encoding='utf-8')) + # sys.stdout.write(str('str out')) + saved_stdout, saved_stderr = sys.stdout, sys.stderr + if stdout == CaptureTarget.STRING: + outfile = StringIO() + outfile.old_write = outfile.write + outfile.write = partial(write_wrapper, outfile) + sys.stdout = outfile + else: + outfile = stdout + if outfile is not None: + sys.stdout = outfile + if stderr == CaptureTarget.STRING: + errfile = StringIO() + errfile.old_write = errfile.write + errfile.write = partial(write_wrapper, errfile) + sys.stderr = errfile + elif stderr == CaptureTarget.STDOUT: + sys.stderr = errfile = outfile + else: + errfile = stderr + if errfile is not None: + sys.stderr = errfile + c = CapturedText() + log.debug("overtaking stderr and stdout") + try: + yield c + finally: + if stdout == CaptureTarget.STRING: + c.stdout = outfile.getvalue() + else: + c.stdout = outfile + if stderr == CaptureTarget.STRING: + c.stderr = errfile.getvalue() + elif stderr == CaptureTarget.STDOUT: + c.stderr = None + else: + c.stderr = errfile + sys.stdout, sys.stderr = saved_stdout, saved_stderr + log.debug("stderr and stdout yielding back") + + +@contextmanager +def argv(args_list): + saved_args = sys.argv + sys.argv = args_list + try: + yield + finally: + sys.argv = saved_args + + +@deprecated("25.9", "26.3", addendum="Use `logging._lock` instead.") +@contextmanager +def _logger_lock(): + logging._acquireLock() + try: + yield + finally: + logging._releaseLock() + + +@contextmanager +def disable_logger(logger_name): + logr = getLogger(logger_name) + _lvl, _dsbld, _prpgt = logr.level, logr.disabled, logr.propagate + null_handler = NullHandler() + with logging._lock: + logr.addHandler(null_handler) + logr.setLevel(CRITICAL + 1) + logr.disabled, logr.propagate = True, False + try: + yield + finally: + with logging._lock: + logr.removeHandler(null_handler) # restore list logr.handlers + logr.level, logr.disabled = _lvl, _dsbld + logr.propagate = _prpgt + + +@contextmanager +def stderr_log_level(level, logger_name=None): + logr = getLogger(logger_name) + _hndlrs, _lvl, _dsbld, _prpgt = ( + logr.handlers, + logr.level, + logr.disabled, + logr.propagate, + ) + handler = StreamHandler(sys.stderr) + handler.name = "stderr" + handler.setLevel(level) + handler.setFormatter(_FORMATTER) + with logging._lock: + logr.setLevel(level) + logr.handlers, logr.disabled, logr.propagate = [], False, False + logr.addHandler(handler) + logr.setLevel(level) + try: + yield + finally: + with logging._lock: + logr.handlers, logr.level, logr.disabled = _hndlrs, _lvl, _dsbld + logr.propagate = _prpgt + + +def attach_stderr_handler( + level=WARN, + logger_name=None, + propagate=False, + formatter=None, + filters=None, +): + """Attach a new `stderr` handler to the given logger and configure both. + + This function creates a new StreamHandler that writes to `stderr` and attaches it + to the logger given by `logger_name` (which maybe `None`, in which case the root + logger is used). If the logger already has a handler by the name of `stderr`, it is + removed first. + + The given `level` is set **for the handler**, not for the logger; however, this + function also sets the level of the given logger to the minimum of its current + effective level and the new handler level, ensuring that the handler will receive the + required log records, while minimizing the number of unnecessary log events. It also + sets the loggers `propagate` property according to the `propagate` argument. + The `formatter` argument can be used to set the formatter of the handler. + """ + # get old stderr logger + logr = getLogger(logger_name) + old_stderr_handler = next( + (handler for handler in logr.handlers if handler.name == "stderr"), None + ) + + # create new stderr logger + new_stderr_handler = StreamHandler(sys.stderr) + new_stderr_handler.name = "stderr" + new_stderr_handler.setLevel(level) + new_stderr_handler.setFormatter(formatter or _FORMATTER) + for filter_ in filters or (): + new_stderr_handler.addFilter(filter_) + + # do the switch + with logging._lock: + if old_stderr_handler: + logr.removeHandler(old_stderr_handler) + logr.addHandler(new_stderr_handler) + if level < logr.getEffectiveLevel(): + logr.setLevel(level) + logr.propagate = propagate + + +def timeout(timeout_secs, func, *args, default_return=None, **kwargs): + """Enforce a maximum time for a callable to complete. + Not yet implemented on Windows. + """ + if on_win: + # Why does Windows have to be so difficult all the time? Kind of gets old. + # Guess we'll bypass Windows timeouts for now. + try: + return func(*args, **kwargs) + except KeyboardInterrupt: # pragma: no cover + return default_return + else: + + class TimeoutException(Exception): + pass + + def interrupt(signum, frame): + raise TimeoutException() + + signal.signal(signal.SIGALRM, interrupt) + signal.alarm(timeout_secs) + + try: + ret = func(*args, **kwargs) + signal.alarm(0) + return ret + except (TimeoutException, KeyboardInterrupt): # pragma: no cover + return default_return + + +# use this for debugging, because ProcessPoolExecutor isn't pdb/ipdb friendly +class DummyExecutor(Executor): + def __init__(self): + self._shutdown = False + self._shutdownLock = Lock() + + def submit(self, fn, *args, **kwargs): + with self._shutdownLock: + if self._shutdown: + raise RuntimeError("cannot schedule new futures after shutdown") + + f = Future() + try: + result = fn(*args, **kwargs) + except BaseException as e: + f.set_exception(e) + else: + f.set_result(result) + + return f + + def map(self, func, *iterables): + for iterable in iterables: + for thing in iterable: + yield func(thing) + + def shutdown(self, wait=True): + with self._shutdownLock: + self._shutdown = True + + +class ThreadLimitedThreadPoolExecutor(ThreadPoolExecutor): + def __init__(self, max_workers=10): + super().__init__(max_workers) + + def _adjust_thread_count(self): + try: + return super()._adjust_thread_count() + except RuntimeError: + # RuntimeError: can't start new thread + # See https://github.com/conda/conda/issues/6624 + if len(self._threads) > 0: + # It's ok to not be able to start new threads if we already have at least + # one thread alive. + pass + else: + raise + + +as_completed = as_completed + + +def get_instrumentation_record_file(): + default_record_file = join("~", ".conda", "instrumentation-record.csv") + return expand( + os.environ.get("CONDA_INSTRUMENTATION_RECORD_FILE", default_record_file) + ) + + +class time_recorder(ContextDecorator): # pragma: no cover + record_file = get_instrumentation_record_file() + start_time = None + total_call_num = defaultdict(int) + total_run_time = defaultdict(float) + + def __init__(self, entry_name=None, module_name=None): + self.entry_name = entry_name + self.module_name = module_name + + def _set_entry_name(self, f): + if self.entry_name is None: + if hasattr(f, "__qualname__"): + entry_name = f.__qualname__ + else: + entry_name = ":" + f.__name__ + if self.module_name: + entry_name = ".".join((self.module_name, entry_name)) + self.entry_name = entry_name + + def __call__(self, f): + self._set_entry_name(f) + return super().__call__(f) + + def __enter__(self): + enabled = os.environ.get("CONDA_INSTRUMENTATION_ENABLED") + if enabled and boolify(enabled): + self.start_time = time() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.start_time: + entry_name = self.entry_name + end_time = time() + run_time = end_time - self.start_time + self.total_call_num[entry_name] += 1 + self.total_run_time[entry_name] += run_time + self._ensure_dir() + with open(self.record_file, "a") as fh: + fh.write(f"{entry_name},{run_time:f}\n") + # total_call_num = self.total_call_num[entry_name] + # total_run_time = self.total_run_time[entry_name] + # log.debug('%s %9.3f %9.3f %d', entry_name, run_time, total_run_time, total_call_num) + + @classmethod + def log_totals(cls): + enabled = os.environ.get("CONDA_INSTRUMENTATION_ENABLED") + if not (enabled and boolify(enabled)): + return + log.info("=== time_recorder total time and calls ===") + for entry_name in sorted(cls.total_run_time.keys()): + log.info( + "TOTAL %9.3f % 9d %s", + cls.total_run_time[entry_name], + cls.total_call_num[entry_name], + entry_name, + ) + + @memoizemethod + def _ensure_dir(self): + if not isdir(dirname(self.record_file)): + os.makedirs(dirname(self.record_file)) + + +def print_instrumentation_data(): # pragma: no cover + record_file = get_instrumentation_record_file() + + grouped_data = defaultdict(list) + final_data = {} + + if not isfile(record_file): + return + + with open(record_file) as fh: + for line in fh: + entry_name, total_time = line.strip().split(",") + grouped_data[entry_name].append(float(total_time)) + + for entry_name in sorted(grouped_data): + all_times = grouped_data[entry_name] + counts = len(all_times) + total_time = sum(all_times) + average_time = total_time / counts + final_data[entry_name] = { + "counts": counts, + "total_time": total_time, + "average_time": average_time, + } + + print(json.dumps(final_data, sort_keys=True, indent=2, separators=(",", ": "))) + + +if __name__ == "__main__": + print_instrumentation_data() diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/iterators.py b/miniconda3/lib/python3.13/site-packages/conda/common/iterators.py new file mode 100644 index 0000000000000000000000000000000000000000..a7405113f5cf9bdaf683b1efa21aedd07b9f48c4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/iterators.py @@ -0,0 +1,39 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Replacements for parts of the toolz library.""" + +from __future__ import annotations + +import collections +import itertools +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Generator, Sequence + from typing import Any + + +def groupby_to_dict(keyfunc, sequence): + """A `toolz`-style groupby implementation. + + Returns a dictionary of { key: [group] } instead of iterators. + """ + result = collections.defaultdict(list) + for key, group in itertools.groupby(sequence, keyfunc): + result[key].extend(group) + return dict(result) + + +def unique(sequence: Sequence[Any]) -> Generator[Any, None, None]: + """A `toolz` inspired `unique` implementation. + + Returns a generator of unique elements in the sequence + """ + seen: set[Any] = set() + yield from ( + # seen.add always returns None so we will always return element + seen.add(element) or element + for element in sequence + # only pass along novel elements + if element not in seen + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/logic.py b/miniconda3/lib/python3.13/site-packages/conda/common/logic.py new file mode 100644 index 0000000000000000000000000000000000000000..7f30c1ca53a567e80152d0f47ddf874fc5d3c77d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/logic.py @@ -0,0 +1,312 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +The basic idea to nest logical expressions is instead of trying to denest +things via distribution, we add new variables. So if we have some logical +expression expr, we replace it with x and add expr <-> x to the clauses, +where x is a new variable, and expr <-> x is recursively evaluated in the +same way, so that the final clauses are ORs of atoms. + +To use this, create a new Clauses object with the max var, for instance, if you +already have [[1, 2, -3]], you would use C = Clause(3). All functions return +a new literal, which represents that function, or True or False if the expression +can be resolved fully. They may also add new clauses to C.clauses, which +will then be delivered to the SAT solver. + +All functions take atoms as arguments (an atom is an integer, representing a +literal or a negated literal, or boolean constants True or False; that is, +it is the callers' responsibility to do the conversion of expressions +recursively. This is done because we do not have data structures +representing the various logical classes, only atoms. + +The polarity argument can be set to True or False if you know that the literal +being used will only be used in the positive or the negative, respectively +(e.g., you will only use x, not -x). This will generate fewer clauses. It +is probably best if you do not take advantage of this directly, but rather +through the Require and Prevent functions. + +""" + +from itertools import chain + +from ._logic import FALSE, TRUE +from ._logic import Clauses as _Clauses + +# TODO: We may want to turn the user-facing {TRUE,FALSE} values into an Enum and +# hide the _logic.{TRUE,FALSE} values as an implementation detail. +# We then have to handle the {TRUE,FALSE} -> _logic.{TRUE,FALSE} conversion +# in Clauses._convert and the inverse _logic.{TRUE,FALSE} -> {TRUE,FALSE} +# conversion in Clauses._eval. +TRUE = TRUE +FALSE = FALSE + +PycoSatSolver = "pycosat" +PyCryptoSatSolver = "pycryptosat" +PySatSolver = "pysat" + + +class Clauses: + def __init__(self, m=0, sat_solver=PycoSatSolver): + self.names = {} + self.indices = {} + self._clauses = _Clauses(m=m, sat_solver_str=sat_solver) + + @property + def m(self): + return self._clauses.m + + @property + def unsat(self): + return self._clauses.unsat + + def get_clause_count(self): + return self._clauses.get_clause_count() + + def as_list(self): + return self._clauses.as_list() + + def _check_variable(self, variable): + if 0 < abs(variable) <= self.m: + return variable + raise ValueError(f"SAT variable out of bounds: {variable} (max_var: {self.m})") + + def _check_literal(self, literal): + if literal in {TRUE, FALSE}: + return literal + return self._check_variable(literal) + + def add_clause(self, clause): + self._clauses.add_clause(map(self._check_variable, self._convert(clause))) + + def add_clauses(self, clauses): + for clause in clauses: + self.add_clause(clause) + + def name_var(self, m, name): + self._check_literal(m) + nname = "!" + name + self.names[name] = m + self.names[nname] = -m + if m not in {TRUE, FALSE} and m not in self.indices: + self.indices[m] = name + self.indices[-m] = nname + return m + + def new_var(self, name=None): + m = self._clauses.new_var() + if name: + self.name_var(m, name) + return m + + def from_name(self, name): + return self.names.get(name) + + def from_index(self, m): + return self.indices.get(m) + + def _assign(self, vals, name=None): + x = self._clauses.assign(vals) + if not name: + return x + if vals in {TRUE, FALSE}: + x = self._clauses.new_var() + self._clauses.add_clause((x,) if vals else (-x,)) + return self.name_var(x, name) + + def _convert(self, x): + if isinstance(x, (tuple, list)): + return type(x)(map(self._convert, x)) + if isinstance(x, int): + return self._check_literal(x) + name = x + try: + return self.names[name] + except KeyError: + raise ValueError(f"Unregistered SAT variable name: {name}") + + def _eval(self, func, args, no_literal_args, polarity, name): + args = self._convert(args) + if name is False: + self._clauses.Eval(func, args + no_literal_args, polarity) + return None + vals = func(*(args + no_literal_args), polarity=polarity) + return self._assign(vals, name) + + def Prevent(self, what, *args): + return what.__get__(self, Clauses)(*args, polarity=False, name=False) + + def Require(self, what, *args): + return what.__get__(self, Clauses)(*args, polarity=True, name=False) + + def Not(self, x, polarity=None, name=None): + return self._eval(self._clauses.Not, (x,), (), polarity, name) + + def And(self, f, g, polarity=None, name=None): + return self._eval(self._clauses.And, (f, g), (), polarity, name) + + def Or(self, f, g, polarity=None, name=None): + return self._eval(self._clauses.Or, (f, g), (), polarity, name) + + def Xor(self, f, g, polarity=None, name=None): + return self._eval(self._clauses.Xor, (f, g), (), polarity, name) + + def ITE(self, c, t, f, polarity=None, name=None): + """If c Then t Else f. + + In this function, if any of c, t, or f are True and False the resulting + expression is resolved. + """ + return self._eval(self._clauses.ITE, (c, t, f), (), polarity, name) + + def All(self, iter, polarity=None, name=None): + return self._eval(self._clauses.All, (iter,), (), polarity, name) + + def Any(self, vals, polarity=None, name=None): + return self._eval(self._clauses.Any, (list(vals),), (), polarity, name) + + def AtMostOne_NSQ(self, vals, polarity=None, name=None): + return self._eval( + self._clauses.AtMostOne_NSQ, (list(vals),), (), polarity, name + ) + + def AtMostOne_BDD(self, vals, polarity=None, name=None): + return self._eval( + self._clauses.AtMostOne_BDD, (list(vals),), (), polarity, name + ) + + def AtMostOne(self, vals, polarity=None, name=None): + vals = list(vals) + nv = len(vals) + if nv < 5 - (polarity is not True): + what = self.AtMostOne_NSQ + else: + what = self.AtMostOne_BDD + return self._eval(what, (vals,), (), polarity, name) + + def ExactlyOne_NSQ(self, vals, polarity=None, name=None): + return self._eval( + self._clauses.ExactlyOne_NSQ, (list(vals),), (), polarity, name + ) + + def ExactlyOne_BDD(self, vals, polarity=None, name=None): + return self._eval( + self._clauses.ExactlyOne_BDD, (list(vals),), (), polarity, name + ) + + def ExactlyOne(self, vals, polarity=None, name=None): + vals = list(vals) + nv = len(vals) + if nv < 2: + what = self.ExactlyOne_NSQ + else: + what = self.ExactlyOne_BDD + return self._eval(what, (vals,), (), polarity, name) + + def LinearBound(self, equation, lo, hi, preprocess=True, polarity=None, name=None): + if not isinstance(equation, dict): + # in case of duplicate literal -> coefficient mappings, always take the last one + equation = {named_lit: coeff for coeff, named_lit in equation} + named_literals = list(equation.keys()) + coefficients = list(equation.values()) + return self._eval( + self._clauses.LinearBound, + (named_literals,), + (coefficients, lo, hi, preprocess), + polarity, + name, + ) + + def sat(self, additional=None, includeIf=False, names=False, limit=0): + """ + Calculate a SAT solution for the current clause set. + + Returned is the list of those solutions. When the clauses are + unsatisfiable, an empty list is returned. + + """ + if self.unsat: + return None + if not self.m: + return set() if names else [] + if additional: + additional = (tuple(self.names.get(c, c) for c in cc) for cc in additional) + solution = self._clauses.sat( + additional=additional, includeIf=includeIf, limit=limit + ) + if solution is None: + return None + if names: + return { + nm + for nm in (self.indices.get(s) for s in solution) + if nm and nm[0] != "!" + } + return solution + + def itersolve(self, constraints=None, m=None): + exclude = [] + if m is None: + m = self.m + while True: + # We don't use pycosat.itersolve because it is more + # important to limit the number of terms added to the + # exclusion list, in our experience. Once we update + # pycosat to do this, this can use it. + sol = self.sat(chain(constraints, exclude)) + if sol is None: + return + yield sol + exclude.append([-k for k in sol if -m <= k <= m]) + + def minimize(self, objective, bestsol=None, trymax=False): + if not isinstance(objective, dict): + # in case of duplicate literal -> coefficient mappings, always take the last one + objective = {named_lit: coeff for coeff, named_lit in objective} + literals = self._convert(list(objective.keys())) + coeffs = list(objective.values()) + + return self._clauses.minimize(literals, coeffs, bestsol=bestsol, trymax=trymax) + + +def minimal_unsatisfiable_subset(clauses, sat, explicit_specs): + """ + Given a set of clauses, find a minimal unsatisfiable subset (an + unsatisfiable core) + + A set is a minimal unsatisfiable subset if no proper subset is + unsatisfiable. A set of clauses may have many minimal unsatisfiable + subsets of different sizes. + + sat should be a function that takes a tuple of clauses and returns True if + the clauses are satisfiable and False if they are not. The algorithm will + work with any order-reversing function (reversing the order of subset and + the order False < True), that is, any function where (A <= B) iff (sat(B) + <= sat(A)), where A <= B means A is a subset of B and False < True). + + """ + working_set = set() + found_conflicts = set() + + if sat(explicit_specs, True) is None: + found_conflicts = set(explicit_specs) + else: + # we succeeded, so we'll add the spec to our future constraints + working_set = set(explicit_specs) + + for spec in set(clauses) - working_set: + if ( + sat( + working_set + | { + spec, + }, + True, + ) + is None + ): + found_conflicts.add(spec) + else: + # we succeeded, so we'll add the spec to our future constraints + working_set.add(spec) + + return found_conflicts diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/path/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/common/path/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91d587a9be41bab8455a516866b68d305af429b6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/path/__init__.py @@ -0,0 +1,239 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common path utilities.""" + +from __future__ import annotations + +import os +import re +from functools import cache +from logging import getLogger +from os.path import ( + abspath, + expanduser, + expandvars, + normcase, + split, +) +from typing import TYPE_CHECKING +from urllib.parse import urlsplit + +from ... import CondaError +from ...deprecations import deprecated +from ..compat import on_win +from .directories import ( + explode_directories, + get_all_directories, + get_leaf_directories, + tokenized_startswith, +) +from .python import ( + get_major_minor_version, + get_python_noarch_target_path, + get_python_short_path, + get_python_site_packages_short_path, + missing_pyc_files, + parse_entry_point_def, + pyc_path, +) +from .windows import ( + unix_path_to_win, + win_path_backout, + win_path_double_escape, + win_path_ok, + win_path_to_unix, +) + +if TYPE_CHECKING: + from collections.abc import Iterable + + PathType = str | os.PathLike[str] + PathsType = Iterable[PathType] + +__all__ = [ + "explode_directories", + "get_all_directories", + "get_leaf_directories", + "get_major_minor_version", + "get_python_noarch_target_path", + "get_python_short_path", + "get_python_site_packages_short_path", + "missing_pyc_files", + "parse_entry_point_def", + "pyc_path", + "tokenized_startswith", + "unix_path_to_win", + "win_path_backout", + "win_path_double_escape", + "win_path_ok", + "win_path_to_unix", +] + +log = getLogger(__name__) + +PATH_MATCH_REGEX = ( + r"\./" # ./ + r"|\.\." # .. + r"|~" # ~ + r"|/" # / + r"|[a-zA-Z]:[/\\]" # drive letter, colon, forward or backslash + r"|\\\\" # windows UNC path + r"|//" # windows UNC path +) + +# Repodata file extensions (static, not plugin-dependent) +KNOWN_REPODATA_EXTENSIONS = ( + ".json", + ".jlap", + ".json.zst", +) + +deprecated.constant( + "26.9", + "27.3", + "KNOWN_EXTENSIONS", + (".conda", ".tar.bz2", *KNOWN_REPODATA_EXTENSIONS), + addendum="Use `conda.common.path.strip_pkg_extension` instead.", +) + + +def is_path(value): + if "://" in value: + return False + return re.match(PATH_MATCH_REGEX, value) + + +def expand(path): + return abspath(expanduser(expandvars(path))) + + +def paths_equal(path1, path2): + """ + Examples: + >>> paths_equal('/a/b/c', '/a/b/c/d/..') + True + + """ + if on_win: + return normcase(abspath(path1)) == normcase(abspath(path2)) + else: + return abspath(path1) == abspath(path2) + + +@cache +def url_to_path(url): + """Convert a file:// URL to a path. + + Relative file URLs (i.e. `file:relative/path`) are not supported. + """ + if is_path(url): + return url + if not url.startswith("file://"): # pragma: no cover + raise CondaError( + f"You can only turn absolute file: urls into paths (not {url})" + ) + _, netloc, path, _, _ = urlsplit(url) + from ..url import percent_decode + + path = percent_decode(path) + if netloc not in ("", "localhost", "127.0.0.1", "::1"): + if not netloc.startswith("\\\\"): + # The only net location potentially accessible is a Windows UNC path + netloc = "//" + netloc + else: + netloc = "" + # Handle Windows drive letters if present + if re.match("^/([a-z])[:|]", path, re.I): + path = path[1] + ":" + path[3:] + return netloc + path + + +BIN_DIRECTORY = "Scripts" if on_win else "bin" + + +def ensure_pad(name, pad="_"): + """ + + Examples: + >>> ensure_pad('conda') + '_conda_' + >>> ensure_pad('_conda') + '__conda_' + >>> ensure_pad('') + '' + + """ + if not name or name[0] == name[-1] == pad: + return name + else: + return f"{pad}{name}{pad}" + + +def right_pad_os_sep(path): + return path if path.endswith(os.sep) else path + os.sep + + +def split_filename(path_or_url): + dn, fn = split(path_or_url) + return (dn or None, fn) if "." in fn else (path_or_url, None) + + +def strip_pkg_extension(path: str) -> tuple[str, str | None]: + """ + Split path into (base, extension) for known extensions. + + Package extensions are determined dynamically from registered plugins. + Repodata extensions (.json, .jlap, .json.zst) are also recognized. + + :param path: Path to split. + :return: Tuple of (base_path, extension) where extension is None if not found. + + Examples: + >>> strip_pkg_extension("/path/_license-1.1-py27_1.tar.bz2") + ('/path/_license-1.1-py27_1', '.tar.bz2') + >>> strip_pkg_extension("/path/_license-1.1-py27_1.conda") + ('/path/_license-1.1-py27_1', '.conda') + >>> strip_pkg_extension("/path/repodata.json") + ('/path/repodata', '.json') + >>> strip_pkg_extension("/path/_license-1.1-py27_1") + ('/path/_license-1.1-py27_1', None) + """ + from ...base.context import context + + # Check package extensions first (dynamic from plugins) + if ext := context.plugin_manager.has_package_extension(path): + return path[: -len(ext)], ext + # Then additional extensions (static) + for ext in KNOWN_REPODATA_EXTENSIONS: + if path.endswith(ext): + return path[: -len(ext)], ext + return path, None + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.base.context.context.plugin_manager.has_package_extension` instead.", +) +def is_package_file(path): + """ + Examples: + >>> is_package_file("/path/_license-1.1-py27_1.tar.bz2") + True + >>> is_package_file("/path/_license-1.1-py27_1.conda") + True + >>> is_package_file("/path/_license-1.1-py27_1") + False + """ + # NOTE: not using CONDA_TARBALL_EXTENSION_V1 or CONDA_TARBALL_EXTENSION_V2 to comply with + # import rules and to avoid a global lookup. + return path[-6:] == ".conda" or path[-8:] == ".tar.bz2" + + +def path_identity(paths: PathType | PathsType | None) -> str | tuple[str, ...] | None: + if paths is None: + return None + elif isinstance(paths, (str, os.PathLike)): + return os.path.normpath(paths) + else: + return tuple(os.path.normpath(path) for path in paths) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/path/_cygpath.py b/miniconda3/lib/python3.13/site-packages/conda/common/path/_cygpath.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5d371e9612eb37af54e4c5b48dd95d963ad6d4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/path/_cygpath.py @@ -0,0 +1,268 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from __future__ import annotations + +import ntpath +import os +import posixpath +import re +from functools import partial +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from . import PathType + + +def nt_to_posix(path: PathType, prefix: PathType | None, cygdrive: bool = False) -> str: + """ + A fallback implementation of `cygpath --unix`. + + Args: + path: The path to convert. + prefix: The Windows style prefix directory to use for the conversion. + If not provided, no checks for root paths will be made. + cygdrive: Whether to use the Cygwin-style drive prefix. + """ + path = os.fspath(path) + prefix = os.fspath(prefix) if prefix else None + + if ntpath.pathsep in path: + return posixpath.pathsep.join( + converted + for path in path.split(ntpath.pathsep) + if (converted := nt_to_posix(path, prefix, cygdrive)) + ) + + # cygpath drops empty strings + if not path: + return path + + # Revert in reverse order of the transformations in posix_to_nt: + # 1. root filesystem forms: + # {prefix}\Library\root + # → /root + # 2. mount forms: + # \\mount + # → //mount + # 3. drive letter forms: + # X:\drive + # x:\drive + # → /x/drive + # → /cygdrive/x/drive + # 4. anything else + + # continue performing substitutions until a match is found + subs = 0 + + # only absolute paths can be detected as root, mount, or drive formats + # NOTE: C: & c: are absolute paths but ntpath.isabs doesn't recognize it + if ntpath.isabs(path) or path in ("C:", "c:"): + # only attempt to match root if prefix is defined + if prefix: + # normalize/resolve the path + norm_path = ntpath.normpath(path) + # ntpath.normpath strips trailing slashes, add them back + if path[-1] in "/\\": + norm_path += ntpath.sep + # attempt to match root + norm_path, subs = _get_RE_WIN_ROOT(prefix).subn(_to_unix_root, norm_path) + # only keep the normalized path if the root was matched + if subs: + path = norm_path + + # attempt to match mount + if not subs: + path, subs = RE_WIN_MOUNT.subn(_to_unix_mount, path) + + # attempt to match drive + if not subs: + path = RE_WIN_DRIVE.sub(partial(_to_unix_drive, cygdrive=cygdrive), path) + + return _resolve_path(path, posixpath.sep) + + +def _get_root(prefix: str) -> str: + # normalize path to remove duplicate slashes, .., and . + prefix = ntpath.normpath(prefix) + + # MSYS2's root filesystem, /, is defined relative to this DLL: + # {root}\usr\lib\msys-2.0.dll + # the conda community has chosen to install that DLL as: + # %CONDA_PREFIX%\Library\usr\lib\msys-2.0.dll + # so we can infer the root path is: + # {prefix}\Library + # ref: https://github.com/conda/conda/pull/14157#discussion_r1725384636 + return ntpath.join(prefix, "Library") + + +def _get_RE_WIN_ROOT(prefix: str) -> re.Pattern: + root = _get_root(prefix) + return re.compile( + rf""" + ^ + {re.escape(root)} + (?P.*)? + $ + """, + flags=re.VERBOSE, + ) + + +def _to_unix_root(match: re.Match) -> str: + return match.group("path") or "/" + + +RE_WIN_MOUNT = re.compile( + r""" + ^ + [/\\]{2}( + (?P[^/\\]+) + (?P.*)? + )? + $ + """, + flags=re.VERBOSE, +) + + +def _to_unix_mount(match: re.Match) -> str: + mount = match.group("mount") or "" + path = match.group("path") or "" + return f"//{mount}{path}" + + +RE_WIN_DRIVE = re.compile( + r""" + ^ + (?P[A-Za-z]): + (?P[/\\]+.*)? + $ + """, + flags=re.VERBOSE, +) + + +def _to_unix_drive(match: re.Match, cygdrive: bool) -> str: + drive = match.group("drive").lower() + path = match.group("path") or "" + return f"{'/cygdrive' if cygdrive else ''}/{drive}{path}" + + +def posix_to_nt(path: PathType, prefix: PathType | None, cygdrive: bool = False) -> str: + """ + A fallback implementation of `cygpath --windows`. + + Args: + path: The path to convert. + prefix: The Windows style prefix directory to use for the conversion. + If not provided, no checks for root paths will be made. + cygdrive: Unused. Present to keep the signature consistent with `nt_to_posix`. + """ + path = os.fspath(path) + prefix = os.fspath(prefix) if prefix else None + + if posixpath.pathsep in path: + return ntpath.pathsep.join( + posix_to_nt(path, prefix) for path in path.split(posixpath.pathsep) + ) + + # cygpath converts a "" to "." + if not path: + return "." + + # Reverting a Unix path means unpicking MSYS2/Cygwin + # conventions -- in order! + # 1. drive letter forms: + # /x/drive (MSYS2) + # /cygdrive/x/drive (Cygwin) + # → X:\drive + # 2. mount forms: + # //mount + # → \\mount + # 3. root filesystem forms: + # /root + # → {prefix}\Library\root + # 3. anything else + + # only absolute paths can be detected as drive, mount, or root formats + if posixpath.isabs(path): + # continue performing substitutions until a match is found + subs = 0 + + # attempt to match drive + path, subs = RE_UNIX_DRIVE.subn(_to_win_drive, path) + + # attempt to match mount + if not subs: + path, subs = RE_UNIX_MOUNT.subn(_to_win_mount, path) + + # only attempt to match root if prefix is defined + if prefix and not subs: + root = _get_root(prefix) + path = RE_UNIX_ROOT.sub(partial(_to_win_root, root=root), path) + + return _resolve_path(path, ntpath.sep) + + +RE_UNIX_DRIVE = re.compile( + r""" + ^ + (/cygdrive)? + /(?P[A-Za-z]) + (/+(?P.*)?)? + $ + """, + flags=re.VERBOSE, +) + + +def _to_win_drive(match: re.Match) -> str: + drive = match.group("drive").upper() + path = match.group("path") or "" + return f"{drive}:\\{path}" + + +RE_UNIX_MOUNT = re.compile( + r""" + ^ + /{2}( + (?P[^/]+) + (?P/+.*)? + )? + $ + """, + flags=re.VERBOSE, +) + + +def _to_win_mount(match: re.Match) -> str: + mount = match.group("mount") or "" + path = match.group("path") or "" + return f"\\\\{mount}{path}" + + +RE_UNIX_ROOT = re.compile( + r""" + ^ + (?P/.*) + $ + """, + flags=re.VERBOSE, +) + + +def _to_win_root(match: re.Match, root: str) -> str: + path = match.group("path") + return f"{root}{path}" + + +def _resolve_path(path: str, sep: str) -> str: + leading = "" + if match := re.match(r"^([/\\]+)(.*)$", path): + leading, path = match.groups() + sep = re.escape(sep) + return re.sub(r"[/\\]", sep, leading) + re.sub(r"[/\\]+", sep, path) + + +def resolve_paths(paths: str, pathsep: str, sep: str) -> str: + return pathsep.join(_resolve_path(path, sep) for path in paths.split(pathsep)) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/path/directories.py b/miniconda3/lib/python3.13/site-packages/conda/common/path/directories.py new file mode 100644 index 0000000000000000000000000000000000000000..146fa8019fa1ae23cb5f88e29c9e575dcb2321cd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/path/directories.py @@ -0,0 +1,58 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common directory utilities.""" + +from __future__ import annotations + +from functools import reduce +from itertools import accumulate, chain +from logging import getLogger +from os.path import join +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + +log = getLogger(__name__) + + +def tokenized_startswith(test_iterable, startswith_iterable): + return all(t == sw for t, sw in zip(test_iterable, startswith_iterable)) + + +def get_all_directories(files: Iterable[str]) -> list[tuple[str, ...]]: + return sorted(filter(None, {tuple(f.split("/")[:-1]) for f in files})) + + +def get_leaf_directories(files: Iterable[str]) -> Sequence[str]: + # give this function a list of files, and it will hand back a list of leaf + # directories to pass to os.makedirs() + directories = get_all_directories(files) + if not directories: + return () + + leaves = [] + + def _process(x, y): + if not tokenized_startswith(y, x): + leaves.append(x) + return y + + last = reduce(_process, directories) + + if not leaves: + leaves.append(directories[-1]) + elif not tokenized_startswith(last, leaves[-1]): + leaves.append(last) + + return tuple("/".join(leaf) for leaf in leaves) + + +def explode_directories(child_directories: Iterable[tuple[str, ...]]) -> set[str]: + # get all directories including parents + # child_directories must already be split with os.path.split + return set( + chain.from_iterable( + accumulate(directory, join) for directory in child_directories if directory + ) + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/path/python.py b/miniconda3/lib/python3.13/site-packages/conda/common/path/python.py new file mode 100644 index 0000000000000000000000000000000000000000..3d8e1e21b4744006498d247c6b1b231a8275145a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/path/python.py @@ -0,0 +1,122 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common Python specific path utilities.""" + +from __future__ import annotations + +import re +from logging import getLogger +from os.path import join, split, splitext + +from ..compat import on_win + +log = getLogger(__name__) + + +def pyc_path(py_path, python_major_minor_version): + """ + This must not return backslashes on Windows as that will break + tests and leads to an eventual need to make url_to_path return + backslashes too and that may end up changing files on disc or + to the result of comparisons with the contents of them. + """ + pyver_string = python_major_minor_version.replace(".", "") + if pyver_string.startswith("2"): + return py_path + "c" + else: + directory, py_file = split(py_path) + basename_root, extension = splitext(py_file) + pyc_file = ( + "__pycache__" + "/" + f"{basename_root}.cpython-{pyver_string}{extension}c" + ) + return "{}{}{}".format(directory, "/", pyc_file) if directory else pyc_file + + +def missing_pyc_files(python_major_minor_version, files): + # returns a tuple of tuples, with the inner tuple being the .py file and the missing .pyc file + py_files = (f for f in files if f.endswith(".py")) + pyc_matches = ( + (py_file, pyc_path(py_file, python_major_minor_version)) for py_file in py_files + ) + result = tuple(match for match in pyc_matches if match[1] not in files) + return result + + +def parse_entry_point_def(ep_definition): + cmd_mod, func = ep_definition.rsplit(":", 1) + command, module = cmd_mod.rsplit("=", 1) + command, module, func = command.strip(), module.strip(), func.strip() + return command, module, func + + +def get_python_short_path(python_version=None): + if on_win: + return "python.exe" + if python_version and "." not in python_version: + python_version = ".".join(python_version) + return join("bin", "python%s" % (python_version or "")) + + +def get_python_site_packages_short_path(python_version): + if python_version is None: + return None + elif on_win: + return "Lib/site-packages" + else: + py_ver = get_major_minor_version(python_version) + return f"lib/python{py_ver}/site-packages" + + +_VERSION_REGEX = re.compile(r"[0-9]+\.[0-9]+") + + +def get_major_minor_version(string: str, with_dot=True) -> str: + # returns None if not found, otherwise two digits as a string + # should work for + # - 3.5.2 + # - 27 + # - bin/python2.7 + # - lib/python34/site-packages/ + # the last two are dangers because windows doesn't have version information there + if not isinstance(string, str): + raise TypeError("Argument must be a string.") + if string.startswith("lib/python"): + pythonstr = string.split("/")[1] + start = len("python") + if len(pythonstr) < start + 2: + return None + maj_min = pythonstr[start], pythonstr[start + 1 :] + elif string.startswith("bin/python"): + pythonstr = string.split("/")[1] + start = len("python") + if len(pythonstr) < start + 3: + return None + if not pythonstr[start + 1] == ".": + raise ValueError( + f"Unrecognized version component. Expected period at position {start + 1}." + ) + maj_min = pythonstr[start], pythonstr[start + 2 :] + else: + match = _VERSION_REGEX.match(string) + if match: + version = match.group(0).split(".") + maj_min = version[0], version[1] + else: + digits = "".join([c for c in string if c.isdigit()]) + if len(digits) < 2: + return None + maj_min = digits[0], digits[1:] + + return ".".join(maj_min) if with_dot else "".join(maj_min) + + +def get_python_noarch_target_path(source_short_path, target_site_packages_short_path): + if source_short_path.startswith("site-packages/"): + sp_dir = target_site_packages_short_path + return source_short_path.replace("site-packages", sp_dir, 1) + elif source_short_path.startswith("python-scripts/"): + from . import BIN_DIRECTORY + + return source_short_path.replace("python-scripts", BIN_DIRECTORY, 1) + else: + return source_short_path diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/path/windows.py b/miniconda3/lib/python3.13/site-packages/conda/common/path/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..51942299a8448cc480c6311b01e04faae6439345 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/path/windows.py @@ -0,0 +1,169 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common Windows path utilities.""" + +from __future__ import annotations + +import ntpath +import os +import posixpath +import re +import subprocess +from logging import getLogger +from pathlib import Path +from shutil import which +from typing import TYPE_CHECKING + +from ..compat import on_win +from ._cygpath import nt_to_posix, posix_to_nt, resolve_paths + +if TYPE_CHECKING: + from . import PathsType, PathType + +log = getLogger(__name__) + + +def win_path_ok(path): + return path.replace("/", "\\") if on_win else path + + +def win_path_double_escape(path): + return path.replace("\\", "\\\\") if on_win else path + + +def win_path_backout(path): + # replace all backslashes except those escaping spaces + # if we pass a file url, something like file://\\unc\path\on\win, make sure + # we clean that up too + return re.sub(r"(\\(?! ))", r"/", path).replace(":////", "://") + + +def _path_to( + paths: PathType | PathsType | None, + prefix: PathType | None = None, + *, + cygdrive: bool, + to_unix: bool, +) -> str | tuple[str, ...] | None: + if paths is None: + return None + + # short-circuit if we don't get any paths + paths = paths if isinstance(paths, (str, os.PathLike)) else tuple(paths) + if not paths: + return "." if isinstance(paths, (str, os.PathLike)) else () + + if on_win and prefix is None: + from ...base.context import context + + prefix = context.target_prefix + + if to_unix: + from_pathsep = ntpath.pathsep + cygpath_arg = "--unix" + cygpath_fallback = nt_to_posix + to_pathsep = posixpath.pathsep + to_sep = posixpath.sep + else: + from_pathsep = posixpath.pathsep + cygpath_arg = "--windows" + cygpath_fallback = posix_to_nt + to_pathsep = ntpath.pathsep + to_sep = ntpath.sep + + # It is very easy to end up with a bash in one place and a cygpath in another due to e.g. + # using upstream MSYS2 bash, but with a conda env that does not have bash but does have + # cygpath. When this happens, we have two different virtual POSIX machines, rooted at + # different points in the Windows filesystem. We do our path conversions with one and + # expect the results to work with the other. It does not. + + # TODO: search prefix for cygpath instead of deriving it from bash + bash = which("bash") + cygpath = str(Path(bash).parent / "cygpath") if bash else "cygpath" + joined = ( + str(paths) + if isinstance(paths, (str, os.PathLike)) + else from_pathsep.join(map(str, paths)) + ) + + converted: str | None = None + try: + # if present, use cygpath to convert paths since its more reliable + converted = subprocess.run( + [cygpath, cygpath_arg, "--path", joined], + text=True, + capture_output=True, + check=True, + ).stdout.strip() + except FileNotFoundError: + # FileNotFoundError: cygpath not available, happens when conda is installed without anything else + log.warning("cygpath is not available, fallback to manual path conversion") + except subprocess.CalledProcessError as err: + # CalledProcessError: cygpath failed for some reason + log.error( + "Unexpected cygpath error, fallback to manual path conversion\n %s: %s\n stdout: %s\n stderr: %s", + err.__class__.__name__, + err, + err.stdout.strip(), + err.stderr.strip(), + ) + except Exception as err: + # Exception: unexpected error + log.error( + "Unexpected cygpath error, fallback to manual path conversion\n %s: %s", + err.__class__.__name__, + err, + ) + else: + # cygpath doesn't always remove duplicate path seps + converted = resolve_paths(converted, to_pathsep, to_sep) + + if converted is None: + converted = cygpath_fallback(joined, prefix, cygdrive) + + if isinstance(paths, (str, os.PathLike)): + return converted + elif not converted: + return () + else: + return tuple(converted.split(to_pathsep)) + + +def win_path_to_unix( + paths: PathType | PathsType | None, + prefix: PathType | None = None, + *, + cygdrive: bool = False, +) -> str | tuple[str, ...] | None: + """Convert Windows paths to Unix paths. + + .. note:: + Produces unexpected results when run on Unix. + + Args: + paths: The path(s) to convert. + prefix: The (Windows path-style) prefix directory to use for the conversion. + If not provided, no checks for prefix paths will be made. + cygdrive: Whether to use the Cygwin-style drive prefix. + """ + return _path_to(paths, prefix=prefix, cygdrive=cygdrive, to_unix=True) + + +def unix_path_to_win( + paths: PathType | PathsType | None, + prefix: PathType | None = None, + *, + cygdrive: bool = False, +) -> str | tuple[str, ...] | None: + """Convert Unix paths to Windows paths. + + .. note:: + Produces unexpected results when run on Unix. + + Args: + paths: The path(s) to convert. + prefix: The (Windows path-style) prefix directory to use for the conversion. + If not provided, no checks for prefix paths will be made. + cygdrive: Unused. Present to keep the signature consistent with `win_path_to_unix`. + """ + return _path_to(paths, prefix, cygdrive=cygdrive, to_unix=False) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/pkg_formats/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/common/pkg_formats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e265393bdbaeb36d2f73fb8556612ad8267de270 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/pkg_formats/__init__.py @@ -0,0 +1,6 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause + +from ...deprecations import deprecated + +deprecated.module("25.9", "26.3", addendum="Use 'prefix_data_loaders' hook instead") diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/pkg_formats/python.py b/miniconda3/lib/python3.13/site-packages/conda/common/pkg_formats/python.py new file mode 100644 index 0000000000000000000000000000000000000000..19e616c85c6254f703eb84dd51de5fdee29e2073 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/pkg_formats/python.py @@ -0,0 +1,46 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common Python package format utilities.""" + +from ...deprecations import deprecated +from ...plugins.prefix_data_loaders.pypi.pkg_format import ( # noqa + AND, + COMPARE_OP, + DEFAULT_MARKER_CONTEXT, + IDENTIFIER, + MARKER_OP, + NON_SPACE, + OR, + PARTIAL_PYPI_SPEC_PATTERN, + PY_FILE_RE, + PYPI_CONDA_DEPS, + PYPI_TO_CONDA, + STRING_CHUNK, + VERSION_IDENTIFIER, + Evaluator, + MetadataWarning, + PySpec, + PythonDistribution, + PythonDistributionMetadata, + PythonEggInfoDistribution, + PythonEggLinkDistribution, + PythonInstalledDistribution, + _is_literal, + evaluator, + get_default_marker_context, + get_dist_file_from_egg_link, + get_site_packages_anchor_files, + interpret, + norm_package_name, + norm_package_version, + parse_marker, + parse_specification, + pypi_name_to_conda_name, + split_spec, +) + +deprecated.module( + "25.9", + "26.3", + addendum="Use 'conda.plugins.prefix_data_loaders.pypi.pkg_format' hook instead", +) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/serialize/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/common/serialize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b2268f39dff274080913a0a2bc1de4a9f23a121 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/serialize/__init__.py @@ -0,0 +1,121 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""YAML and JSON serialization and deserialization functions.""" + +import functools +from io import StringIO +from logging import getLogger + +from ...deprecations import deprecated +from .json import CondaJSONEncoder, loads + +log = getLogger(__name__) + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.common.serialize.yaml._yaml()` instead.", +) +@functools.cache +def _yaml_round_trip(): + import ruamel.yaml as yaml + + parser = yaml.YAML(typ="rt") + parser.indent(mapping=2, offset=2, sequence=4) + return parser + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.common.serialize.yaml._yaml()` instead.", +) +@functools.cache +def _yaml_safe(): + import ruamel.yaml as yaml + + parser = yaml.YAML(typ="safe", pure=True) + parser.indent(mapping=2, offset=2, sequence=4) + parser.default_flow_style = False + parser.sort_base_mapping_type_on_output = False + return parser + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.common.serialize.yaml.load()` instead.", +) +def yaml_round_trip_load(string): + return _yaml_round_trip().load(string) + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.common.serialize.yaml.load()` instead.", +) +def yaml_safe_load(string): + """ + Examples: + >>> yaml_safe_load("key: value") + {'key': 'value'} + + """ + return _yaml_safe().load(string) + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.common.serialize.yaml.dump()` instead.", +) +def yaml_round_trip_dump(object, stream=None): + """Dump object to string or stream.""" + ostream = stream or StringIO() + _yaml_round_trip().dump(object, ostream) + if not stream: + return ostream.getvalue() + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.common.serialize.yaml.dump()` instead.", +) +def yaml_safe_dump(object, stream=None): + """Dump object to string or stream.""" + ostream = stream or StringIO() + _yaml_safe().dump(object, ostream) + if not stream: + return ostream.getvalue() + + +deprecated.constant( + "26.3", + "26.9", + "EntityEncoder", + CondaJSONEncoder, + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", +) +del CondaJSONEncoder +deprecated.constant( + "26.3", + "26.9", + "json_load", + loads, + addendum="Use `conda.common.serialize.json.loads(sort_keys=True)` instead.", +) +del loads + + +@deprecated( + "26.3", + "26.9", + addendum="Use `conda.common.serialize.json.dumps(sort_keys=True)` instead.", +) +def json_dump(object): + from .json import dumps + + return dumps(object, sort_keys=True) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/serialize/json.py b/miniconda3/lib/python3.13/site-packages/conda/common/serialize/json.py new file mode 100644 index 0000000000000000000000000000000000000000..29ab4e0b0c6f18cdd131db2bce34c93f98752203 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/serialize/json.py @@ -0,0 +1,124 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""JSON serialization utilities for conda.""" + +from __future__ import annotations + +from enum import Enum +from pathlib import Path +from typing import TYPE_CHECKING, overload + +from frozendict import frozendict + +# detect the best json library to use +from requests.compat import json + +if TYPE_CHECKING: + from io import IO + from typing import Any + + from ..path import PathType + + +class CondaJSONEncoder(json.JSONEncoder): + def default(self, obj: Any) -> Any: + # immutable types + + if isinstance(obj, frozendict): + return dict(obj) + + # Python types + if isinstance(obj, Enum): + return obj.value + elif isinstance(obj, Path): + return str(obj) + + # auxlib entity types + for attr in ("dump", "__json__", "to_json", "as_json"): + if method := getattr(obj, attr, None): + return method() + + # default + return super().default(obj) + + +@overload +def write(obj: Any, *, fp: IO[str], **kwargs) -> None: ... + + +@overload +def write(obj: Any, *, path: PathType, **kwargs) -> None: ... + + +@overload +def write(obj: Any, **kwargs) -> str: ... + + +def write( + obj: Any, *, fp: IO[str] | None = None, path: PathType | None = None, **kwargs +) -> None | str: + if fp and path: + raise ValueError("At most one of fp or path must be provided") + + kwargs.setdefault("cls", CondaJSONEncoder) + kwargs.setdefault("indent", 2) + + if fp is not None: + json.dump(obj, fp, **kwargs) + return None + else: + text = json.dumps(obj, **kwargs) + if path is not None: + Path(path).write_text(text) + return None + else: + return text + + +def dump(obj: Any, fp: IO[str], **kwargs) -> None: + write(obj, fp=fp, **kwargs) + + +def dumps(obj: Any, **kwargs) -> str: + return write(obj, **kwargs) + + +@overload +def read(*, text: str, **kwargs) -> Any: ... + + +@overload +def read(*, fp: IO[str], **kwargs) -> Any: ... + + +@overload +def read(*, path: PathType, **kwargs) -> Any: ... + + +def read( + *, + text: str | None = None, + fp: IO[str] | None = None, + path: PathType | None = None, + **kwargs, +) -> Any: + if (text, fp, path).count(None) != 2: + raise ValueError("Exactly one of text, fp or path must be provided") + + if fp is not None: + return json.load(fp, **kwargs) + elif path is not None: + return json.loads(Path(path).read_text(), **kwargs) + else: + return json.loads(text, **kwargs) + + +def load(fp: IO[str], **kwargs) -> Any: + return read(fp=fp, **kwargs) + + +def loads(s: str, **kwargs) -> Any: + return read(text=s, **kwargs) + + +JSONDecodeError = json.JSONDecodeError diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/serialize/yaml.py b/miniconda3/lib/python3.13/site-packages/conda/common/serialize/yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..98383ce0afcdb0f2d3dce678608b19eaafe38eaf --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/serialize/yaml.py @@ -0,0 +1,127 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""YAML serialization utilities for conda.""" + +from __future__ import annotations + +from enum import Enum +from functools import cache +from io import StringIO +from pathlib import Path +from typing import TYPE_CHECKING, overload + +import ruamel.yaml + +if TYPE_CHECKING: + from io import IO + from typing import Any + + from ..path import PathType + + +class CondaYAMLRepresenter(ruamel.yaml.representer.RoundTripRepresenter): + def default(self, data: Any) -> Any: + # Python types + if isinstance(data, Enum): + return self.represent_str(data.value) + elif isinstance(data, Path): + return self.represent_str(str(data)) + + # auxlib entity types + for attr in ("dump", "__json__", "to_json", "as_json"): + if method := getattr(data, attr, None): + return self.represent_data(method()) + + # mirror JSON behavior + raise TypeError( + f"Object of type {data.__class__.__name__} is not YAML serializable" + ) + + +CondaYAMLRepresenter.add_representer(None, CondaYAMLRepresenter.default) + + +@cache +def _yaml() -> ruamel.yaml.YAML: + parser = ruamel.yaml.YAML(typ="rt") + parser.Representer = CondaYAMLRepresenter + parser.indent(mapping=2, offset=2, sequence=4) + parser.default_flow_style = False + parser.sort_base_mapping_type_on_output = False + return parser + + +@overload +def write(obj: Any) -> str: ... + + +@overload +def write(obj: Any, *, fp: IO[str]) -> None: ... + + +@overload +def write(obj: Any, *, path: PathType) -> None: ... + + +def write( + obj: Any, *, fp: IO[str] | None = None, path: PathType | None = None +) -> None | str: + if fp and path: + raise ValueError("At most one of fp or path must be provided") + + if fp is not None: + _yaml().dump(obj, fp) + return None + else: + stream = StringIO() + _yaml().dump(obj, stream=stream) + text = stream.getvalue() + if path is not None: + Path(path).write_text(text) + return None + else: + return text + + +def dump(obj: Any, fp: IO[str]) -> None: + write(obj, fp=fp) + + +def dumps(obj: Any) -> str: + return write(obj) + + +@overload +def read(*, text: str) -> Any: ... + + +@overload +def read(*, fp: IO[str]) -> Any: ... + + +@overload +def read(*, path: PathType) -> Any: ... + + +def read( + *, text: str | None = None, fp: IO[str] | None = None, path: PathType | None = None +) -> Any: + if (text, fp, path).count(None) != 2: + raise ValueError("Exactly one of text, fp or path must be provided") + + if fp is not None: + text = fp.read() + elif path is not None: + text = Path(path).read_text() + return _yaml().load(text) + + +def load(fp: IO[str]) -> Any: + return read(fp=fp) + + +def loads(s: str) -> Any: + return read(text=s) + + +YAMLError = ruamel.yaml.YAMLError diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/signals.py b/miniconda3/lib/python3.13/site-packages/conda/common/signals.py new file mode 100644 index 0000000000000000000000000000000000000000..696a827853611de7519f86de1382fee909eebc9b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/signals.py @@ -0,0 +1,62 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Intercept signals and handle them gracefully.""" + +import signal +import threading +from contextlib import contextmanager +from logging import getLogger + +log = getLogger(__name__) + +INTERRUPT_SIGNALS = ( + "SIGABRT", + "SIGINT", + "SIGTERM", + "SIGQUIT", + "SIGBREAK", +) + + +def get_signal_name(signum): + """ + Examples: + >>> from signal import SIGINT + >>> get_signal_name(SIGINT) + 'SIGINT' + + """ + return next( + ( + k + for k, v in signal.__dict__.items() + if v == signum and k.startswith("SIG") and not k.startswith("SIG_") + ), + None, + ) + + +@contextmanager +def signal_handler(handler): + # TODO: test and fix windows + # https://danielkaes.wordpress.com/2009/06/04/how-to-catch-kill-events-with-python/ + _thread_local = threading.local() + _thread_local.previous_handlers = [] + for signame in INTERRUPT_SIGNALS: + sig = getattr(signal, signame, None) + if sig: + log.debug("registering handler for %s", signame) + try: + prev_handler = signal.signal(sig, handler) + _thread_local.previous_handlers.append((sig, prev_handler)) + except ValueError as e: # pragma: no cover + # ValueError: signal only works in main thread + log.debug("%r", e) + try: + yield + finally: + standard_handlers = signal.SIG_IGN, signal.SIG_DFL + for sig, previous_handler in _thread_local.previous_handlers: + if callable(previous_handler) or previous_handler in standard_handlers: + log.debug("de-registering handler for %s", sig) + signal.signal(sig, previous_handler) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/toposort.py b/miniconda3/lib/python3.13/site-packages/conda/common/toposort.py new file mode 100644 index 0000000000000000000000000000000000000000..20c9994ee0c010140a46127795f1c76be0a1e2c3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/toposort.py @@ -0,0 +1,112 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Topological sorting implementation.""" + +from functools import reduce as _reduce +from logging import getLogger + +log = getLogger(__name__) + + +def _toposort(data): + """Dependencies are expressed as a dictionary whose keys are items + and whose values are a set of dependent items. Output is a list of + sets in topological order. The first set consists of items with no + dependences, each subsequent set consists of items that depend upon + items in the preceding sets. + """ + # Special case empty input. + if len(data) == 0: + return + + # Ignore self dependencies. + for k, v in data.items(): + v.discard(k) + # Find all items that don't depend on anything. + extra_items_in_deps = _reduce(set.union, data.values()) - set(data.keys()) + # Add empty dependences where needed. + data.update({item: set() for item in extra_items_in_deps}) + while True: + ordered = sorted({item for item, dep in data.items() if len(dep) == 0}) + if not ordered: + break + + for item in ordered: + yield item + data.pop(item, None) + + for dep in sorted(data.values()): + dep -= set(ordered) + + if len(data) != 0: + from ..exceptions import CondaValueError + + msg = "Cyclic dependencies exist among these items: {}" + raise CondaValueError(msg.format(" -> ".join(repr(x) for x in data.keys()))) + + +def pop_key(data): + """ + Pop an item from the graph that has the fewest dependencies in the case of a tie + The winners will be sorted alphabetically + """ + items = sorted(data.items(), key=lambda item: (len(item[1]), item[0])) + key = items[0][0] + + data.pop(key) + + for dep in data.values(): + dep.discard(key) + + return key + + +def _safe_toposort(data): + """Dependencies are expressed as a dictionary whose keys are items + and whose values are a set of dependent items. Output is a list of + sets in topological order. The first set consists of items with no + dependencies, each subsequent set consists of items that depend upon + items in the preceding sets. + """ + # Special case empty input. + if len(data) == 0: + return + + t = _toposort(data) + + while True: + try: + value = next(t) + yield value + except ValueError as err: + log.debug(err.args[0]) + + if not data: + return # pragma: nocover + + yield pop_key(data) + + t = _toposort(data) + + continue + except StopIteration: + return + + +def toposort(data, safe=True): + data = {k: set(v) for k, v in data.items()} + + if "python" in data: + # Special case: Remove circular dependency between python and pip, + # to ensure python is always installed before anything that needs it. + # For more details: + # - https://github.com/conda/conda/issues/1152 + # - https://github.com/conda/conda/pull/1154 + # - https://github.com/conda/conda-build/issues/401 + # - https://github.com/conda/conda/pull/1614 + data["python"].discard("pip") + + if safe: + return list(_safe_toposort(data)) + else: + return list(_toposort(data)) diff --git a/miniconda3/lib/python3.13/site-packages/conda/common/url.py b/miniconda3/lib/python3.13/site-packages/conda/common/url.py new file mode 100644 index 0000000000000000000000000000000000000000..7648b996da456c55929bd43feeff0ebf7393c9a3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/common/url.py @@ -0,0 +1,525 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common URL utilities.""" + +from __future__ import annotations + +import codecs +import re +import socket +import struct +from collections import namedtuple +from functools import cache +from getpass import getpass +from os.path import abspath, expanduser +from typing import TYPE_CHECKING, NamedTuple +from urllib.parse import ( # noqa: F401 + quote, + quote_plus, + unquote, + unquote_plus, +) +from urllib.parse import urlparse as _urlparse +from urllib.parse import urlunparse as _urlunparse # noqa: F401 + +from ..deprecations import deprecated +from .compat import on_win +from .path import split_filename, strip_pkg_extension + +if TYPE_CHECKING: + from collections.abc import Iterable + from re import Pattern + from typing import Any, Self + from urllib.parse import ParseResult + + +@deprecated("25.9", "26.3", addendum="Use int(..., 16) instead.") +def hex_octal_to_int(ho: str) -> int: + ho = ord(ho.upper()) + o0 = ord("0") + o9 = ord("9") + oA = ord("A") + oF = ord("F") + res = ( + ho - o0 + if ho >= o0 and ho <= o9 + else (ho - oA + 10) + if ho >= oA and ho <= oF + else None + ) + return res + + +@cache +def percent_decode(path: str) -> str: + # This is not fast so avoid when we can. + if "%" not in path: + return path + ranges: list[tuple[int, int]] = [] + for m in re.finditer(r"(%[0-9A-F]{2})", path, flags=re.IGNORECASE): + ranges.append((m.start(), m.end())) + if not len(ranges): + return path + + # Sorry! Correctness is more important than speed at the moment. + # Should use a map + lambda eventually. + result = b"" + skips = 0 + for i, c in enumerate(path): + if skips > 0: + skips -= 1 + continue + c = c.encode("ascii") + emit = c + if c == b"%": + for r in ranges: + if i == r[0]: + emit = struct.pack("B", int(path[i + 1 : i + 3], 16)) + skips = 2 + break + if emit: + result += emit + return codecs.utf_8_decode(result)[0] + + +file_scheme = "file://" + +# Keeping this around for now, need to combine with the same function in conda/common/path.py +""" +def url_to_path(url): + assert url.startswith(file_scheme), "{} is not a file-scheme URL".format(url) + decoded = percent_decode(url[len(file_scheme):]) + if decoded.startswith('/') and decoded[2] == ':': + # A Windows path. + decoded.replace('/', '\\') + return decoded +""" + + +@cache +def path_to_url(path: str) -> str: + if not path: + raise ValueError(f"Not allowed: {path!r}") + if path.startswith(file_scheme): + try: + path.decode("ascii") + except UnicodeDecodeError: + raise ValueError( + f"Non-ascii not allowed for things claiming to be URLs: {path!r}" + ) + return path + path = abspath(expanduser(path)).replace("\\", "/") + # We do not use urljoin here because we want to take our own + # *very* explicit control of how paths get encoded into URLs. + # We should not follow any RFCs on how to encode and decode + # them, we just need to make sure we can represent them in a + # way that will not cause problems for whatever amount of + # urllib processing we *do* need to do on them (which should + # be none anyway, but I doubt that is the case). I have gone + # for ASCII and % encoding of everything not alphanumeric or + # not in `!'()*-._/:`. This should be pretty save. + # + # To avoid risking breaking the internet, this code only runs + # for `file://` URLs. + # + percent_encode_chars = "!'()*-._/\\:" + percent_encode = lambda s: "".join( + [f"%{ord(c):02X}", c][c < "{" and c.isalnum() or c in percent_encode_chars] + for c in s + ) + if any(ord(char) >= 128 for char in path): + path = percent_encode( + path.decode("unicode-escape") + if hasattr(path, "decode") + else bytes(path, "utf-8").decode("unicode-escape") + ) + + # https://blogs.msdn.microsoft.com/ie/2006/12/06/file-uris-in-windows/ + if len(path) > 1 and path[1] == ":": + path = file_scheme + "/" + path + else: + path = file_scheme + path + return path + + +url_attrs = ( + "scheme", + "path", + "query", + "fragment", + "username", + "password", + "hostname", + "port", +) + + +class Url(namedtuple("Url", url_attrs)): + """ + Object used to represent a Url. The string representation of this object is a url string. + + This object was inspired by the urllib3 implementation as it gives you a way to construct + URLs from various parts. The motivation behind this object was making something that is + interoperable with built the `urllib.parse.urlparse` function and has more features than + the built-in `ParseResult` object. + """ + + def __new__( + cls, + scheme: str | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + username: str | None = None, + password: str | None = None, + hostname: str | None = None, + port: str | None = None, + ): + if path and not path.startswith("/"): + path = "/" + path + if scheme: + scheme = scheme.lower() + if hostname: + hostname = hostname.lower() + return super().__new__( + cls, scheme, path, query, fragment, username, password, hostname, port + ) + + @property + def auth(self) -> str | None: + if self.username and self.password: + return f"{self.username}:{self.password}" + elif self.username: + return self.username + + @property + def netloc(self) -> str | None: + if self.port: + return f"{self.hostname}:{self.port}" + return self.hostname + + def __str__(self) -> str: + scheme, path, query, fragment, username, password, hostname, port = self + url = "" + + if scheme: + url += f"{scheme}://" + if password and username: + url += f"{username}:{password}@" + if hostname: + url += hostname + if port: + url += f":{port}" + if path: + url += path + if query: + url += f"?{query}" + if fragment: + url += f"#{fragment}" + + return url + + def as_dict(self) -> dict[str, str | None]: + """Provide a public interface for namedtuple's _asdict""" + return self._asdict() + + def replace(self, **kwargs) -> Self: + """Provide a public interface for namedtuple's _replace""" + return self._replace(**kwargs) + + @classmethod + def from_parse_result(cls, parse_result: ParseResult) -> Self: + values = {fld: getattr(parse_result, fld, "") for fld in url_attrs} + return cls(**values) + + +@cache +def urlparse(url: str) -> Url: + if on_win and url.startswith("file:"): + url.replace("\\", "/") + # Allows us to pass in strings like 'example.com:8080/path/1'. + if not has_scheme(url): + url = "//" + url + return Url.from_parse_result(_urlparse(url)) + + +def url_to_s3_info(url: str) -> tuple[str, str]: + """Convert an s3 url to a tuple of bucket and key. + + Examples: + >>> url_to_s3_info("s3://bucket-name.bucket/here/is/the/key") + ('bucket-name.bucket', '/here/is/the/key') + """ + parsed_url = urlparse(url) + if parsed_url.scheme != "s3": + raise ValueError(f"You can only use s3: urls (not {url!r})") + bucket, key = parsed_url.hostname, parsed_url.path + return bucket, key + + +def is_url(url: Any) -> bool: + """ + Examples: + >>> is_url(None) + False + >>> is_url("s3://some/bucket") + True + """ + if not url: + return False + try: + return urlparse(url).scheme != "" + except ValueError: + return False + + +def is_ipv4_address(string_ip: str) -> bool: + """ + Examples: + >>> [is_ipv4_address(ip) for ip in ('8.8.8.8', '192.168.10.10', '255.255.255.255')] + [True, True, True] + >>> [is_ipv4_address(ip) for ip in ('8.8.8', '192.168.10.10.20', '256.255.255.255', '::1')] + [False, False, False, False] + """ + try: + socket.inet_aton(string_ip) + except OSError: + return False + return string_ip.count(".") == 3 + + +def is_ipv6_address(string_ip: str) -> bool: + """ + Examples: + >> [is_ipv6_address(ip) for ip in ('::1', '2001:db8:85a3::370:7334', '1234:'*7+'1234')] + [True, True, True] + >> [is_ipv6_address(ip) for ip in ('192.168.10.10', '1234:'*8+'1234')] + [False, False] + """ + try: + socket.inet_pton(socket.AF_INET6, string_ip) + except OSError: + return False + return True + + +def is_ip_address(string_ip: str) -> bool: + """ + Examples: + >> is_ip_address('192.168.10.10') + True + >> is_ip_address('::1') + True + >> is_ip_address('www.google.com') + False + """ + return is_ipv4_address(string_ip) or is_ipv6_address(string_ip) + + +def join(*args: str): + start = "/" if not args[0] or args[0].startswith("/") else "" + return start + "/".join(y for y in (x.strip("/") for x in args if x) if y) + + +join_url = join + + +def has_scheme(value: str) -> bool: + return re.match(r"[a-z][a-z0-9]{0,11}://", value) + + +def strip_scheme(url: str) -> str: + """ + Examples: + >>> strip_scheme("https://www.conda.io") + 'www.conda.io' + >>> strip_scheme("s3://some.bucket/plus/a/path.ext") + 'some.bucket/plus/a/path.ext' + """ + return url.split("://", 1)[-1] + + +def mask_anaconda_token(url: str) -> str: + _, token = split_anaconda_token(url) + return url.replace(token, "", 1) if token else url + + +def split_anaconda_token(url: str): + """ + Examples: + >>> split_anaconda_token("https://1.2.3.4/t/tk-123-456/path") + (u'https://1.2.3.4/path', u'tk-123-456') + >>> split_anaconda_token("https://1.2.3.4/t//path") + (u'https://1.2.3.4/path', u'') + >>> split_anaconda_token("https://some.domain/api/t/tk-123-456/path") + (u'https://some.domain/api/path', u'tk-123-456') + >>> split_anaconda_token("https://1.2.3.4/conda/t/tk-123-456/path") + (u'https://1.2.3.4/conda/path', u'tk-123-456') + >>> split_anaconda_token("https://1.2.3.4/path") + (u'https://1.2.3.4/path', None) + >>> split_anaconda_token("https://10.2.3.4:8080/conda/t/tk-123-45") + (u'https://10.2.3.4:8080/conda', u'tk-123-45') + """ + _token_match = re.search(r"/t/([a-zA-Z0-9-]*)", url) + token = _token_match.groups()[0] if _token_match else None + cleaned_url = url.replace("/t/" + token, "", 1) if token is not None else url + return cleaned_url.rstrip("/"), token + + +def split_platform(known_subdirs: Iterable[str], url: str) -> tuple[str, str]: + """ + + Examples: + >>> from conda.base.constants import KNOWN_SUBDIRS + >>> split_platform(KNOWN_SUBDIRS, "https://1.2.3.4/t/tk-123/linux-ppc64le/path") + (u'https://1.2.3.4/t/tk-123/path', u'linux-ppc64le') + + """ + _platform_match = _split_platform_re(known_subdirs).search(url) + platform = _platform_match.groups()[0] if _platform_match else None + cleaned_url = url.replace("/" + platform, "", 1) if platform is not None else url + return cleaned_url.rstrip("/"), platform + + +@cache +def _split_platform_re(known_subdirs: Iterable[str]) -> Pattern[str]: + _platform_match_regex = r"/({})(?:/|$)".format( + r"|".join(rf"{d}" for d in known_subdirs) + ) + return re.compile(_platform_match_regex, re.IGNORECASE) + + +def has_platform(url: str, known_subdirs: Iterable[str]) -> bool | None: + url_no_package_name, _ = split_filename(url) + if not url_no_package_name: + return None + maybe_a_platform = url_no_package_name.rsplit("/", 1)[-1] + return maybe_a_platform in known_subdirs and maybe_a_platform or None + + +def split_scheme_auth_token( + url: str, +) -> tuple[str | None, str | None, str | None, str | None]: + """ + Examples: + >>> split_scheme_auth_token("https://u:p@conda.io/t/x1029384756/more/path") + ('conda.io/more/path', 'https', 'u:p', 'x1029384756') + >>> split_scheme_auth_token(None) + (None, None, None, None) + """ + if not url: + return None, None, None, None + cleaned_url, token = split_anaconda_token(url) + url_parts = urlparse(cleaned_url) + remainder_url = Url( + hostname=url_parts.hostname, + port=url_parts.port, + path=url_parts.path, + query=url_parts.query, + ) + + return str(remainder_url), url_parts.scheme, url_parts.auth, token + + +class _SplitUrlParts(NamedTuple): + scheme: str | None + auth: str | None + token: str | None + platform: str | None + package_filename: str | None + hostname: str | None + port: str | None + path: str | None + query: str | None + + +def split_conda_url_easy_parts( + known_subdirs: Iterable[str], url: str +) -> _SplitUrlParts: + # scheme, auth, token, platform, package_filename, host, port, path, query + cleaned_url, token = split_anaconda_token(url) + cleaned_url, platform = split_platform(known_subdirs, cleaned_url) + _, ext = strip_pkg_extension(cleaned_url) + cleaned_url, package_filename = ( + cleaned_url.rsplit("/", 1) + if ext and "/" in cleaned_url + else (cleaned_url, None) + ) + + # TODO: split out namespace using regex + url_parts = urlparse(cleaned_url) + + return _SplitUrlParts( + url_parts.scheme, + url_parts.auth, + token, + platform, + package_filename, + url_parts.hostname, + url_parts.port, + url_parts.path, + url_parts.query, + ) + + +@cache +def get_proxy_username_and_pass(scheme: str) -> tuple[str, str]: + username = input(f"\n{scheme} proxy username: ") + passwd = getpass("Password: ") + return username, passwd + + +def add_username_and_password(url: str, username: str, password: str) -> str: + """ + Inserts `username` and `password` into provided `url` + + >>> add_username_and_password('https://anaconda.org', 'TestUser', 'Password') + 'https://TestUser:Password@anaconda.org' + """ + url = urlparse(url) + url_with_auth = url.replace(username=username, password=quote(password, safe="")) + return str(url_with_auth) + + +def maybe_add_auth(url: str, auth: str, force: bool = False) -> str: + """Add auth if the url doesn't currently have it. + + By default, does not replace auth if it already exists. Setting ``force`` to ``True`` + overrides this behavior. + + Examples: + >>> maybe_add_auth("https://www.conda.io", "user:passwd") + 'https://user:passwd@www.conda.io' + >>> maybe_add_auth("https://www.conda.io", "") + 'https://www.conda.io' + """ + if not auth: + return url + + url_parts = urlparse(url) + if url_parts.username and url_parts.password and not force: + return url + + auth_parts = auth.split(":") + if len(auth_parts) > 1: + url_parts = url_parts.replace(username=auth_parts[0], password=auth_parts[1]) + + return str(url_parts) + + +def maybe_unquote(url: str) -> str: + return unquote_plus(remove_auth(url)) if url else url + + +def remove_auth(url: str) -> str: + """Remove embedded authentication from URL. + + .. code-block:: pycon + + >>> remove_auth("https://user:password@anaconda.com") + 'https://anaconda.com' + """ + url = urlparse(url) + url_no_auth = url.replace(username="", password="") + + return str(url_no_auth) diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed2e43f79ce73ceb0e7e350e4b02496ee3fd4d4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/__init__.py @@ -0,0 +1,23 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Code in ``conda.core`` is the core logic. It is strictly forbidden from having side effects. +No printing to stdout or stderr, no disk manipulation, no http requests. +All side effects should be implemented through ``conda.gateways``. Objects defined in +``conda.models`` should be heavily preferred for ``conda.core`` function/method arguments +and return values. + +Conda modules importable from ``conda.core`` are + +- ``conda.common`` +- ``conda.core`` +- ``conda.models`` +- ``conda.gateways`` + +Conda modules strictly off limits for import within ``conda.core`` are + +- ``conda.api`` +- ``conda.cli`` +- ``conda.client`` + +""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/envs_manager.py b/miniconda3/lib/python3.13/site-packages/conda/core/envs_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c1162e5452894ed7f09f4cc7d2ece2c04ecec4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/envs_manager.py @@ -0,0 +1,226 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools for managing conda environments.""" + +from __future__ import annotations + +import os +from errno import EACCES, ENOENT, EROFS +from logging import getLogger +from os.path import dirname, isdir, isfile, join, normpath +from typing import TYPE_CHECKING + +from ..base.context import context +from ..common._os import is_admin +from ..common.compat import ensure_text_type, on_win, open_utf8 +from ..common.path import expand +from ..gateways.disk.read import yield_lines +from .prefix_data import PrefixData + +if TYPE_CHECKING: + from collections.abc import Iterator + +log = getLogger(__name__) + + +def get_user_environments_txt_file(userhome: str = "~") -> str: + """ + Gets the path to the user's environments.txt file. + + :param userhome: The home directory of the user. + :type userhome: str + :return: Path to the environments.txt file. + :rtype: str + """ + return expand(join(userhome, ".conda", "environments.txt")) + + +def register_env(location: str) -> None: + """ + Registers an environment by adding it to environments.txt file. + + :param location: The file path of the environment to register. + :type location: str + :return: None + """ + if not context.register_envs: + return + + user_environments_txt_file = get_user_environments_txt_file() + location = normpath(location) + folder = dirname(location) + try: + os.makedirs(folder) + except: + pass + + if ( + "placehold_pl" in location + or "skeleton_" in location + or user_environments_txt_file == os.devnull + ): + # Don't record envs created by conda-build. + return + + if location in yield_lines(user_environments_txt_file): + # Nothing to do. Location is already recorded in a known environments.txt file. + return + + user_environments_txt_directory = os.path.dirname(user_environments_txt_file) + try: + os.makedirs(user_environments_txt_directory, exist_ok=True) + except OSError as exc: + log.warning( + "Unable to register environment. " + f"Could not create {user_environments_txt_directory}. " + f"Reason: {exc}" + ) + return + + try: + with open_utf8(user_environments_txt_file, "a") as fh: + fh.write(ensure_text_type(location)) + fh.write("\n") + except OSError as e: + if e.errno in (EACCES, EROFS, ENOENT): + log.warning( + "Unable to register environment. Path not writable or missing.\n" + " environment location: %s\n" + " registry file: %s", + location, + user_environments_txt_file, + ) + else: + raise + + +def unregister_env(location: str) -> None: + """ + Unregisters an environment by removing its entry from the environments.txt file if certain conditions are met. + + The environment is only unregistered if its associated 'conda-meta' directory exists and contains no significant files other than 'history'. If these conditions are met, the environment's path is removed from environments.txt. + + :param location: The file path of the environment to unregister. + :type location: str + :return: None + """ + if isdir(location): + meta_dir = join(location, "conda-meta") + if isdir(meta_dir): + meta_dir_contents = tuple(entry.name for entry in os.scandir(meta_dir)) + if len(meta_dir_contents) > 1: + # if there are any files left other than 'conda-meta/history' + # then don't unregister + return + + _clean_environments_txt(get_user_environments_txt_file(), location) + + +def list_all_known_prefixes() -> list[str]: + """ + Lists all known conda environment prefixes. + + :return: A list of all known conda environment prefixes. + :rtype: List[str] + """ + all_env_paths = set() + # If the user is an admin, load environments from all user home directories + if is_admin(): + if on_win: + home_dir_dir = dirname(expand("~")) + search_dirs = tuple(entry.path for entry in os.scandir(home_dir_dir)) + else: + from pwd import getpwall + + search_dirs = tuple(pwentry.pw_dir for pwentry in getpwall()) or ( + expand("~"), + ) + else: + search_dirs = (expand("~"),) + for home_dir in filter(None, search_dirs): + environments_txt_file = get_user_environments_txt_file(home_dir) + if isfile(environments_txt_file): + try: + # When the user is an admin, some environments.txt files might + # not be readable (if on network file system for example) + all_env_paths.update(_clean_environments_txt(environments_txt_file)) + except PermissionError: + log.warning(f"Unable to access {environments_txt_file}") + + # in case environments.txt files aren't complete, also add all known conda environments in + # all envs_dirs + envs_dirs = (envs_dir for envs_dir in context.envs_dirs if isdir(envs_dir)) + all_env_paths.update( + path + for path in ( + entry.path for envs_dir in envs_dirs for entry in os.scandir(envs_dir) + ) + if path not in all_env_paths and PrefixData(path).is_environment() + ) + + all_env_paths.add(context.root_prefix) + return sorted(all_env_paths) + + +def query_all_prefixes(spec: str) -> Iterator[tuple[str, tuple]]: + """ + Queries all known prefixes for a given specification. + + :param spec: The specification to query for. + :type spec: str + :return: An iterator of tuples containing the prefix and the query results. + :rtype: Iterator[Tuple[str, Tuple]] + """ + for prefix in list_all_known_prefixes(): + prefix_recs = tuple(PrefixData(prefix).query(spec)) + if prefix_recs: + yield prefix, prefix_recs + + +def _clean_environments_txt( + environments_txt_file: str, + remove_location: str | None = None, +) -> tuple[str, ...]: + """ + Cleans the environments.txt file by removing specified locations. + + :param environments_txt_file: The file path of environments.txt. + :param remove_location: Optional location to remove from the file. + :type environments_txt_file: str + :type remove_location: Optional[str] + :return: A tuple of the cleaned lines. + :rtype: Tuple[str, ...] + """ + if not isfile(environments_txt_file): + return () + + if remove_location: + remove_location = normpath(remove_location) + environments_txt_lines = tuple(yield_lines(environments_txt_file)) + environments_txt_lines_cleaned = tuple( + prefix + for prefix in environments_txt_lines + if prefix != remove_location and PrefixData(prefix).is_environment() + ) + if environments_txt_lines_cleaned != environments_txt_lines: + _rewrite_environments_txt(environments_txt_file, environments_txt_lines_cleaned) + return environments_txt_lines_cleaned + + +def _rewrite_environments_txt(environments_txt_file: str, prefixes: list[str]) -> None: + """ + Rewrites the environments.txt file with the specified prefixes. + + :param environments_txt_file: The file path of environments.txt. + :param prefixes: List of prefixes to write into the file. + :type environments_txt_file: str + :type prefixes: List[str] + :return: None + """ + try: + with open_utf8(environments_txt_file, "w") as fh: + fh.write("\n".join(prefixes)) + fh.write("\n") + except OSError as e: + log.info("File not cleaned: %s", environments_txt_file) + log.debug("%r", e, exc_info=True) diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/index.py b/miniconda3/lib/python3.13/site-packages/conda/core/index.py new file mode 100644 index 0000000000000000000000000000000000000000..50dcefe8188a5f8251e78cf8ca06083fa0bab7c2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/index.py @@ -0,0 +1,682 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools for fetching the current index.""" + +from __future__ import annotations + +from collections import UserDict +from logging import getLogger +from typing import TYPE_CHECKING + +from boltons.setutils import IndexedSet + +from ..base.context import context, validate_channels +from ..deprecations import deprecated +from ..exceptions import ( + CondaKeyError, + InvalidSpec, + PackagesNotFoundError, +) +from ..models.channel import Channel, all_channel_urls +from ..models.match_spec import MatchSpec +from ..models.records import EMPTY_LINK, PackageCacheRecord, PackageRecord, PrefixRecord +from .package_cache_data import PackageCacheData +from .prefix_data import PrefixData +from .subdir_data import SubdirData + +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import Any, Self + + from ..common.path import PathType + + +log = getLogger(__name__) + +LAST_CHANNEL_URLS = [] + + +@deprecated( + "25.9", + "26.3", + addendum="Use `conda.base.context.validate_channels` instead.", +) +def check_allowlist(channel_urls: list[str]) -> None: + """ + Check if the given channel URLs are allowed by the context's allowlist. + :param channel_urls: A list of channel URLs to check against the allowlist. + :raises ChannelNotAllowed: If any URL is not in the allowlist. + :raises ChannelDenied: If any URL is in the denylist. + """ + validate_channels(channel_urls) + + +class Index(UserDict): + """The ``Index`` provides information about available packages from all relevant sources. + + There are four types of sources for package information, namely + + Channels + represent packages available from standard sources identified with a url, mostly online, + but can also be on a local filesystem using the ``file://`` scheme. + Programatically, channels are represented by :class:`conda.models.channel.Channel`, their data + is fetched using :class:`conda.core.subdir_data.SubdirData`. + + For more information see :ref:`concepts-channels`. + + Individual packages from channels are usually represented by :class:`conda.models.records.PackageRecord`. + + Prefix + represents packages that are already installed. Every :class:`Index` can be associated + with exactly one Prefix, which is the location of one of the conda :ref:`concepts-conda-environments`. + The package information about the installed packages is represented by :class:`conda.core.prefix_data.PrefixData`. + + Individual packages from prefixes are usually represented by :class:`conda.models.records.PrefixRecord`. + + Package Cache + represents packages that are locally unpacked, but may not be installed in the environment + associated with this index. These are usually packages that have been installed in any environment + of the local conda installation, but may have been removed from all environments by now. + + Individual packages from the package are usually represented by :class:`conda.models.records.PackageCacheRecord`. + + Virtual Packages + represent properties of the system, not actual conda packages in the normal sense. These are, + for example, system packages that inform the solver about the operating system in use, or + track features that can be used to steer package priority. + + Individual virtual packages are represented by special :class:`conda.models.records.PackageRecord`, + see :meth:`conda.models.records.PackageRecord.virtual_package` and + :meth:`conda.models.records.PackageRecord.feature`. + """ + + def __init__( + self, + channels: Iterable[str | Channel] = (), + prepend: bool = True, + platform: str | None = None, + subdirs: tuple[str, ...] | None = None, + use_local: bool = False, + use_cache: bool | None = None, + prefix: PathType | PrefixData | None = None, + repodata_fn: str | None = context.repodata_fns[-1], + use_system: bool = False, + ) -> None: + """Initializes a new index with the desired components. + + Args: + channels: channels identified by canonical names or URLS or Channel objects; + for more details, see :meth:`conda.models.channel.Channel.from_value` + prepend: if ``True`` (default), add configured channel with higher priority than passed channels; + if ``False``, do *not* add configured channels. + platform: see ``subdirs``. + subdirs: platform and subdirs determine the selection of subdirs in the channels; + if both are ``None``, subdirs is taken from the configuration; + if both are given, ``subdirs`` takes precedence and ``platform`` is ignored; + if only ``platform`` is given, subdirs will be ``(platform, "noarch")``; + if ``subdirs`` is given, subdirs will be ``subdirs``. + use_local: if ``True``, add the special "local" channel for locally built packages with lowest priority. + use_cache: if ``True``, add packages from the package cache. + prefix: associate prefix with this index and add its packages. + repodata_fn: filename of the repodata, default taken from config, almost always "repodata.json". + use_system: if ``True``, add system packages, that is virtual packages defined by plugins, usually used + to make intrinsic information about the system, such as cpu architecture or operating system, available + to the solver. + """ + channels = list(channels) + if use_local: + channels = ["local", *channels] + if prepend: + channels += context.channels + self._channels = IndexedSet(channels) + if subdirs: + if platform: + log.warning("subdirs is %s, ignoring platform %s", subdirs, platform) + else: + subdirs = (platform, "noarch") if platform is not None else context.subdirs + self._subdirs = subdirs + self._repodata_fn = repodata_fn + self.channels = {} + self.expanded_channels = IndexedSet() + for channel in self._channels: + urls = Channel(channel).urls(True, subdirs) + expanded_channels = [Channel(url) for url in urls] + self.channels[channel] = [ + SubdirData(expanded_channel, repodata_fn=repodata_fn) + for expanded_channel in expanded_channels + ] + self.expanded_channels.update(expanded_channels) + # LAST_CHANNEL_URLS is still used in conda-build and must be maintained for the moment. + LAST_CHANNEL_URLS.clear() + LAST_CHANNEL_URLS.extend(self.expanded_channels) + if prefix is None: + self.prefix_data = None + elif isinstance(prefix, PrefixData): + self.prefix_data = prefix + else: + self.prefix_data = PrefixData(prefix) + self.use_cache = True if use_cache is None and context.offline else use_cache + self.use_system = use_system + + @property + def cache_entries(self) -> tuple[PackageCacheRecord, ...]: + """Contents of the package cache if active. + + Returns: + All packages available from the package cache. + """ + try: + return self._cache_entries + except AttributeError: + self.reload(cache=True) + return self._cache_entries + + @property + def system_packages(self) -> dict[PackageRecord, PackageRecord]: + """System packages provided by plugins. + + Returns: + Identity mapping of the available system packages in a ``dict``. + """ + try: + return self._system_packages + except AttributeError: + self.reload(system=True) + return self._system_packages + + @property + def features(self) -> dict[PackageRecord, PackageRecord]: + """Active tracking features. + + Returns: + Identity mapping of the local tracking features in a ``dict``. + """ + try: + return self._features + except AttributeError: + self.reload(features=True) + return self._features + + def reload( + self, + *, + prefix: bool = False, + cache: bool = False, + features: bool = False, + system: bool = False, + ) -> None: + """Reload one or more of the index components. + + Can be used to refresh the index with new information, for example after a new + package has been installed into the index. + + Args: + prefix: if ``True``, reload the prefix data. + cache: if ``True``, reload the package cache. + features: if ``True``, reload the tracking features. + system: if ``True``, reload the system packages. + """ + has_data = hasattr(self, "_data") + if prefix: + if self.prefix_data: + self.prefix_data.reload() + if has_data: + self._supplement_index_dict_with_prefix() + if cache: + self._cache_entries = PackageCacheData.get_all_extracted_entries() + if has_data: + self._supplement_index_dict_with_cache() + if features: + self._features = { + (rec := PackageRecord.feature(track_feature)): rec + for track_feature in context.track_features + } + if has_data: + self._data.update(self.features) + if system: + self._system_packages = { + package: package + for package in context.plugin_manager.get_virtual_package_records() + } + if has_data: + self._data.update(self.system_packages) + + def __repr__(self) -> str: + channels = ", ".join(self.channels.keys()) + return f"<{self.__class__.__name__}(channels=[{channels}])>" + + def get_reduced_index(self, specs: Iterable[MatchSpec]) -> ReducedIndex: + """Create a reduced index with a subset of packages. + + Can be used to create a reduced index as a subset from an existing index. + + Args: + specs: the specs that span the subset. + + Returns: + a reduced index with the same sources as this index, but limited to ``specs`` + and their dependency graph. + """ + return ReducedIndex( + specs=specs, + channels=self._channels, + prepend=False, + subdirs=self._subdirs, + use_local=False, + use_cache=self.use_cache, + prefix=self.prefix_data, + repodata_fn=self._repodata_fn, + use_system=self.use_system, + ) + + @property + def data(self) -> dict[PackageRecord, PackageRecord]: + """The entire index as a dict; avoid if possible. + + Warning: + This returns the entire contents of the index as a single identity mapping in + a ``dict``. This may be convenient, but it comes at a cost because all sources + must be fully loaded at significant overhead for :class:`~conda.models.records.PackageRecord` + construction for **every** package. + + Hence, all uses of :attr:`data`, including all iteration over the entire index, + is strongly discouraged. + """ + try: + return self._data + except AttributeError: + self._realize() + return self._data + + @data.setter + def data(self, value: dict[PackageRecord, PackageRecord]) -> None: + self._data = value + + def _supplement_index_dict_with_prefix(self) -> None: + """ + Supplement the index with information from its prefix. + """ + if self.prefix_data is None: + return + + # supplement index with information from prefix/conda-meta + for prefix_record in self.prefix_data.iter_records(): + if prefix_record in self._data: + current_record = self._data[prefix_record] + if current_record.channel == prefix_record.channel: + # The downloaded repodata takes priority, so we do not overwrite. + # We do, however, copy the link information so that the solver (i.e. resolve) + # knows this package is installed. + link = prefix_record.get("link") or EMPTY_LINK + self._data[prefix_record] = PrefixRecord.from_objects( + current_record, prefix_record, link=link + ) + else: + # If the local packages channel information does not agree with + # the channel information in the index then they are most + # likely referring to different packages. This can occur if a + # multi-channel changes configuration, e.g. defaults with and + # without the free channel. In this case we need to fake the + # channel data for the existing package. + prefix_channel = prefix_record.channel + prefix_channel._Channel__canonical_name = prefix_channel.url() + del prefix_record._PackageRecord__pkey + self._data[prefix_record] = prefix_record + else: + # If the package is not in the repodata, use the local data. + # If the channel is known but the package is not in the index, it + # is because 1) the channel is unavailable offline, or 2) it no + # longer contains this package. Either way, we should prefer any + # other version of the package to this one. On the other hand, if + # it is in a channel we don't know about, assign it a value just + # above the priority of all known channels. + self._data[prefix_record] = prefix_record + + def _supplement_index_dict_with_cache(self) -> None: + # supplement index with packages from the cache + for pcrec in self.cache_entries: + if pcrec in self._data: + # The downloaded repodata takes priority + current_record = self._data[pcrec] + self._data[pcrec] = PackageCacheRecord.from_objects( + current_record, pcrec + ) + else: + self._data[pcrec] = pcrec + + def _realize(self) -> None: + self._data = {} + for subdir_datas in self.channels.values(): + for subdir_data in subdir_datas: + self._data.update((prec, prec) for prec in subdir_data.iter_records()) + self._supplement_index_dict_with_prefix() + if self.use_cache: + self._supplement_index_dict_with_cache() + self._data.update(self.features) + if self.use_system: + self._data.update(self.system_packages) + + def _retrieve_from_channels(self, key: PackageRecord) -> PackageRecord | None: + for subdir_datas in reversed(self.channels.values()): + for subdir_data in subdir_datas: + if key.subdir != subdir_data.channel.subdir: + continue + prec_candidates = list(subdir_data.query(key)) + if not prec_candidates: + continue + if len(prec_candidates) > 1: + raise CondaKeyError( + key, "More than one matching package found in channels." + ) + prec = prec_candidates[0] + if prec: + return prec + return None + + def _retrieve_all_from_channels(self, key: PackageRecord) -> list[PackageRecord]: + precs = [] + for subdir_datas in reversed(self.channels.values()): + for subdir_data in subdir_datas: + if hasattr(key, "subdir") and key.subdir != subdir_data.channel.subdir: + continue + precs.extend(subdir_data.query(key)) + return precs + + def _update_from_prefix( + self, key: PackageRecord, prec: PackageRecord | None + ) -> PackageRecord | None: + prefix_prec = self.prefix_data.get(key.name, None) if self.prefix_data else None + if prefix_prec and prefix_prec == prec: + if prec: + if prec.channel == prefix_prec.channel: + link = prefix_prec.get("link") or EMPTY_LINK + prec = PrefixRecord.from_objects(prec, prefix_prec, link=link) + else: + prefix_channel = prefix_prec.channel + prefix_channel._Channel__canonical_name = prefix_channel.url() + del prefix_prec._PackageRecord__pkey + prec = prefix_prec + else: + prec = prefix_prec + return prec + + def _update_from_cache( + self, key: PackageRecord, prec: PackageRecord | None + ) -> PackageRecord | None: + for pcrec in self.cache_entries: + if pcrec == key: + if prec: + # The downloaded repodata takes priority + return PackageCacheRecord.from_objects(prec, pcrec) + else: + return pcrec + return prec + + def __getitem__(self, key: PackageRecord) -> PackageRecord: + if not isinstance(key, PackageRecord): + raise TypeError( + "Can only retrieve PackageRecord objects. Got {}.", type(key) + ) + try: + return self._data[key] + except AttributeError: + pass + if key.name.startswith("__"): + try: + return self.system_packages[key] + except KeyError: + pass + if key.name.endswith("@"): + try: + return self.features[key] + except KeyError: + pass + prec = self._retrieve_from_channels(key) + prec = self._update_from_prefix(key, prec) + if self.use_cache: + prec = self._update_from_cache(key, prec) + if prec is None: + raise KeyError((key,)) + return prec + + def __contains__(self, key: PackageRecord) -> bool: + try: + _ = self[key] + return True + except (PackagesNotFoundError, KeyError): + return False + + def __copy__(self) -> Self: + inst = self.__class__.__new__(self.__class__) + inst.__dict__.update(self.__dict__) + if "_data" in self.__dict__: + inst.__dict__["_data"] = self.__dict__["_data"].copy() + return inst + + +class ReducedIndex(Index): + """Index that contains a subset of available packages. + + Like :class:`Index`, this makes information about packages from the same four + sources available. However, the contents of the reduced index is limited to + a subset of packages relevant to a given specification. + This works by taking into account all packages that match the given specification + together with their dependencies and their dependencies dependencies, etc. + + Note: + See :meth:`Index.get_reduced_index` for convenient construction. + """ + + def __init__( + self, + specs: Iterable[MatchSpec], + channels: tuple[str, ...] = (), + prepend: bool = True, + platform: str | None = None, + subdirs: tuple[str, ...] | None = None, + use_local: bool = False, + use_cache: bool | None = None, + prefix: PathType | PrefixData | None = None, + repodata_fn: str | None = context.repodata_fns[-1], + use_system: bool = False, + ) -> None: + """Initialize a new reduced index. + + Args: + specs: the collection of specifications that span the subset of packages. + all other args: see :class:`Index`. + """ + super().__init__( + channels, + prepend, + platform, + subdirs, + use_local, + use_cache, + prefix, + repodata_fn, + use_system, + ) + self.specs = specs + self._derive_reduced_index() + + def __repr__(self) -> str: + channels = ", ".join(self.channels.keys()) + return f"<{self.__class__.__name__}(spec={self.specs}, channels=[{channels}])>" + + def _derive_reduced_index(self) -> None: + records = IndexedSet() + collected_names = set() + collected_track_features = set() + pending_names = set() + pending_track_features = set() + + def push_specs(*specs: MatchSpec | str) -> None: + """ + Add a package name or track feature from a MatchSpec to the pending set. + + :param spec: The MatchSpec to process. + """ + for spec in map(MatchSpec, specs): + name = spec.get_raw_value("name") + if name and name not in collected_names: + pending_names.add(name) + track_features = spec.get_raw_value("track_features") + if track_features: + for ftr_name in track_features: + if ftr_name not in collected_track_features: + pending_track_features.add(ftr_name) + + def push_records(*records: PackageRecord) -> None: + """ + Process a package record to collect its dependencies and features. + + :param record: The package record to process. + """ + for record in records: + try: + combined_depends = record.combined_depends + except InvalidSpec as e: + log.warning( + "Skipping %s due to InvalidSpec: %s", + record.record_id(), + e._kwargs["invalid_spec"], + ) + return + push_specs( + record.name, + *combined_depends, + *( + MatchSpec(track_features=ftr_name) + for ftr_name in record.track_features + ), + ) + + if self.prefix_data: + push_records(*self.prefix_data.iter_records()) + push_specs(*self.specs) + + while pending_names or pending_track_features: + while pending_names: + name = pending_names.pop() + collected_names.add(name) + spec = MatchSpec(name) + # new_records = SubdirData.query_all( + # spec, channels=channels, subdirs=subdirs, repodata_fn=repodata_fn + # ) + new_records = self._retrieve_all_from_channels(spec) + push_records(*new_records) + records.update(new_records) + + while pending_track_features: + feature_name = pending_track_features.pop() + collected_track_features.add(feature_name) + spec = MatchSpec(track_features=feature_name) + # new_records = SubdirData.query_all( + # spec, channels=channels, subdirs=subdirs, repodata_fn=repodata_fn + # ) + new_records = self._retrieve_all_from_channels(spec) + push_records(*new_records) + records.update(new_records) + + self._data = {rec: rec for rec in records} + + self._supplement_index_dict_with_prefix() + + if self.use_cache: + self._supplement_index_dict_with_cache() + + # add feature records for the solver + known_features = set() + for rec in self._data.values(): + known_features.update((*rec.track_features, *rec.features)) + known_features.update(context.track_features) + for known_feature in known_features: + rec = PackageRecord.feature(known_feature) + self._data[rec] = rec + + self._data.update(self.system_packages) + + +def dist_str_in_index(index: dict[Any, Any], dist_str: str) -> bool: + """ + Check if a distribution string matches any package in the index. + + :param index: The package index. + :param dist_str: The distribution string to match against the index. + :return: True if there is a match; False otherwise. + """ + match_spec = MatchSpec.from_dist_str(dist_str) + return any(match_spec.match(prec) for prec in index.values()) + + +@deprecated("25.3", "26.3", addendum="Use `conda.core.Index.reload` instead.") +def _supplement_index_with_system(index: dict[PackageRecord, PackageRecord]) -> None: + """ + Loads and populates virtual package records from conda plugins + and adds them to the provided index, unless there is a naming + conflict. + :param index: The package index to supplement. + """ + if isinstance(index, Index): + return + for package in context.plugin_manager.get_virtual_package_records(): + index[package] = package + + +def get_archspec_name() -> str | None: + """ + Determine the architecture specification name for the current environment. + + :return: The architecture name if available, otherwise None. + """ + from ..base.context import _arch_names, non_x86_machines + + target_plat, target_arch = context.subdir.split("-") + # This has to reverse what Context.subdir is doing + if target_arch in non_x86_machines: + machine = target_arch + elif target_arch == "zos": + return None + elif target_arch.isdigit(): + machine = _arch_names[int(target_arch)] + else: + return None + + native_subdir = context._native_subdir() + + if native_subdir != context.subdir: + return machine + else: + import archspec.cpu + + return str(archspec.cpu.host()) + + +@deprecated( + "26.3", + "26.9", + addendum="Use `conda.models.channel.all_channel_urls(context.channels)` instead.", +) +def calculate_channel_urls( + channel_urls: tuple[str] = (), + prepend: bool = True, + platform: str | None = None, + use_local: bool = False, +) -> list[str]: + """ + Calculate the full list of channel URLs to use based on the given parameters. + + :param channel_urls: Initial list of channel URLs. + :param prepend: Whether to prepend default channels to the list. + :param platform: The target platform for the channels. + :param use_local: Whether to include the local channel. + :return: The calculated list of channel URLs. + """ + if use_local: + channel_urls = ["local"] + list(channel_urls) + if prepend: + channel_urls += context.channels + + subdirs = (platform, "noarch") if platform is not None else context.subdirs + return all_channel_urls(channel_urls, subdirs=subdirs) diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/initialize.py b/miniconda3/lib/python3.13/site-packages/conda/core/initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfc7c9efd2df5804a460a1afecba6dde6b8ddcc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/initialize.py @@ -0,0 +1,2388 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Backend logic for `conda init`. + +Sections in this module are + + 1. top-level functions + 2. plan creators + 3. plan runners + 4. individual operations + 5. helper functions + +The top-level functions compose and execute full plans. + +A plan is created by composing various individual operations. The plan data structure is a +list of dicts, where each dict represents an individual operation. The dict contains two +keys--`function` and `kwargs`--where function is the name of the individual operation function +within this module. + +Each individual operation must + + a) return a `Result` (i.e. NEEDS_SUDO, MODIFIED, or NO_CHANGE) + b) have no side effects if context.dry_run is True + c) be verbose and descriptive about the changes being made or proposed is context.verbose + +The plan runner functions take the plan (list of dicts) as an argument, and then coordinate the +execution of each individual operation. The docstring for `run_plan_elevated()` has details on +how that strategy is implemented. + +""" + +import os +import re +import struct +import sys +from difflib import unified_diff +from errno import ENOENT +from glob import glob +from itertools import chain +from logging import getLogger +from os.path import abspath, basename, dirname, exists, expanduser, isdir, isfile, join +from pathlib import Path +from random import randint +from typing import Literal + +from .. import CONDA_PACKAGE_ROOT, CondaError +from .. import __version__ as CONDA_VERSION +from ..activate import ( + CshActivator, + FishActivator, + PosixActivator, + PowerShellActivator, + XonshActivator, +) +from ..auxlib.compat import Utf8NamedTemporaryFile +from ..auxlib.ish import dals +from ..base.context import context +from ..common.compat import ( + ensure_binary, + ensure_text_type, + ensure_utf8_encoding, + on_mac, + on_win, + open_utf8, +) +from ..common.path import ( + BIN_DIRECTORY, + expand, + get_python_short_path, + get_python_site_packages_short_path, + win_path_ok, +) +from ..common.serialize import json +from ..exceptions import CondaValueError +from ..gateways.disk.create import copy, mkdir_p +from ..gateways.disk.delete import rm_rf +from ..gateways.disk.link import lexists +from ..gateways.disk.permissions import make_executable +from ..gateways.disk.read import compute_sum +from ..gateways.subprocess import subprocess_call +from .portability import generate_shebang_for_entry_point + +if on_win: # pragma: no cover + import winreg + + # Use v1 import paths to avoid bootstrapping issues + # TODO: Remove once fully deployed (one release after merge) + from menuinst.knownfolders import FOLDERID, get_folder_path + from menuinst.winshortcut import create_shortcut + + +log = getLogger(__name__) + +CONDA_INITIALIZE_RE_BLOCK = ( + r"^# >>> conda initialize >>>(?:\n|\r\n)" + r"([\s\S]*?)" + r"# <<< conda initialize <<<(?:\n|\r\n)?" +) + +CONDA_INITIALIZE_PS_RE_BLOCK = ( + r"^#region conda initialize(?:\n|\r\n)([\s\S]*?)#endregion(?:\n|\r\n)?" +) + + +class Result: + NEEDS_SUDO = "needs sudo" + MODIFIED = "modified" + NO_CHANGE = "no change" + + +ContentTypeOptions = Literal["initialize", "add_condabin_to_path"] + +# ##################################################### +# top-level functions +# ##################################################### + + +def install(conda_prefix): + plan = make_install_plan(conda_prefix) + run_plan(plan) + if not context.dry_run and any( + step["result"] == Result.NEEDS_SUDO for step in plan + ): + raise CondaError("Some steps require elevated permissions.") + print_plan_results(plan) + return 0 + + +def initialize( + conda_prefix, shells, for_user, for_system, anaconda_prompt, reverse=False +): + plan1 = [] + if os.getenv("CONDA_PIP_UNINITIALIZED") == "true": + plan1 = make_install_plan(conda_prefix) + run_plan(plan1) + if not context.dry_run: + run_plan_elevated(plan1) + + plan2 = make_initialize_plan( + conda_prefix, shells, for_user, for_system, anaconda_prompt, reverse=reverse + ) + run_plan(plan2) + if not context.dry_run: + run_plan_elevated(plan2) + + plan = plan1 + plan2 + print_plan_results(plan) + + if any(step["result"] == Result.NEEDS_SUDO for step in plan): + print("Operation failed.", file=sys.stderr) + return 1 + + +def initialize_dev(shell, dev_env_prefix=None, conda_source_root=None): + # > alias conda-dev='eval "$(python -m conda init --dev)"' + # > eval "$(python -m conda init --dev)" + + prefix = expand(dev_env_prefix or sys.prefix) + conda_source_root = expand(conda_source_root or os.getcwd()) + + python_exe, python_version, site_packages_dir = _get_python_info(prefix) + + if not isfile(join(conda_source_root, "conda", "__main__.py")): + raise CondaValueError( + f"Directory is not a conda source root: {conda_source_root}" + ) + + plan = make_install_plan(prefix) + plan.append( + { + "function": remove_conda_in_sp_dir.__name__, + "kwargs": { + "target_path": site_packages_dir, + }, + } + ) + plan.append( + { + "function": make_conda_egg_link.__name__, + "kwargs": { + "target_path": join(site_packages_dir, "conda.egg-link"), + "conda_source_root": conda_source_root, + }, + } + ) + plan.append( + { + "function": modify_easy_install_pth.__name__, + "kwargs": { + "target_path": join(site_packages_dir, "easy-install.pth"), + "conda_source_root": conda_source_root, + }, + } + ) + plan.append( + { + "function": make_dev_egg_info_file.__name__, + "kwargs": { + "target_path": join(conda_source_root, "conda.egg-info"), + }, + } + ) + + run_plan(plan) + + if context.dry_run or context.verbose: + print_plan_results(plan, sys.stderr) + + if any(step["result"] == Result.NEEDS_SUDO for step in plan): # pragma: no cover + raise CondaError( + "Operation failed. Privileged install disallowed for 'conda init --dev'." + ) + + env_vars = { + "PYTHONHASHSEED": randint(0, 4294967296), + "PYTHON_MAJOR_VERSION": python_version[0], + "TEST_PLATFORM": "win" if on_win else "unix", + } + unset_env_vars = ( + "CONDA_DEFAULT_ENV", + "CONDA_EXE", + "_CE_M", + "_CE_CONDA", + "CONDA_PREFIX", + "CONDA_PREFIX_1", + "CONDA_PREFIX_2", + "CONDA_PYTHON_EXE", + "CONDA_PROMPT_MODIFIER", + "CONDA_SHLVL", + ) + + if shell == "bash": + print("\n".join(_initialize_dev_bash(prefix, env_vars, unset_env_vars))) + elif shell == "cmd.exe": + script = _initialize_dev_cmdexe(prefix, env_vars, unset_env_vars) + if not context.dry_run: + with open_utf8("dev-init.bat", "w") as fh: + fh.write("\n".join(script)) + if context.verbose: + print("\n".join(script)) + print("now run > .\\dev-init.bat") + else: + raise NotImplementedError() + return 0 + + +def _initialize_dev_bash(prefix, env_vars, unset_env_vars): + sys_executable = abspath(sys.executable) + if on_win: + sys_executable = f"$(cygpath '{sys_executable}')" + + # unset/set environment variables + yield from (f"unset {envvar}" for envvar in unset_env_vars) + yield from ( + f"export {envvar}='{value}'" for envvar, value in sorted(env_vars.items()) + ) + + # initialize shell interface + yield f'eval "$("{sys_executable}" -m conda shell.bash hook)"' + + # optionally activate environment + if context.auto_activate: + yield f"conda activate '{prefix}'" + + +def _initialize_dev_cmdexe(prefix, env_vars, unset_env_vars): + dev_arg = "" + if context.dev: + dev_arg = "--dev" + condabin = Path(prefix, "condabin") + + yield ( + '@IF NOT "%CONDA_PROMPT_MODIFIER%" == "" ' + '@CALL SET "PROMPT=%%PROMPT:%CONDA_PROMPT_MODIFIER%=%_empty_not_set_%%%"' + ) + + # unset/set environment variables + yield from (f"@SET {envvar}=" for envvar in unset_env_vars) + yield from ( + f'@SET "{envvar}={value}"' for envvar, value in sorted(env_vars.items()) + ) + + # initialize shell interface + yield f'@CALL "{condabin / "conda_hook.bat"}" {dev_arg}' + yield "@IF %ERRORLEVEL% NEQ 0 @EXIT /B %ERRORLEVEL%" + + # optionally activate environment + if context.auto_activate: + yield f'@CALL "{condabin / "conda.bat"}" activate {dev_arg} "{prefix}"' + yield "@IF %ERRORLEVEL% NEQ 0 @EXIT /B %ERRORLEVEL%" + + +def add_condabin_to_path(conda_prefix, shells, for_user, for_system, reverse=False): + plan = make_condabin_plan( + conda_prefix, shells, for_user, for_system, reverse=reverse + ) + run_plan(plan) + if not context.dry_run: + run_plan_elevated(plan) + + print_plan_results(plan) + + if any(step["result"] == Result.NEEDS_SUDO for step in plan): + print("Operation failed.", file=sys.stderr) + return 1 + + +# ##################################################### +# plan creators +# ##################################################### + + +def make_install_plan(conda_prefix): + try: + python_exe, python_version, site_packages_dir = _get_python_info(conda_prefix) + except OSError: + python_exe, python_version, site_packages_dir = None, None, None # NOQA + + plan = [] + + # ###################################### + # executables + # ###################################### + if on_win: + conda_exe_path = join(conda_prefix, "Scripts", "conda-script.py") + conda_env_exe_path = join(conda_prefix, "Scripts", "conda-env-script.py") + plan.append( + { + "function": make_entry_point_exe.__name__, + "kwargs": { + "target_path": join(conda_prefix, "Scripts", "conda.exe"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": make_entry_point_exe.__name__, + "kwargs": { + "target_path": join(conda_prefix, "Scripts", "conda-env.exe"), + "conda_prefix": conda_prefix, + }, + } + ) + else: + # We can't put a conda.exe in condabin on Windows. It'll conflict with conda.bat. + plan.append( + { + "function": make_entry_point.__name__, + "kwargs": { + "target_path": join(conda_prefix, "condabin", "conda"), + "conda_prefix": conda_prefix, + "module": "conda.cli", + "func": "main", + }, + } + ) + conda_exe_path = join(conda_prefix, "bin", "conda") + conda_env_exe_path = join(conda_prefix, "bin", "conda-env") + + plan.append( + { + "function": make_entry_point.__name__, + "kwargs": { + "target_path": conda_exe_path, + "conda_prefix": conda_prefix, + "module": "conda.cli", + "func": "main", + }, + } + ) + plan.append( + { + "function": make_entry_point.__name__, + "kwargs": { + "target_path": conda_env_exe_path, + "conda_prefix": conda_prefix, + # TODO: Remove upon full deprecation in 25.3 + "module": "conda_env.cli.main", + "func": "main", + }, + } + ) + + # ###################################### + # shell wrappers + # ###################################### + if on_win: + plan.append( + { + "function": install_condabin_conda_bat.__name__, + "kwargs": { + "target_path": join(conda_prefix, "condabin", "conda.bat"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_library_bin_conda_bat.__name__, + "kwargs": { + "target_path": join(conda_prefix, "Library", "bin", "conda.bat"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_condabin_conda_activate_bat.__name__, + "kwargs": { + "target_path": join( + conda_prefix, "condabin", "_conda_activate.bat" + ), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_condabin_rename_tmp_bat.__name__, + "kwargs": { + "target_path": join(conda_prefix, "condabin", "rename_tmp.bat"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_condabin_conda_auto_activate_bat.__name__, + "kwargs": { + "target_path": join( + conda_prefix, "condabin", "conda_auto_activate.bat" + ), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_condabin_hook_bat.__name__, + "kwargs": { + "target_path": join(conda_prefix, "condabin", "conda_hook.bat"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_Scripts_activate_bat.__name__, + "kwargs": { + "target_path": join(conda_prefix, "Scripts", "activate.bat"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_activate_bat.__name__, + "kwargs": { + "target_path": join(conda_prefix, "condabin", "activate.bat"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_deactivate_bat.__name__, + "kwargs": { + "target_path": join(conda_prefix, "condabin", "deactivate.bat"), + "conda_prefix": conda_prefix, + }, + } + ) + + plan.append( + { + "function": install_activate.__name__, + "kwargs": { + "target_path": join(conda_prefix, BIN_DIRECTORY, "activate"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_deactivate.__name__, + "kwargs": { + "target_path": join(conda_prefix, BIN_DIRECTORY, "deactivate"), + "conda_prefix": conda_prefix, + }, + } + ) + + plan.append( + { + "function": install_conda_sh.__name__, + "kwargs": { + "target_path": join(conda_prefix, "etc", "profile.d", "conda.sh"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_conda_fish.__name__, + "kwargs": { + "target_path": join( + conda_prefix, "etc", "fish", "conf.d", "conda.fish" + ), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_conda_psm1.__name__, + "kwargs": { + "target_path": join(conda_prefix, "shell", "condabin", "Conda.psm1"), + "conda_prefix": conda_prefix, + }, + } + ) + plan.append( + { + "function": install_conda_hook_ps1.__name__, + "kwargs": { + "target_path": join( + conda_prefix, "shell", "condabin", "conda-hook.ps1" + ), + "conda_prefix": conda_prefix, + }, + } + ) + if site_packages_dir: + plan.append( + { + "function": install_conda_xsh.__name__, + "kwargs": { + "target_path": join(site_packages_dir, "xontrib", "conda.xsh"), + "conda_prefix": conda_prefix, + }, + } + ) + else: + print( + "WARNING: Cannot install xonsh wrapper without a python interpreter in prefix: " + f"{conda_prefix}", + file=sys.stderr, + ) + plan.append( + { + "function": install_conda_csh.__name__, + "kwargs": { + "target_path": join(conda_prefix, "etc", "profile.d", "conda.csh"), + "conda_prefix": conda_prefix, + }, + } + ) + return plan + + +def make_initialize_plan( + conda_prefix, shells, for_user, for_system, anaconda_prompt, reverse=False +): + """ + Creates a plan for initializing conda in shells. + + Bash: + On Linux, when opening the terminal, .bashrc is sourced (because it is an interactive shell). + On macOS on the other hand, the .bash_profile gets sourced by default when executing it in + Terminal.app. Some other programs do the same on macOS so that's why we're initializing conda + in .bash_profile. + On Windows, there are multiple ways to open bash depending on how it was installed. Git Bash, + Cygwin, and MSYS2 all use .bash_profile by default. + + PowerShell: + There's several places PowerShell can store its path, depending on if it's Windows PowerShell, + PowerShell Core on Windows, or PowerShell Core on macOS/Linux. The easiest way to resolve it + is to just ask different possible installations of PowerShell where their profiles are. + """ + plan = make_install_plan(conda_prefix) + shells = set(shells) + if shells & {"bash", "zsh"}: + if "bash" in shells and for_user: + bashrc_path = expand( + join("~", ".bash_profile" if (on_mac or on_win) else ".bashrc") + ) + plan.append( + { + "function": init_sh_user.__name__, + "kwargs": { + "target_path": bashrc_path, + "conda_prefix": conda_prefix, + "shell": "bash", + "reverse": reverse, + }, + } + ) + + if "zsh" in shells and for_user: + if "ZDOTDIR" in os.environ: + zshrc_path = expand(join("$ZDOTDIR", ".zshrc")) + else: + zshrc_path = expand(join("~", ".zshrc")) + plan.append( + { + "function": init_sh_user.__name__, + "kwargs": { + "target_path": zshrc_path, + "conda_prefix": conda_prefix, + "shell": "zsh", + "reverse": reverse, + }, + } + ) + + if for_system: + plan.append( + { + "function": init_sh_system.__name__, + "kwargs": { + "target_path": "/etc/profile.d/conda.sh", + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + + if "fish" in shells: + if for_user: + config_fish_path = expand(join("~", ".config", "fish", "config.fish")) + plan.append( + { + "function": init_fish_user.__name__, + "kwargs": { + "target_path": config_fish_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + + if for_system: + config_fish_path = expand(join("~", ".config", "fish", "config.fish")) + plan.append( + { + "function": init_fish_user.__name__, + "kwargs": { + "target_path": config_fish_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + + if "xonsh" in shells: + if for_user: + config_xonsh_path = expand(join("~", ".xonshrc")) + plan.append( + { + "function": init_xonsh_user.__name__, + "kwargs": { + "target_path": config_xonsh_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + + if for_system: + if on_win: + config_xonsh_path = expand( + join("%ALLUSERSPROFILE%", "xonsh", "xonshrc") + ) + else: + config_xonsh_path = "/etc/xonshrc" + plan.append( + { + "function": init_xonsh_user.__name__, + "kwargs": { + "target_path": config_xonsh_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + + if "tcsh" in shells and for_user: + tcshrc_path = expand(join("~", ".tcshrc")) + plan.append( + { + "function": init_sh_user.__name__, + "kwargs": { + "target_path": tcshrc_path, + "conda_prefix": conda_prefix, + "shell": "tcsh", + "reverse": reverse, + }, + } + ) + + if "powershell" in shells: + if for_user: + profile = "$PROFILE.CurrentUserAllHosts" + + if for_system: + profile = "$PROFILE.AllUsersAllHosts" + + def find_powershell_paths(*exe_names): + for exe_name in exe_names: + try: + yield subprocess_call( + (exe_name, "-NoProfile", "-Command", profile) + ).stdout.strip() + except Exception: + pass + + config_powershell_paths = set( + find_powershell_paths("powershell", "pwsh", "pwsh-preview") + ) + + for config_path in config_powershell_paths: + if config_path is not None: + plan.append( + { + "function": init_powershell_user.__name__, + "kwargs": { + "target_path": config_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + + if "cmd.exe" in shells: + if for_user: + plan.append( + { + "function": init_cmd_exe_registry.__name__, + "kwargs": { + "target_path": "HKEY_CURRENT_USER\\Software\\Microsoft\\" + "Command Processor\\AutoRun", + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + if for_system: + plan.append( + { + "function": init_cmd_exe_registry.__name__, + "kwargs": { + "target_path": "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\" + "Command Processor\\AutoRun", + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + # it would be nice to enable this on a user-level basis, but unfortunately, it is + # a system-level key only. + plan.append( + { + "function": init_long_path.__name__, + "kwargs": { + "target_path": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\" + "FileSystem\\LongPathsEnabled" + }, + } + ) + if anaconda_prompt: + plan.append( + { + "function": install_anaconda_prompt.__name__, + "kwargs": { + "target_path": join( + conda_prefix, "condabin", "Anaconda Prompt.lnk" + ), + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + if on_win: + desktop_dir, exception = get_folder_path(FOLDERID.Desktop) + if exception: + raise RuntimeError(f"Could not get Desktop folder: {exception}") + else: + desktop_dir = join(expanduser("~"), "Desktop") + plan.append( + { + "function": install_anaconda_prompt.__name__, + "kwargs": { + "target_path": join(desktop_dir, "Anaconda Prompt.lnk"), + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + + return plan + + +def make_condabin_plan(conda_prefix, shells, for_user, for_system, reverse=False): + """ + Creates a plan to add $PREFIX/condabin to $PATH. + """ + plan = [] + shells = set(shells) + if shells & {"bash", "zsh"}: + if "bash" in shells and for_user: + bashrc_path = expand( + join("~", ".bash_profile" if (on_mac or on_win) else ".bashrc") + ) + plan.append( + { + "function": init_sh_user.__name__, + "kwargs": { + "target_path": bashrc_path, + "conda_prefix": conda_prefix, + "shell": "bash", + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if "zsh" in shells and for_user: + if "ZDOTDIR" in os.environ: + zshrc_path = expand(join("$ZDOTDIR", ".zshrc")) + else: + zshrc_path = expand(join("~", ".zshrc")) + plan.append( + { + "function": init_sh_user.__name__, + "kwargs": { + "target_path": zshrc_path, + "conda_prefix": conda_prefix, + "shell": "zsh", + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if for_system: + plan.append( + { + "function": init_sh_system.__name__, + "kwargs": { + "target_path": "/etc/profile.d/conda.sh", + "conda_prefix": conda_prefix, + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if "fish" in shells: + if for_user: + config_fish_path = expand(join("~", ".config", "fish", "config.fish")) + plan.append( + { + "function": init_fish_user.__name__, + "kwargs": { + "target_path": config_fish_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if for_system: + config_fish_path = expand(join("~", ".config", "fish", "config.fish")) + plan.append( + { + "function": init_fish_user.__name__, + "kwargs": { + "target_path": config_fish_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if "xonsh" in shells: + if for_user: + config_xonsh_path = expand(join("~", ".xonshrc")) + plan.append( + { + "function": init_xonsh_user.__name__, + "kwargs": { + "target_path": config_xonsh_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if for_system: + if on_win: + config_xonsh_path = expand( + join("%ALLUSERSPROFILE%", "xonsh", "xonshrc") + ) + else: + config_xonsh_path = "/etc/xonshrc" + plan.append( + { + "function": init_xonsh_user.__name__, + "kwargs": { + "target_path": config_xonsh_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if "tcsh" in shells and for_user: + tcshrc_path = expand(join("~", ".tcshrc")) + plan.append( + { + "function": init_sh_user.__name__, + "kwargs": { + "target_path": tcshrc_path, + "conda_prefix": conda_prefix, + "shell": "tcsh", + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if "powershell" in shells: + if for_user: + profile = "$PROFILE.CurrentUserAllHosts" + + if for_system: + profile = "$PROFILE.AllUsersAllHosts" + + def find_powershell_paths(*exe_names): + for exe_name in exe_names: + try: + yield subprocess_call( + (exe_name, "-NoProfile", "-Command", profile) + ).stdout.strip() + except Exception: + pass + + config_powershell_paths = set( + find_powershell_paths("powershell", "pwsh", "pwsh-preview") + ) + + for config_path in config_powershell_paths: + if config_path is not None: + plan.append( + { + "function": init_powershell_user.__name__, + "kwargs": { + "target_path": config_path, + "conda_prefix": conda_prefix, + "reverse": reverse, + "content_type": "add_condabin_to_path", + }, + } + ) + + if "cmd.exe" in shells: + if for_user: + # Modify HKCU\Environment\PATH + plan.append( + { + "function": add_condabin_to_path_registry.__name__, + "kwargs": { + "target_path": "HKEY_CURRENT_USER\\Environment\\PATH", + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + if for_system: + # Modify HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATH + plan.append( + { + "function": add_condabin_to_path_registry.__name__, + "kwargs": { + "target_path": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\" + "Session Manager\\Environment\\PATH", + "conda_prefix": conda_prefix, + "reverse": reverse, + }, + } + ) + # Also ensure long paths are enabled if modifying system settings + plan.append( + { + "function": init_long_path.__name__, + "kwargs": { + "target_path": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\" + "FileSystem\\LongPathsEnabled" + }, + } + ) + # Note: We are *not* modifying AutoRun here for PATH changes, + # only the persistent PATH environment variable. AutoRun is for shell hooks. + + return plan + + +# ##################################################### +# plan runners +# ##################################################### + + +def run_plan(plan): + for step in plan: + previous_result = step.get("result", None) + if previous_result in (Result.MODIFIED, Result.NO_CHANGE): + continue + try: + result = globals()[step["function"]]( + *step.get("args", ()), **step.get("kwargs", {}) + ) + except OSError as e: + log.info("%s: %r", step["function"], e, exc_info=True) + result = Result.NEEDS_SUDO + step["result"] = result + + +def run_plan_elevated(plan): + """ + The strategy of this function differs between unix and Windows. Both strategies use a + subprocess call, where the subprocess is run with elevated privileges. The executable + invoked with the subprocess is `python -m conda.core.initialize`, so see the + `if __name__ == "__main__"` at the bottom of this module. + + For unix platforms, we convert the plan list to json, and then call this module with + `sudo python -m conda.core.initialize` while piping the plan json to stdin. We collect json + from stdout for the results of the plan execution with elevated privileges. + + For Windows, we create a temporary file that holds the json content of the plan. The + subprocess reads the content of the file, modifies the content of the file with updated + execution status, and then closes the file. This process then reads the content of that file + for the individual operation execution results, and then deletes the file. + """ + if any(step["result"] == Result.NEEDS_SUDO for step in plan): + plan_input = json.dumps( + plan, + ensure_ascii=False, + default=lambda x: x.__dict__, + ) + + if on_win: + from ..common._os.windows import run_as_admin + + temp_path = None + try: + with Utf8NamedTemporaryFile("w+", suffix=".json", delete=False) as tf: + # the default mode is 'w+b', and universal new lines don't work in that mode + tf.write(plan_input) + temp_path = tf.name + python_exe = f'"{abspath(sys.executable)}"' + hinstance, error_code = run_as_admin( + (python_exe, "-m", "conda.core.initialize", f'"{temp_path}"') + ) + if error_code is not None: + print( + f"ERROR during elevated execution.\n rc: {error_code}", + file=sys.stderr, + ) + + with open_utf8(temp_path) as fh: + plan_output = ensure_text_type(fh.read()) + + finally: + if temp_path and lexists(temp_path): + rm_rf(temp_path) + + else: + result = subprocess_call( + f"sudo {sys.executable} -m conda.core.initialize", + env={}, + path=os.getcwd(), + stdin=plan_input, + ) + stderr = result.stderr.strip() + if stderr: + print(stderr, file=sys.stderr) + plan_output = result.stdout.strip() + + plan[:] = json.loads(plan_output) + + +def run_plan_from_stdin(): + stdin = sys.stdin.read().strip() + plan = json.loads(stdin) + run_plan(plan) + sys.stdout.write(json.dumps(plan)) + + +def run_plan_from_temp_file(temp_path): + with open_utf8(temp_path) as fh: + plan = json.loads(ensure_text_type(fh.read())) + run_plan(plan) + with open_utf8(temp_path, "w+b") as fh: + fh.write(ensure_binary(json.dumps(plan, ensure_ascii=False))) + + +def print_plan_results(plan, stream=None): + if not stream: + stream = sys.stdout + for step in plan: + print( + "%-14s%s" % (step.get("result"), step["kwargs"]["target_path"]), file=stream + ) + + changed = any(step.get("result") == Result.MODIFIED for step in plan) + if changed: + if context.dry_run: + print( + "\n==> DRY RUN: The above changes would have been made. NO ACTUAL CHANGES WERE MADE. <==\n", + file=stream, + ) + else: + print( + "\n==> For changes to take effect, close and re-open your current shell. <==\n", + file=stream, + ) + else: + if context.dry_run: + print("DRY RUN: No action would have been taken.", file=stream) + else: + print("No action taken.", file=stream) + + +# ##################################################### +# individual operations +# ##################################################### + + +def make_entry_point(target_path, conda_prefix, module, func): + # 'ep' in this function refers to 'entry point' + # target_path: join(conda_prefix, 'bin', 'conda') + conda_ep_path = target_path + + if isfile(conda_ep_path): + with open_utf8(conda_ep_path) as fh: + original_ep_content = fh.read() + else: + original_ep_content = "" + + if on_win: + # no shebang needed on windows + new_ep_content = "" + else: + python_path = join(conda_prefix, get_python_short_path()) + new_ep_content = generate_shebang_for_entry_point( + python_path, with_usr_bin_env=True + ) + + conda_extra = dals( + """ + # Before any more imports, leave cwd out of sys.path for internal 'conda shell.*' commands. + # see https://github.com/conda/conda/issues/6549 + if len(sys.argv) > 1 and sys.argv[1].startswith('shell.') and sys.path and sys.path[0] == '': + # The standard first entry in sys.path is an empty string, + # and os.path.abspath('') expands to os.getcwd(). + del sys.path[0] + """ + ) + + new_ep_content += dals( + """ + # -*- coding: utf-8 -*- + import sys + %(extra)s + if __name__ == '__main__': + from %(module)s import %(func)s + sys.exit(%(func)s()) + """ + ) % { + "extra": conda_extra if module == "conda.cli" else "", + "module": module, + "func": func, + } + + if new_ep_content != original_ep_content: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(original_ep_content, new_ep_content)) + if not context.dry_run: + mkdir_p(dirname(conda_ep_path)) + with open_utf8(conda_ep_path, "w") as fdst: + fdst.write(new_ep_content) + if not on_win: + make_executable(conda_ep_path) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def make_entry_point_exe(target_path, conda_prefix): + # target_path: join(conda_prefix, 'Scripts', 'conda.exe') + exe_path = target_path + bits = 8 * struct.calcsize("P") + source_exe_path = join(CONDA_PACKAGE_ROOT, "shell", "cli-%d.exe" % bits) + if isfile(exe_path): + if compute_sum(exe_path, "md5") == compute_sum(source_exe_path, "md5"): + return Result.NO_CHANGE + + if not context.dry_run: + if not isdir(dirname(exe_path)): + mkdir_p(dirname(exe_path)) + # prefer copy() over create_hard_link_or_copy() because of windows file deletion issues + # with open processes + copy(source_exe_path, exe_path) + return Result.MODIFIED + + +def install_anaconda_prompt(target_path, conda_prefix, reverse): + # target_path: join(conda_prefix, 'condabin', 'Anaconda Prompt.lnk') + # target: join(os.environ["HOMEPATH"], "Desktop", "Anaconda Prompt.lnk") + icon_path = join(CONDA_PACKAGE_ROOT, "shell", "conda_icon.ico") + target = join(os.environ["HOMEPATH"], "Desktop", "Anaconda Prompt.lnk") + + args = ( + "/K", + '""{}" && "{}""'.format( + join(conda_prefix, "condabin", "conda_hook.bat"), + join(conda_prefix, "condabin", "conda_auto_activate.bat"), + ), + ) + # The API for the call to 'create_shortcut' has 3 + # required arguments (path, description, filename) + # and 4 optional ones (args, working_dir, icon_path, icon_index). + result = Result.NO_CHANGE + if not context.dry_run: + create_shortcut( + "%windir%\\System32\\cmd.exe", + "Anconda Prompt", + "" + target_path, + " ".join(args), + "" + expanduser("~"), + "" + icon_path, + ) + result = Result.MODIFIED + if reverse: + if os.path.isfile(target): + os.remove(target) + result = Result.MODIFIED + return result + + +def _install_file(target_path, file_content): + if isfile(target_path): + with open_utf8(target_path) as fh: + original_content = fh.read() + else: + original_content = "" + + new_content = file_content + + if new_content != original_content: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(original_content, new_content)) + if not context.dry_run: + mkdir_p(dirname(target_path)) + with open_utf8(target_path, "w") as fdst: + fdst.write(new_content) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def install_conda_sh(target_path, conda_prefix): + # target_path: join(conda_prefix, 'etc', 'profile.d', 'conda.sh') + file_content = PosixActivator().hook(auto_activate=False) + return _install_file(target_path, file_content) + + +def install_Scripts_activate_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'Scripts', 'activate.bat') + src_path = join(CONDA_PACKAGE_ROOT, "shell", "Scripts", "activate.bat") + with open_utf8(src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_activate_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'condabin', 'activate.bat') + src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "activate.bat") + with open_utf8(src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_deactivate_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'condabin', 'deactivate.bat') + src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "deactivate.bat") + with open_utf8(src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_activate(target_path, conda_prefix): + # target_path: join(conda_prefix, BIN_DIRECTORY, 'activate') + src_path = join(CONDA_PACKAGE_ROOT, "shell", "bin", "activate") + file_content = f'#!/bin/sh\n_CONDA_ROOT="{conda_prefix}"\n' + with open_utf8(src_path) as fsrc: + file_content += fsrc.read() + return _install_file(target_path, file_content) + + +def install_deactivate(target_path, conda_prefix): + # target_path: join(conda_prefix, BIN_DIRECTORY, 'deactivate') + src_path = join(CONDA_PACKAGE_ROOT, "shell", "bin", "deactivate") + file_content = f'#!/bin/sh\n_CONDA_ROOT="{conda_prefix}"\n' + with open_utf8(src_path) as fsrc: + file_content += fsrc.read() + return _install_file(target_path, file_content) + + +def install_condabin_conda_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'condabin', 'conda.bat') + conda_bat_src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "conda.bat") + with open_utf8(conda_bat_src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_library_bin_conda_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'Library', 'bin', 'conda.bat') + conda_bat_src_path = join( + CONDA_PACKAGE_ROOT, "shell", "Library", "bin", "conda.bat" + ) + with open_utf8(conda_bat_src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_condabin_conda_activate_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'condabin', '_conda_activate.bat') + conda_bat_src_path = join( + CONDA_PACKAGE_ROOT, "shell", "condabin", "_conda_activate.bat" + ) + with open_utf8(conda_bat_src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_condabin_rename_tmp_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'condabin', 'rename_tmp.bat') + conda_bat_src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "rename_tmp.bat") + with open_utf8(conda_bat_src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_condabin_conda_auto_activate_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'condabin', 'conda_auto_activate.bat') + conda_bat_src_path = join( + CONDA_PACKAGE_ROOT, "shell", "condabin", "conda_auto_activate.bat" + ) + with open_utf8(conda_bat_src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_condabin_hook_bat(target_path, conda_prefix): + # target_path: join(conda_prefix, 'condabin', 'conda_hook.bat') + conda_bat_src_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "conda_hook.bat") + with open_utf8(conda_bat_src_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_conda_fish(target_path, conda_prefix): + # target_path: join(conda_prefix, 'etc', 'fish', 'conf.d', 'conda.fish') + file_content = FishActivator().hook(auto_activate=False) + return _install_file(target_path, file_content) + + +def install_conda_psm1(target_path, conda_prefix): + # target_path: join(conda_prefix, 'shell', 'condabin', 'Conda.psm1') + conda_psm1_path = join(CONDA_PACKAGE_ROOT, "shell", "condabin", "Conda.psm1") + with open_utf8(conda_psm1_path) as fsrc: + file_content = fsrc.read() + return _install_file(target_path, file_content) + + +def install_conda_hook_ps1(target_path, conda_prefix): + # target_path: join(conda_prefix, 'shell', 'condabin', 'conda-hook.ps1') + file_content = PowerShellActivator().hook(auto_activate=False) + return _install_file(target_path, file_content) + + +def install_conda_xsh(target_path, conda_prefix): + # target_path: join(site_packages_dir, 'xonsh', 'conda.xsh') + file_content = XonshActivator().hook(auto_activate=False) + return _install_file(target_path, file_content) + + +def install_conda_csh(target_path, conda_prefix): + # target_path: join(conda_prefix, 'etc', 'profile.d', 'conda.csh') + file_content = CshActivator().hook(auto_activate=False) + return _install_file(target_path, file_content) + + +def _config_fish_content(conda_prefix): + conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda") + if on_win: + from ..common.path import win_path_to_unix + + conda_exe = win_path_to_unix(conda_exe) + conda_initialize_content = dals( + """ + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + if test -f %(conda_exe)s + eval %(conda_exe)s "shell.fish" "hook" $argv | source + else + if test -f "%(conda_prefix)s/etc/fish/conf.d/conda.fish" + . "%(conda_prefix)s/etc/fish/conf.d/conda.fish" + else + set -x PATH "%(conda_prefix)s/bin" $PATH + end + end + # <<< conda initialize <<< + """ + ) % { + "conda_exe": conda_exe, + "conda_prefix": conda_prefix, + } + return conda_initialize_content + + +def _config_fish_content_to_add_condabin_to_path(conda_prefix): + condabin_dir = join(conda_prefix, "condabin") + if on_win: + from ..common.path import win_path_to_unix + + condabin_dir = win_path_to_unix(condabin_dir) + conda_initialize_content = dals( + f""" + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + set -x PATH "{condabin_dir}" $PATH + # <<< conda initialize <<< + """ + ) + return conda_initialize_content + + +def init_fish_user( + target_path, + conda_prefix, + reverse=False, + content_type: ContentTypeOptions = "initialize", +): + # target_path: ~/.config/config.fish + user_rc_path = target_path + + try: + with open_utf8(user_rc_path) as fh: + rc_content = fh.read() + except FileNotFoundError: + rc_content = "" + except: + raise + + rc_original_content = rc_content + + conda_init_comment = "# commented out by conda initialize" + if content_type == "initialize": + conda_initialize_content = _config_fish_content(conda_prefix) + elif content_type == "add_condabin_to_path": + conda_initialize_content = _config_fish_content_to_add_condabin_to_path( + conda_prefix + ) + else: + raise ValueError( + f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'." + ) + if reverse: + # uncomment any lines that were commented by prior conda init run + rc_content = re.sub( + rf"#\s(.*?)\s*{conda_init_comment}", + r"\1", + rc_content, + flags=re.MULTILINE, + ) + + # remove any conda init sections added + rc_content = re.sub( + r"^\s*" + CONDA_INITIALIZE_RE_BLOCK, + "", + rc_content, + flags=re.DOTALL | re.MULTILINE, + ) + else: + if not on_win: + rc_content = re.sub( + rf"^[ \t]*?(set -gx PATH ([\'\"]?).*?{basename(conda_prefix)}\/bin\2 [^\n]*?\$PATH)" + r"", + rf"# \1 {conda_init_comment}", + rc_content, + flags=re.MULTILINE, + ) + + rc_content = re.sub( + r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/fish\/conf\.d\/conda\.fish.*?)\n" + r"(conda activate.*?)$", + rf"# \1 {conda_init_comment}\n# \2 {conda_init_comment}", + rc_content, + flags=re.MULTILINE, + ) + rc_content = re.sub( + r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/fish\/conda\.d\/conda\.fish.*?)$", + rf"# \1 {conda_init_comment}", + rc_content, + flags=re.MULTILINE, + ) + + replace_str = "__CONDA_REPLACE_ME_123__" + rc_content = re.sub( + CONDA_INITIALIZE_RE_BLOCK, + replace_str, + rc_content, + flags=re.MULTILINE, + ) + # TODO: maybe remove all but last of replace_str, if there's more than one occurrence + rc_content = rc_content.replace(replace_str, conda_initialize_content) + + if "# >>> conda initialize >>>" not in rc_content: + rc_content += f"\n{conda_initialize_content}\n" + + if rc_content != rc_original_content: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(rc_original_content, rc_content)) + if not context.dry_run: + # Make the directory if needed. + if not exists(dirname(user_rc_path)): + mkdir_p(dirname(user_rc_path)) + with open_utf8(user_rc_path, "w") as fh: + fh.write(rc_content) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def _config_xonsh_content(conda_prefix): + conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda") + if on_win: + from ..common.path import win_path_to_unix + + conda_exe = win_path_to_unix(conda_exe) + conda_initialize_content = dals( + """ + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + if !(test -f "{conda_exe}"): + import sys as _sys + from types import ModuleType as _ModuleType + _mod = _ModuleType("xontrib.conda", + "Autogenerated from $({conda_exe} shell.xonsh hook)") + __xonsh__.execer.exec($("{conda_exe}" "shell.xonsh" "hook"), + glbs=_mod.__dict__, + filename="$({conda_exe} shell.xonsh hook)") + _sys.modules["xontrib.conda"] = _mod + del _sys, _mod, _ModuleType + # <<< conda initialize <<< + """ + ).format(conda_exe=conda_exe) + return conda_initialize_content + + +def _config_xonsh_content_to_add_condabin_to_path(conda_prefix): + condabin_path = join(conda_prefix, "condabin") + if on_win: + from ..common.path import win_path_to_unix + + condabin_path = win_path_to_unix(condabin_path) + return dals( + f""" + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + $PATH.insert(0, "{condabin_path}") + # <<< conda initialize <<< + """ + ) + + +def init_xonsh_user( + target_path, + conda_prefix, + reverse=False, + content_type: ContentTypeOptions = "initialize", +): + # target_path: ~/.xonshrc + user_rc_path = target_path + + try: + with open_utf8(user_rc_path) as fh: + rc_content = fh.read() + except FileNotFoundError: + rc_content = "" + except: + raise + + rc_original_content = rc_content + + conda_init_comment = "# commented out by conda initialize" + if content_type == "initialize": + conda_initialize_content = _config_xonsh_content(conda_prefix) + elif content_type == "add_condabin_to_path": + conda_initialize_content = _config_xonsh_content_to_add_condabin_to_path( + conda_prefix + ) + else: + raise ValueError( + f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'." + ) + if reverse: + # uncomment any lines that were commented by prior conda init run + rc_content = re.sub( + rf"#\s(.*?)\s*{conda_init_comment}", + r"\1", + rc_content, + flags=re.MULTILINE, + ) + + # remove any conda init sections added + rc_content = re.sub( + r"^\s*" + CONDA_INITIALIZE_RE_BLOCK, + "", + rc_content, + flags=re.DOTALL | re.MULTILINE, + ) + else: + replace_str = "__CONDA_REPLACE_ME_123__" + rc_content = re.sub( + CONDA_INITIALIZE_RE_BLOCK, + replace_str, + rc_content, + flags=re.MULTILINE, + ) + # TODO: maybe remove all but last of replace_str, if there's more than one occurrence + rc_content = rc_content.replace(replace_str, conda_initialize_content) + + if "# >>> conda initialize >>>" not in rc_content: + rc_content += f"\n{conda_initialize_content}\n" + + if rc_content != rc_original_content: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(rc_original_content, rc_content)) + if not context.dry_run: + # Make the directory if needed. + if not exists(dirname(user_rc_path)): + mkdir_p(dirname(user_rc_path)) + with open_utf8(user_rc_path, "w") as fh: + fh.write(rc_content) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def _bashrc_content(conda_prefix, shell): + conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda") + if on_win: + from ..common.path import win_path_to_unix + + conda_exe = win_path_to_unix(conda_exe) + conda_initialize_content = dals( + """ + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + if [ -f '%(conda_exe)s' ]; then + eval "$('%(conda_exe)s' 'shell.%(shell)s' 'hook')" + fi + # <<< conda initialize <<< + """ + ) % { + "conda_exe": conda_exe, + "shell": shell, + } + else: + if shell in ("csh", "tcsh"): + conda_initialize_content = dals( + """ + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + if ( -f "%(conda_prefix)s/etc/profile.d/conda.csh" ) then + source "%(conda_prefix)s/etc/profile.d/conda.csh" + else + setenv PATH "%(conda_bin)s:$PATH" + endif + # <<< conda initialize <<< + """ + ) % { + "conda_exe": conda_exe, + "shell": shell, + "conda_bin": dirname(conda_exe), + "conda_prefix": conda_prefix, + } + else: + conda_initialize_content = dals( + """ + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + __conda_setup="$('%(conda_exe)s' 'shell.%(shell)s' 'hook' 2> /dev/null)" + if [ $? -eq 0 ]; then + eval "$__conda_setup" + else + if [ -f "%(conda_prefix)s/etc/profile.d/conda.sh" ]; then + . "%(conda_prefix)s/etc/profile.d/conda.sh" + else + export PATH="%(conda_bin)s:$PATH" + fi + fi + unset __conda_setup + # <<< conda initialize <<< + """ + ) % { + "conda_exe": conda_exe, + "shell": shell, + "conda_bin": dirname(conda_exe), + "conda_prefix": conda_prefix, + } + return conda_initialize_content + + +def _bashrc_content_to_add_condabin_to_path(conda_prefix, shell): + condabin_path = join(conda_prefix, "condabin") + if on_win: + from ..common.path import win_path_to_unix + + condabin_path = win_path_to_unix(condabin_path) + return dals( + f""" + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + if [ -d '{condabin_path}' ]; then + export PATH="{condabin_path}:$PATH" + fi + # <<< conda initialize <<< + """ + ) + if shell in ("csh", "tcsh"): + return dals( + f""" + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + if ( -d "{condabin_path}" ) then + setenv PATH "{condabin_path}:$PATH" + endif + # <<< conda initialize <<< + """ + ) + return dals( + f""" + # >>> conda initialize >>> + # !! Contents within this block are managed by 'conda init' !! + export PATH="{condabin_path}:$PATH" + # <<< conda initialize <<< + """ + ) + + +def init_sh_user( + target_path, + conda_prefix, + shell, + reverse=False, + content_type: ContentTypeOptions = "initialize", +): + # target_path: ~/.bash_profile + user_rc_path = target_path + + try: + with open_utf8(user_rc_path) as fh: + rc_content = fh.read() + except FileNotFoundError: + rc_content = "" + except: + raise + + rc_original_content = rc_content + + if content_type == "initialize": + conda_initialize_content = _bashrc_content(conda_prefix, shell) + elif content_type == "add_condabin_to_path": + conda_initialize_content = _bashrc_content_to_add_condabin_to_path( + conda_prefix, shell + ) + else: + raise ValueError( + f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'." + ) + + conda_init_comment = "# commented out by conda initialize" + + if reverse: + # uncomment any lines that were commented by prior conda init run + rc_content = re.sub( + rf"#\s(.*?)\s*{conda_init_comment}", + r"\1", + rc_content, + flags=re.MULTILINE, + ) + + # remove any conda init sections added + rc_content = re.sub( + r"^\s*" + CONDA_INITIALIZE_RE_BLOCK, + "", + rc_content, + flags=re.DOTALL | re.MULTILINE, + ) + else: + if not on_win: + rc_content = re.sub( + rf"^[ \t]*?(export PATH=[\'\"].*?{basename(conda_prefix)}\/bin:\$PATH[\'\"])" + r"", + rf"# \1 {conda_init_comment}", + rc_content, + flags=re.MULTILINE, + ) + + rc_content = re.sub( + r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/profile\.d\/conda\.sh.*?)\n" + r"(conda activate.*?)$", + rf"# \1 {conda_init_comment}\n# \2 {conda_init_comment}", + rc_content, + flags=re.MULTILINE, + ) + rc_content = re.sub( + r"^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*etc\/profile\.d\/conda\.sh.*?)$", + rf"# \1 {conda_init_comment}", + rc_content, + flags=re.MULTILINE, + ) + + if on_win: + rc_content = re.sub( + r"^[ \t]*^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*Scripts[/\\]activate.*?)$", + r"# \1 # commented out by conda initialize", + rc_content, + flags=re.MULTILINE, + ) + else: + rc_content = re.sub( + r"^[ \t]*^[ \t]*[^#\n]?[ \t]*((?:source|\.) .*bin/activate.*?)$", + r"# \1 # commented out by conda initialize", + rc_content, + flags=re.MULTILINE, + ) + + replace_str = "__CONDA_REPLACE_ME_123__" + rc_content = re.sub( + CONDA_INITIALIZE_RE_BLOCK, + replace_str, + rc_content, + flags=re.MULTILINE, + ) + # TODO: maybe remove all but last of replace_str, if there's more than one occurrence + rc_content = rc_content.replace(replace_str, conda_initialize_content) + + if "# >>> conda initialize >>>" not in rc_content: + rc_content += f"\n{conda_initialize_content}\n" + + if rc_content != rc_original_content: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(rc_original_content, rc_content)) + if not context.dry_run: + with open_utf8(user_rc_path, "w") as fh: + fh.write(rc_content) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def init_sh_system( + target_path, + conda_prefix, + reverse=False, + content_type: ContentTypeOptions = "initialize", +): + # target_path: '/etc/profile.d/conda.sh' + conda_sh_system_path = target_path + + if exists(conda_sh_system_path): + with open_utf8(conda_sh_system_path) as fh: + conda_sh_system_contents = fh.read() + else: + conda_sh_system_contents = "" + if reverse: + if exists(conda_sh_system_path): + os.remove(conda_sh_system_path) + return Result.MODIFIED + else: + if content_type == "initialize": + conda_sh_contents = _bashrc_content(conda_prefix, "posix") + elif content_type == "add_condabin_to_path": + conda_sh_contents = _bashrc_content_to_add_condabin_to_path( + conda_prefix, "posix" + ) + else: + raise ValueError( + f"Unknown content_type='{content_type}'. " + "Use 'initialize' or 'add_condabin_to_path'." + ) + if conda_sh_system_contents != conda_sh_contents: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(conda_sh_contents, conda_sh_system_contents)) + if not context.dry_run: + if lexists(conda_sh_system_path): + rm_rf(conda_sh_system_path) + mkdir_p(dirname(conda_sh_system_path)) + with open_utf8(conda_sh_system_path, "w") as fh: + fh.write(conda_sh_contents) + return Result.MODIFIED + return Result.NO_CHANGE + + +def _read_windows_registry(target_path): # pragma: no cover + # HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun + # HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun + # returns value_value, value_type -or- None, None if target does not exist + main_key, the_rest = target_path.split("\\", 1) + subkey_str, value_name = the_rest.rsplit("\\", 1) + main_key = getattr(winreg, main_key) + + try: + key = winreg.OpenKey(main_key, subkey_str, 0, winreg.KEY_READ) + except OSError as e: + if e.errno != ENOENT: + raise + return None, None + + try: + value_tuple = winreg.QueryValueEx(key, value_name) + value_value = value_tuple[0] + if isinstance(value_value, str): + value_value = value_value.strip() + value_type = value_tuple[1] + return value_value, value_type + except Exception: + # [WinError 2] The system cannot find the file specified + winreg.CloseKey(key) + return None, None + finally: + winreg.CloseKey(key) + + +def _write_windows_registry(target_path, value_value, value_type): # pragma: no cover + main_key, the_rest = target_path.split("\\", 1) + subkey_str, value_name = the_rest.rsplit("\\", 1) + main_key = getattr(winreg, main_key) + try: + key = winreg.OpenKey(main_key, subkey_str, 0, winreg.KEY_WRITE) + except OSError as e: + if e.errno != ENOENT: + raise + key = winreg.CreateKey(main_key, subkey_str) + try: + winreg.SetValueEx(key, value_name, 0, value_type, value_value) + finally: + winreg.CloseKey(key) + + +def init_cmd_exe_registry(target_path, conda_prefix, reverse=False): + # HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun + # HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun + + prev_value, value_type = _read_windows_registry(target_path) + if prev_value is None: + prev_value = "" + value_type = winreg.REG_EXPAND_SZ + + old_hook_path = '"{}"'.format(join(conda_prefix, "condabin", "conda_hook.bat")) + new_hook = f"if exist {old_hook_path} {old_hook_path}" + if reverse: + # we can't just reset it to None and remove it, because there may be other contents here. + # We need to strip out our part, and if there's nothing left, remove the key. + # Break up string by parts joined with "&" + autorun_parts = prev_value.split("&") + autorun_parts = [part.strip() for part in autorun_parts if new_hook not in part] + # We must remove the old hook path too if it is there + autorun_parts = [ + part.strip() for part in autorun_parts if old_hook_path not in part + ] + new_value = " & ".join(autorun_parts) + else: + replace_str = "__CONDA_REPLACE_ME_123__" + # Replace new (if exist checked) hook + new_value = re.sub( + r"(if exist \"[^\"]*?conda[-_]hook\.bat\" \"[^\"]*?conda[-_]hook\.bat\")", + replace_str, + prev_value, + count=1, + flags=re.IGNORECASE | re.UNICODE, + ) + # Replace old hook + new_value = re.sub( + r"(\"[^\"]*?conda[-_]hook\.bat\")", + replace_str, + new_value, + flags=re.IGNORECASE | re.UNICODE, + ) + + # Fold repeats of 'HOOK & HOOK' + new_value_2 = new_value.replace(replace_str + " & " + replace_str, replace_str) + while new_value_2 != new_value: + new_value = new_value_2 + new_value_2 = new_value.replace( + replace_str + " & " + replace_str, replace_str + ) + new_value = new_value_2.replace(replace_str, new_hook) + if new_hook not in new_value: + if new_value: + new_value += " & " + new_hook + else: + new_value = new_hook + + if prev_value != new_value: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(prev_value, new_value)) + if not context.dry_run: + _write_windows_registry(target_path, new_value, value_type) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def add_condabin_to_path_registry(target_path, conda_prefix, reverse=False): + # Modifies the PATH environment variable stored in the Windows registry. + # target_path examples: + # - HKEY_CURRENT_USER\Environment\PATH + # - HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PATH + + prev_value, value_type = _read_windows_registry(target_path) + if prev_value is None: + prev_value = "" + # PATH is typically REG_EXPAND_SZ, allowing variables like %SystemRoot% + value_type = 2 # winreg.REG_EXPAND_SZ + + # The Windows registry always wants backslashes! + condabin_path = join(conda_prefix, "condabin").replace("/", "\\") + # Normalize for case-insensitive comparison, though registry might preserve case + normalized_condabin_path = condabin_path.lower() + + # Split PATH, handling potential empty strings from leading/trailing/double semicolons + path_parts = [part for part in prev_value.split(";") if part.strip()] + normalized_path_parts = [part.lower() for part in path_parts] + + if reverse: + # Remove condabin_path if present + new_path_parts = [ + part + for part, normalized_part in zip(path_parts, normalized_path_parts) + if normalized_part != normalized_condabin_path + ] + new_value = ";".join(new_path_parts) + else: + # Add condabin_path if not already present (typically at the beginning) + if normalized_condabin_path not in normalized_path_parts: + # Prepend condabin_path + path_parts.insert(0, condabin_path) + new_value = ";".join(path_parts) + + if prev_value != new_value: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(prev_value, new_value)) + if not context.dry_run: + _write_windows_registry(target_path, new_value, value_type) + # Notify the system about the environment change (requires user logoff/logon or restart for full effect) + # This part is complex and might require ctypes/pywin32 calls to SendMessageTimeout with HWND_BROADCAST + # For simplicity, we'll rely on the message printed by print_plan_results + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def init_long_path(target_path): + win_ver, _, win_rev = context.os_distribution_name_version[1].split(".") + # win10, build 14352 was the first preview release that supported this + if int(win_ver) >= 10 and int(win_rev) >= 14352: + prev_value, value_type = _read_windows_registry(target_path) + if str(prev_value) != "1": + if context.verbose: + print("\n") + print(target_path) + print(make_diff(str(prev_value), "1")) + if not context.dry_run: + _write_windows_registry(target_path, 1, winreg.REG_DWORD) + return Result.MODIFIED + else: + return Result.NO_CHANGE + else: + if context.verbose: + print("\n") + print( + "Not setting long path registry key; Windows version must be at least 10 with " + 'the fall 2016 "Anniversary update" or newer.' + ) + return Result.NO_CHANGE + + +def _powershell_profile_content(conda_prefix): + conda_exe = join(conda_prefix, BIN_DIRECTORY, "conda.exe" if on_win else "conda") + + conda_powershell_module = dals( + f""" + #region conda initialize + # !! Contents within this block are managed by 'conda init' !! + If (Test-Path "{conda_exe}") {{ + (& "{conda_exe}" "shell.powershell" "hook") | Out-String | ?{{$_}} | Invoke-Expression + }} + #endregion + """ + ) + + return conda_powershell_module + + +def _powershell_profile_content_to_add_condabin_to_path(conda_prefix): + condabin_dir = join(conda_prefix, "condabin") + + return dals( + f""" + #region conda initialize + # !! Contents within this block are managed by 'conda init' !! + $Env:Path = "{condabin_dir}" + [IO.Path]::PathSeparator + $Env:Path + #endregion + """ + ) + + +def init_powershell_user( + target_path, + conda_prefix, + reverse=False, + content_type: ContentTypeOptions = "initialize", +): + # target_path: $PROFILE + profile_path = target_path + + # NB: the user may not have created a profile. We need to check + # if the file exists first. + if os.path.exists(profile_path): + with open_utf8(profile_path) as fp: + profile_content = fp.read() + else: + profile_content = "" + + profile_original_content = profile_content + + # TODO: comment out old ipmos and Import-Modules. + + if reverse: + profile_content = re.sub( + CONDA_INITIALIZE_PS_RE_BLOCK, + "", + profile_content, + count=1, + flags=re.DOTALL | re.MULTILINE, + ) + else: + # Find what content we need to add. + if content_type == "initialize": + conda_initialize_content = _powershell_profile_content(conda_prefix) + elif content_type == "add_condabin_to_path": + conda_initialize_content = ( + _powershell_profile_content_to_add_condabin_to_path(conda_prefix) + ) + else: + raise ValueError( + f"Unknown content_type='{content_type}'. Use 'initialize' or 'add_condabin_to_path'." + ) + + if "#region conda initialize" not in profile_content: + profile_content += f"\n{conda_initialize_content}\n" + else: + profile_content = re.sub( + CONDA_INITIALIZE_PS_RE_BLOCK, + "__CONDA_REPLACE_ME_123__", + profile_content, + count=1, + flags=re.DOTALL | re.MULTILINE, + ).replace("__CONDA_REPLACE_ME_123__", conda_initialize_content) + + if profile_content != profile_original_content: + if context.verbose: + print("\n") + print(target_path) + print(make_diff(profile_original_content, profile_content)) + if not context.dry_run: + # Make the directory if needed. + if not exists(dirname(profile_path)): + mkdir_p(dirname(profile_path)) + with open_utf8(profile_path, "w") as fp: + fp.write(profile_content) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def remove_conda_in_sp_dir(target_path): + # target_path: site_packages_dir + modified = False + site_packages_dir = target_path + rm_rf_these = chain.from_iterable( + ( + glob(join(site_packages_dir, "conda-*info")), + glob(join(site_packages_dir, "conda.*")), + glob(join(site_packages_dir, "conda-*.egg")), + ) + ) + rm_rf_these = (p for p in rm_rf_these if not p.endswith("conda.egg-link")) + for fn in rm_rf_these: + print(f"rm -rf {join(site_packages_dir, fn)}", file=sys.stderr) + if not context.dry_run: + rm_rf(join(site_packages_dir, fn)) + modified = True + others = ( + "conda", + "conda_env", + ) + for other in others: + path = join(site_packages_dir, other) + if lexists(path): + print(f"rm -rf {path}", file=sys.stderr) + if not context.dry_run: + rm_rf(path) + modified = True + if modified: + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def make_conda_egg_link(target_path, conda_source_root): + # target_path: join(site_packages_dir, 'conda.egg-link') + conda_egg_link_contents = conda_source_root + os.linesep + + if isfile(target_path): + with open_utf8(target_path, "rb") as fh: + conda_egg_link_contents_old = fh.read() + else: + conda_egg_link_contents_old = "" + + if conda_egg_link_contents_old != conda_egg_link_contents: + if context.verbose: + print("\n", file=sys.stderr) + print(target_path, file=sys.stderr) + print( + make_diff(conda_egg_link_contents_old, conda_egg_link_contents), + file=sys.stderr, + ) + if not context.dry_run: + with open_utf8(target_path, "wb") as fh: + fh.write(ensure_utf8_encoding(conda_egg_link_contents)) + return Result.MODIFIED + else: + return Result.NO_CHANGE + + +def modify_easy_install_pth(target_path, conda_source_root): + # target_path: join(site_packages_dir, 'easy-install.pth') + easy_install_new_line = conda_source_root + + if isfile(target_path): + with open_utf8(target_path) as fh: + old_contents = fh.read() + else: + old_contents = "" + + old_contents_lines = old_contents.splitlines() + if easy_install_new_line in old_contents_lines: + return Result.NO_CHANGE + + ln_end = os.sep + "conda" + old_contents_lines = tuple( + ln for ln in old_contents_lines if not ln.endswith(ln_end) + ) + new_contents = ( + easy_install_new_line + + os.linesep + + os.linesep.join(old_contents_lines) + + os.linesep + ) + + if context.verbose: + print("\n", file=sys.stderr) + print(target_path, file=sys.stderr) + print(make_diff(old_contents, new_contents), file=sys.stderr) + if not context.dry_run: + with open_utf8(target_path, "wb") as fh: + fh.write(ensure_utf8_encoding(new_contents)) + return Result.MODIFIED + + +def make_dev_egg_info_file(target_path): + # target_path: join(conda_source_root, 'conda.egg-info') + + if isfile(target_path): + with open_utf8(target_path) as fh: + old_contents = fh.read() + else: + old_contents = "" + + new_contents = ( + dals( + """ + Metadata-Version: 1.1 + Name: conda + Version: %s + Platform: UNKNOWN + Summary: OS-agnostic, system-level binary package manager. + """ + ) + % CONDA_VERSION + ) + + if old_contents == new_contents: + return Result.NO_CHANGE + + if context.verbose: + print("\n", file=sys.stderr) + print(target_path, file=sys.stderr) + print(make_diff(old_contents, new_contents), file=sys.stderr) + if not context.dry_run: + if lexists(target_path): + rm_rf(target_path) + with open_utf8(target_path, "w") as fh: + fh.write(new_contents) + return Result.MODIFIED + + +# ##################################################### +# helper functions +# ##################################################### + + +def make_diff(old, new): + return "\n".join(unified_diff(old.splitlines(), new.splitlines())) + + +def _get_python_info(prefix): + python_exe = join(prefix, get_python_short_path()) + result = subprocess_call(f"{python_exe} --version") + stdout, stderr = result.stdout.strip(), result.stderr.strip() + if stderr: + python_version = stderr.split()[1] + elif stdout: # pragma: no cover + python_version = stdout.split()[1] + else: # pragma: no cover + raise ValueError("No python version information available.") + + site_packages_dir = join( + prefix, win_path_ok(get_python_site_packages_short_path(python_version)) + ) + return python_exe, python_version, site_packages_dir + + +if __name__ == "__main__": + if on_win: + temp_path = sys.argv[1] + run_plan_from_temp_file(temp_path) + else: + run_plan_from_stdin() diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/link.py b/miniconda3/lib/python3.13/site-packages/conda/core/link.py new file mode 100644 index 0000000000000000000000000000000000000000..06dfe02255339ffacd2ba0e9ace9fdee73230a3d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/link.py @@ -0,0 +1,1710 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Package installation implemented as a series of link/unlink transactions.""" + +from __future__ import annotations # noqa: I001 + +from dataclasses import dataclass, fields +import itertools +import os +import sys +import warnings +from collections import defaultdict +from itertools import chain +from logging import getLogger +from os.path import basename, dirname, isdir, join +from pathlib import Path +from textwrap import indent +from traceback import format_exception_only +from typing import TYPE_CHECKING, NamedTuple + +from .. import CondaError, CondaMultiError, conda_signal_handler +from ..auxlib.collection import first +from ..auxlib.ish import dals +from ..base.constants import DEFAULTS_CHANNEL_NAME, PREFIX_MAGIC_FILE, SafetyChecks +from ..base.context import context +from ..common.compat import ensure_text_type, on_win +from ..common.io import ( + DummyExecutor, + ThreadLimitedThreadPoolExecutor, + dashlist, + time_recorder, +) +from ..common.path import ( + BIN_DIRECTORY, + explode_directories, + get_all_directories, + get_major_minor_version, + get_python_site_packages_short_path, +) +from ..common.signals import signal_handler +from ..deprecations import deprecated +from ..exceptions import ( + CondaSystemExit, + DisallowedPackageError, + EnvironmentNotWritableError, + KnownPackageClobberError, + LinkError, + RemoveError, + SharedLinkPathClobberError, + SpecNotFoundInPackageCache, + UnknownPackageClobberError, + maybe_raise, +) +from ..gateways.disk import mkdir_p +from ..gateways.disk.delete import rm_rf +from ..gateways.disk.read import isfile, lexists, read_package_info +from ..gateways.disk.test import ( + hardlink_supported, + softlink_supported, +) +from ..gateways.subprocess import subprocess_call +from ..models.enums import LinkType +from ..models.version import VersionOrder +from ..reporters import confirm_yn, get_spinner +from ..resolve import MatchSpec +from ..utils import get_comspec, human_bytes, wrap_subprocess_call +from .package_cache_data import PackageCacheData +from .path_actions import ( + AggregateCompileMultiPycAction, + CompileMultiPycAction, + CreatePrefixRecordAction, + CreatePythonEntryPointAction, + LinkPathAction, + MakeMenuAction, + RegisterEnvironmentLocationAction, + RemoveLinkedPackageRecordAction, + RemoveMenuAction, + UnlinkPathAction, + UnregisterEnvironmentLocationAction, + UpdateHistoryAction, +) +from .prefix_data import PrefixData + +if TYPE_CHECKING: + from collections.abc import Generator, Iterable + + from ..models.package_info import PackageInfo + from ..models.records import PackageRecord + from .path_actions import Action + +log = getLogger(__name__) + + +def determine_link_type(extracted_package_dir, target_prefix): + source_test_file = join(extracted_package_dir, "info", "index.json") + if context.always_copy: + return LinkType.copy + if context.always_softlink: + return LinkType.softlink + if hardlink_supported(source_test_file, target_prefix): + return LinkType.hardlink + if context.allow_softlinks and softlink_supported(source_test_file, target_prefix): + return LinkType.softlink + return LinkType.copy + + +def make_unlink_actions(transaction_context, target_prefix, prefix_record): + # no side effects in this function! + unlink_path_actions = tuple( + UnlinkPathAction(transaction_context, prefix_record, target_prefix, trgt) + for trgt in prefix_record.files + ) + + try: + extracted_package_dir = basename(prefix_record.extracted_package_dir) + except AttributeError: + try: + extracted_package_dir = basename(prefix_record.link.source) + except AttributeError: + # for backward compatibility only + extracted_package_dir = ( + f"{prefix_record.name}-{prefix_record.version}-{prefix_record.build}" + ) + + meta_short_path = "{}/{}".format("conda-meta", extracted_package_dir + ".json") + remove_conda_meta_actions = ( + RemoveLinkedPackageRecordAction( + transaction_context, prefix_record, target_prefix, meta_short_path + ), + ) + + _all_d = get_all_directories(axn.target_short_path for axn in unlink_path_actions) + all_directories = sorted(explode_directories(_all_d), reverse=True) + directory_remove_actions = tuple( + UnlinkPathAction( + transaction_context, prefix_record, target_prefix, d, LinkType.directory + ) + for d in all_directories + ) + + # unregister_private_package_actions = UnregisterPrivateEnvAction.create_actions( + # transaction_context, package_cache_record, target_prefix + # ) + + return ( + *unlink_path_actions, + *directory_remove_actions, + # *unregister_private_package_actions, + *remove_conda_meta_actions, + ) + + +def match_specs_to_dists(packages_info_to_link, specs): + matched_specs = [None for _ in range(len(packages_info_to_link))] + for spec in specs or (): + spec = MatchSpec(spec) + idx = next( + ( + q + for q, pkg_info in enumerate(packages_info_to_link) + if pkg_info.repodata_record.name == spec.name + ), + None, + ) + if idx is not None: + matched_specs[idx] = spec + return tuple(matched_specs) + + +class PrefixSetup(NamedTuple): + target_prefix: str + unlink_precs: tuple[PackageRecord, ...] + link_precs: tuple[PackageRecord, ...] + remove_specs: tuple[MatchSpec, ...] + update_specs: tuple[MatchSpec, ...] + neutered_specs: tuple[MatchSpec, ...] + + +class ActionGroup(NamedTuple): + type: str + pkg_data: PackageInfo | None + actions: Iterable[Action] + target_prefix: str + + +@deprecated( + "25.9", + "26.3", + addendum="PrefixActions will be renamed to PrefixActionGroup in 26.3.", +) +@dataclass +class PrefixActions: + """A container for groups of actions carried out during an UnlinkLinkTransaction. + + :param remove_menu_action_groups: Actions which remove menu items + :param unlink_action_groups: Actions which unlink files + :param unregister_action_groups: Actions which unregister environment locations + :param link_action_groups: Actions which link files + :param register_action_groups: Actions which register environment locations + :param compile_action_groups: Actions which compile pyc files + :param make_menu_action_groups: Actions which create menu items + :param entry_point_action_groups: Actions which create python entry points + :param prefix_record_groups: Actions which create package json files in ``conda-meta/`` + :param initial_action_groups: User-defined actions which run before all other actions + :param final_action_groups: User-defined actions which run after all other actions + """ + + remove_menu_action_groups: Iterable[ActionGroup] + unlink_action_groups: Iterable[ActionGroup] + unregister_action_groups: Iterable[ActionGroup] + link_action_groups: Iterable[ActionGroup] + register_action_groups: Iterable[ActionGroup] + compile_action_groups: Iterable[ActionGroup] + make_menu_action_groups: Iterable[ActionGroup] + entry_point_action_groups: Iterable[ActionGroup] + prefix_record_groups: Iterable[ActionGroup] + initial_action_groups: Iterable[ActionGroup] = () + final_action_groups: Iterable[ActionGroup] = () + + def __iter__(self) -> Generator[Iterable[ActionGroup], None, None]: + for field in fields(self): + yield getattr(self, field.name) + + +@deprecated("25.9", "26.3", addendum="Use PrefixActions instead.") +class PrefixActionGroup(NamedTuple): + remove_menu_action_groups: Iterable[ActionGroup] + unlink_action_groups: Iterable[ActionGroup] + unregister_action_groups: Iterable[ActionGroup] + link_action_groups: Iterable[ActionGroup] + register_action_groups: Iterable[ActionGroup] + compile_action_groups: Iterable[ActionGroup] + make_menu_action_groups: Iterable[ActionGroup] + entry_point_action_groups: Iterable[ActionGroup] + prefix_record_groups: Iterable[ActionGroup] + + +class ChangeReport(NamedTuple): + prefix: str + specs_to_remove: Iterable[MatchSpec] + specs_to_add: Iterable[MatchSpec] + removed_precs: Iterable[PackageRecord] + new_precs: Iterable[PackageRecord] + updated_precs: Iterable[PackageRecord] + downgraded_precs: Iterable[PackageRecord] + superseded_precs: Iterable[PackageRecord] + fetch_precs: Iterable[PackageRecord] + revised_precs: Iterable[PackageRecord] + + +class UnlinkLinkTransaction: + def __init__(self, *setups): + self.prefix_setups = {stp.target_prefix: stp for stp in setups} + self.prefix_action_groups = {} + + for stp in self.prefix_setups.values(): + log.info( + "initializing UnlinkLinkTransaction with\n" + " target_prefix: %s\n" + " unlink_precs:\n" + " %s\n" + " link_precs:\n" + " %s\n", + stp.target_prefix, + "\n ".join(prec.dist_str() for prec in stp.unlink_precs), + "\n ".join(prec.dist_str() for prec in stp.link_precs), + ) + + self._pfe = None + self._prepared = False + self._verified = False + # this can be CPU-bound. Use ProcessPoolExecutor. + self.verify_executor = ( + DummyExecutor() + if context.debug or context.verify_threads == 1 + else ThreadLimitedThreadPoolExecutor(context.verify_threads) + ) + # this is more I/O bound. Use ThreadPoolExecutor. + self.execute_executor = ( + DummyExecutor() + if context.debug or context.execute_threads == 1 + else ThreadLimitedThreadPoolExecutor(context.execute_threads) + ) + + @property + def nothing_to_do(self): + return not any( + (stp.unlink_precs or stp.link_precs) for stp in self.prefix_setups.values() + ) and all( + PrefixData(stp.target_prefix).is_environment() + for stp in self.prefix_setups.values() + ) + + def download_and_extract(self): + if self._pfe is None: + self._get_pfe() + if not self._pfe._executed: + self._pfe.execute() + + def prepare(self): + if self._pfe is None: + self._get_pfe() + if not self._pfe._executed: + self._pfe.execute() + + if self._prepared: + return + + self.transaction_context = {} + + with get_spinner("Preparing transaction"): + for stp in self.prefix_setups.values(): + self.prefix_action_groups[stp.target_prefix] = self._prepare( + self.transaction_context, + stp.target_prefix, + stp.unlink_precs, + stp.link_precs, + stp.remove_specs, + stp.update_specs, + stp.neutered_specs, + ) + + self._prepared = True + + @time_recorder("unlink_link_prepare_and_verify") + def verify(self): + if not self._prepared: + self.prepare() + + if context.dry_run: + raise RuntimeError("Cannot execute .verify() with dry-run enabled.") + + if context.safety_checks == SafetyChecks.disabled: + self._verified = True + return + + with get_spinner("Verifying transaction"): + exceptions = self._verify(self.prefix_setups, self.prefix_action_groups) + if exceptions: + try: + maybe_raise(CondaMultiError(exceptions), context) + except: + rm_rf(self.transaction_context["temp_dir"]) + raise + log.info(exceptions) + try: + self._verify_pre_link_message( + itertools.chain( + *( + act.link_action_groups + for act in self.prefix_action_groups.values() + ) + ) + ) + except CondaSystemExit: + rm_rf(self.transaction_context["temp_dir"]) + raise + self._verified = True + + def _verify_pre_link_message(self, all_link_groups): + flag_pre_link = False + for act in all_link_groups: + prelink_msg_dir = ( + Path(act.pkg_data.extracted_package_dir) / "info" / "prelink_messages" + ) + all_msg_subdir = list( + item for item in prelink_msg_dir.glob("**/*") if item.is_file() + ) + if prelink_msg_dir.is_dir() and all_msg_subdir: + print("\n\nThe following PRELINK MESSAGES are INCLUDED:\n\n") + flag_pre_link = True + + for msg_file in all_msg_subdir: + print(f" File {msg_file.name}:\n") + print(indent(msg_file.read_text(), " ")) + print() + if flag_pre_link: + confirm_yn() + + def execute(self): + if not self._verified: + self.verify() + + if context.dry_run: + raise RuntimeError("Cannot run .execute() with dry-run enabled.") + + try: + # innermost dict.values() is an iterable of PrefixActions + # instances; zip() is an iterable of each PrefixActions + self._execute( + tuple(chain(*chain(*zip(*self.prefix_action_groups.values())))) + ) + finally: + rm_rf(self.transaction_context["temp_dir"]) + + def _get_pfe(self): + from .package_cache_data import ProgressiveFetchExtract + + if self._pfe is not None: + pfe = self._pfe + elif not self.prefix_setups: + self._pfe = pfe = ProgressiveFetchExtract(()) + else: + link_precs = set( + chain.from_iterable( + stp.link_precs for stp in self.prefix_setups.values() + ) + ) + self._pfe = pfe = ProgressiveFetchExtract(link_precs) + return pfe + + @classmethod + def _prepare( + cls, + transaction_context, + target_prefix, + unlink_precs, + link_precs, + remove_specs, + update_specs, + neutered_specs, + ): + # make sure prefix directory exists + if not isdir(target_prefix): + try: + mkdir_p(target_prefix) + except OSError as e: + log.debug(repr(e)) + raise CondaError( + f"Unable to create prefix directory '{target_prefix}'.\n" + "Check that you have sufficient permissions." + "" + ) + + # gather information from disk and caches + prefix_data = PrefixData(target_prefix) + prefix_recs_to_unlink = (prefix_data.get(prec.name) for prec in unlink_precs) + # NOTE: load_meta can return None + # TODO: figure out if this filter shouldn't be an assert not None + prefix_recs_to_unlink = tuple(lpd for lpd in prefix_recs_to_unlink if lpd) + pkg_cache_recs_to_link = tuple( + PackageCacheData.get_entry_to_link(prec) for prec in link_precs + ) + if not all(pkg_cache_recs_to_link): + raise SpecNotFoundInPackageCache("Some records cannot be found in cache.") + packages_info_to_link = tuple( + read_package_info(prec, pcrec) + for prec, pcrec in zip(link_precs, pkg_cache_recs_to_link) + ) + + link_types = tuple( + determine_link_type(pkg_info.extracted_package_dir, target_prefix) + for pkg_info in packages_info_to_link + ) + + # make all the path actions + # no side effects allowed when instantiating these action objects + python_version, python_site_packages = cls._get_python_info( + target_prefix, + prefix_recs_to_unlink, + packages_info_to_link, + ) + transaction_context["target_python_version"] = python_version + transaction_context["target_site_packages_short_path"] = python_site_packages + transaction_context["temp_dir"] = join(target_prefix, ".condatmp") + + remove_menu_action_groups = [] + unlink_action_groups = [] + for prefix_rec in prefix_recs_to_unlink: + unlink_action_groups.append( + ActionGroup( + "unlink", + prefix_rec, + make_unlink_actions(transaction_context, target_prefix, prefix_rec), + target_prefix, + ) + ) + + remove_menu_action_groups.append( + ActionGroup( + "remove_menus", + prefix_rec, + RemoveMenuAction.create_actions( + transaction_context, prefix_rec, target_prefix + ), + target_prefix, + ) + ) + + if unlink_action_groups: + axns = ( + UnregisterEnvironmentLocationAction(transaction_context, target_prefix), + ) + unregister_action_groups = [ + ActionGroup("unregister", None, axns, target_prefix) + ] + else: + unregister_action_groups = () + + matchspecs_for_link_dists = match_specs_to_dists( + packages_info_to_link, update_specs + ) + link_action_groups = [] + entry_point_action_groups = [] + compile_action_groups = [] + make_menu_action_groups = [] + record_axns = [] + for pkg_info, lt, spec in zip( + packages_info_to_link, link_types, matchspecs_for_link_dists + ): + link_ag = ActionGroup( + "link", + pkg_info, + cls._make_link_actions( + transaction_context, pkg_info, target_prefix, lt, spec + ), + target_prefix, + ) + link_action_groups.append(link_ag) + + entry_point_ag = ActionGroup( + "entry_point", + pkg_info, + cls._make_entry_point_actions( + transaction_context, + pkg_info, + target_prefix, + lt, + spec, + link_action_groups, + ), + target_prefix, + ) + entry_point_action_groups.append(entry_point_ag) + + compile_ag = ActionGroup( + "compile", + pkg_info, + cls._make_compile_actions( + transaction_context, + pkg_info, + target_prefix, + lt, + spec, + link_action_groups, + ), + target_prefix, + ) + compile_action_groups.append(compile_ag) + + make_menu_ag = ActionGroup( + "make_menus", + pkg_info, + MakeMenuAction.create_actions( + transaction_context, pkg_info, target_prefix, lt + ), + target_prefix, + ) + make_menu_action_groups.append(make_menu_ag) + + all_link_path_actions = ( + *link_ag.actions, + *compile_ag.actions, + *entry_point_ag.actions, + *make_menu_ag.actions, + ) + record_axns.extend( + CreatePrefixRecordAction.create_actions( + transaction_context, + pkg_info, + target_prefix, + lt, + spec, + all_link_path_actions, + ) + ) + + prefix_record_groups = [ActionGroup("record", None, record_axns, target_prefix)] + + # We're post solve here. The update_specs are explicit requests. We need to neuter + # any historic spec that was neutered prior to the solve. + history_actions = UpdateHistoryAction.create_actions( + transaction_context, + target_prefix, + remove_specs, + update_specs, + neutered_specs, + ) + register_actions = ( + RegisterEnvironmentLocationAction(transaction_context, target_prefix), + ) + register_action_groups = [ + ActionGroup( + "register", None, register_actions + history_actions, target_prefix + ) + ] + + # Instantiate any pre or post transactions defined by the user. + pre_transaction_actions = context.plugin_manager.get_pre_transaction_actions( + transaction_context, + target_prefix, + unlink_precs, + link_precs, + remove_specs, + update_specs, + neutered_specs, + ) + post_transaction_actions = context.plugin_manager.get_post_transaction_actions( + transaction_context, + target_prefix, + unlink_precs, + link_precs, + remove_specs, + update_specs, + neutered_specs, + ) + + return PrefixActions( + remove_menu_action_groups, + unlink_action_groups, + unregister_action_groups, + link_action_groups, + register_action_groups, + compile_action_groups, + make_menu_action_groups, + entry_point_action_groups, + prefix_record_groups, + initial_action_groups=[ + ActionGroup("initial", None, pre_transaction_actions, target_prefix) + ], + final_action_groups=[ + ActionGroup("final", None, post_transaction_actions, target_prefix) + ], + ) + + @staticmethod + def _verify_individual_level(prefix_action_group): + all_actions = chain.from_iterable( + axngroup.actions + for action_groups in prefix_action_group + for axngroup in action_groups + ) + + # run all per-action (per-package) verify methods + # one of the more important of these checks is to verify that a file listed in + # the packages manifest (i.e. info/files) is actually contained within the package + error_results = [] + for axn in all_actions: + if axn.verified: + continue + error_result = axn.verify() + if error_result: + formatted_error = "".join( + format_exception_only(type(error_result), error_result) + ) + log.debug("Verification error in action %s\n%s", axn, formatted_error) + error_results.append(error_result) + return error_results + + @staticmethod + def _verify_prefix_level(target_prefix_AND_prefix_action_group_tuple): + # further verification of the whole transaction + # for each path we are creating in link_actions, we need to make sure + # 1. each path either doesn't already exist in the prefix, or will be unlinked + # 2. there's only a single instance of each path + # 3. if the target is a private env, leased paths need to be verified + # 4. make sure conda-meta/history file is writable + # 5. make sure envs/catalog.json is writable; done with RegisterEnvironmentLocationAction + # TODO: 3, 4 + + # this strange unpacking is to help the parallel execution work. Unpacking + # tuples in the map call could be done with a lambda, but that is then not picklable, + # which precludes the use of ProcessPoolExecutor (but not ThreadPoolExecutor) + target_prefix, prefix_action_group = target_prefix_AND_prefix_action_group_tuple + + unlink_action_groups = prefix_action_group.unlink_action_groups + prefix_record_groups = prefix_action_group.prefix_record_groups + + lower_on_win = lambda p: p.lower() if on_win else p + unlink_paths = { + lower_on_win(axn.target_short_path) + for grp in unlink_action_groups + for axn in grp.actions + if isinstance(axn, UnlinkPathAction) + } + # we can get all of the paths being linked by looking only at the + # CreateLinkedPackageRecordAction actions + create_lpr_actions = ( + axn + for grp in prefix_record_groups + for axn in grp.actions + if isinstance(axn, CreatePrefixRecordAction) + ) + + error_results = [] + # Verification 1. each path either doesn't already exist in the prefix, or will be unlinked + link_paths_dict = defaultdict(list) + for axn in create_lpr_actions: + for link_path_action in axn.all_link_path_actions: + if isinstance(link_path_action, CompileMultiPycAction): + target_short_paths = link_path_action.target_short_paths + else: + target_short_paths = ( + (link_path_action.target_short_path,) + if not hasattr(link_path_action, "link_type") + or link_path_action.link_type != LinkType.directory + else () + ) + for path in target_short_paths: + path = lower_on_win(path) + link_paths_dict[path].append(axn) + if path not in unlink_paths and lexists(join(target_prefix, path)): + # we have a collision; at least try to figure out where it came from + colliding_prefix_rec = first( + ( + prefix_rec + for prefix_rec in PrefixData( + target_prefix + ).iter_records() + ), + key=lambda prefix_rec: path in prefix_rec.files, + ) + if colliding_prefix_rec: + error_results.append( + KnownPackageClobberError( + path, + axn.package_info.repodata_record.dist_str(), + colliding_prefix_rec.dist_str(), + context, + ) + ) + else: + error_results.append( + UnknownPackageClobberError( + path, + axn.package_info.repodata_record.dist_str(), + context, + ) + ) + + # Verification 2. there's only a single instance of each path + for path, axns in link_paths_dict.items(): + if len(axns) > 1: + error_results.append( + SharedLinkPathClobberError( + path, + tuple( + axn.package_info.repodata_record.dist_str() for axn in axns + ), + context, + ) + ) + return error_results + + @staticmethod + def _verify_transaction_level(prefix_setups): + # 1. make sure we're not removing conda from conda's env + # 2. make sure we're not removing a conda dependency from conda's env + # 3. enforce context.disallowed_packages + # 4. make sure we're not removing pinned packages without no-pin flag + # 5. make sure conda-meta/history for each prefix is writable + # TODO: Verification 4 + + conda_prefixes = ( + join(context.root_prefix, "envs", "_conda_"), + context.root_prefix, + ) + conda_setups = tuple( + setup + for setup in prefix_setups.values() + if setup.target_prefix in conda_prefixes + ) + + conda_unlinked = any( + prec.name == "conda" + for setup in conda_setups + for prec in setup.unlink_precs + ) + + conda_prec, conda_final_setup = next( + ( + (prec, setup) + for setup in conda_setups + for prec in setup.link_precs + if prec.name == "conda" + ), + (None, None), + ) + + if conda_unlinked and conda_final_setup is None: + # means conda is being unlinked and not re-linked anywhere + # this should never be able to be skipped, even with --force + yield RemoveError( + "This operation will remove conda without replacing it with\n" + "another version of conda." + ) + + if conda_final_setup is None: + # means we're not unlinking then linking a new package, so look up current conda record + conda_final_prefix = context.conda_prefix + pd = PrefixData(conda_final_prefix) + pkg_names_already_lnkd = tuple(rec.name for rec in pd.iter_records()) + pkg_names_being_lnkd = () + pkg_names_being_unlnkd = () + conda_linked_depends = next( + ( + record.depends + for record in pd.iter_records() + if record.name == "conda" + ), + (), + ) + else: + conda_final_prefix = conda_final_setup.target_prefix + pd = PrefixData(conda_final_prefix) + pkg_names_already_lnkd = tuple(rec.name for rec in pd.iter_records()) + pkg_names_being_lnkd = tuple( + prec.name for prec in conda_final_setup.link_precs or () + ) + pkg_names_being_unlnkd = tuple( + prec.name for prec in conda_final_setup.unlink_precs or () + ) + conda_linked_depends = conda_prec.depends + + if conda_final_prefix in prefix_setups: + for conda_dependency in conda_linked_depends: + dep_name = MatchSpec(conda_dependency).name + if dep_name not in pkg_names_being_lnkd and ( + dep_name not in pkg_names_already_lnkd + or dep_name in pkg_names_being_unlnkd + ): + yield RemoveError( + f"'{dep_name}' is a dependency of conda and cannot be removed from\n" + "conda's operating environment." + ) + + # Verification 3. enforce disallowed_packages + disallowed = tuple(MatchSpec(s) for s in context.disallowed_packages) + for prefix_setup in prefix_setups.values(): + for prec in prefix_setup.link_precs: + if any(d.match(prec) for d in disallowed): + yield DisallowedPackageError(prec) + + # Verification 5. make sure conda-meta/history for each prefix is writable + for prefix_setup in prefix_setups.values(): + test_path = join(prefix_setup.target_prefix, PREFIX_MAGIC_FILE) + test_path_existed = lexists(test_path) + dir_existed = None + try: + dir_existed = mkdir_p(dirname(test_path)) + open(test_path, "a").close() + except OSError: + if dir_existed is False: + rm_rf(dirname(test_path)) + yield EnvironmentNotWritableError(prefix_setup.target_prefix) + else: + if not dir_existed: + rm_rf(dirname(test_path)) + elif not test_path_existed: + rm_rf(test_path) + + def _verify(self, prefix_setups, prefix_action_groups): + transaction_exceptions = tuple( + exc + for exc in UnlinkLinkTransaction._verify_transaction_level(prefix_setups) + if exc + ) + if transaction_exceptions: + return transaction_exceptions + + exceptions = [] + for exc in self.verify_executor.map( + UnlinkLinkTransaction._verify_individual_level, + prefix_action_groups.values(), + ): + if exc: + exceptions.extend(exc) + for exc in self.verify_executor.map( + UnlinkLinkTransaction._verify_prefix_level, prefix_action_groups.items() + ): + if exc: + exceptions.extend(exc) + return exceptions + + def _execute(self, all_action_groups): + # unlink unlink_action_groups and unregister_action_groups + unlink_actions = tuple( + group for group in all_action_groups if group.type == "unlink" + ) + # link unlink_action_groups and register_action_groups + link_actions = list( + group for group in all_action_groups if group.type == "link" + ) + compile_actions = list( + group for group in all_action_groups if group.type == "compile" + ) + entry_point_actions = list( + group for group in all_action_groups if group.type == "entry_point" + ) + record_actions = list( + group for group in all_action_groups if group.type == "record" + ) + make_menu_actions = list( + group for group in all_action_groups if group.type == "make_menus" + ) + remove_menu_actions = list( + group for group in all_action_groups if group.type == "remove_menus" + ) + pre_transaction_actions = list( + group for group in all_action_groups if group.type == "initial" + ) + post_transaction_actions = list( + group for group in all_action_groups if group.type == "final" + ) + + with signal_handler(conda_signal_handler), time_recorder("unlink_link_execute"): + exceptions = [] + with get_spinner("Executing transaction"): + # Execute any user-defined pre-transaction actions + for exc in self.execute_executor.map( + UnlinkLinkTransaction._execute_actions, + pre_transaction_actions, + ): + if exc: + exceptions.append(exc) + + # Execute unlink actions + for group, register_group, install_side in ( + (unlink_actions, "unregister", False), + (link_actions, "register", True), + ): + if not install_side: + # uninstalling menus must happen prior to unlinking, or else they might + # call something that isn't there anymore + for axngroup in remove_menu_actions: + UnlinkLinkTransaction._execute_actions(axngroup) + + for axngroup in group: + is_unlink = axngroup.type == "unlink" + target_prefix = axngroup.target_prefix + prec = axngroup.pkg_data + run_script( + target_prefix if is_unlink else prec.extracted_package_dir, + prec, + "pre-unlink" if is_unlink else "pre-link", + target_prefix, + ) + + # parallel block 1: + for exc in self.execute_executor.map( + UnlinkLinkTransaction._execute_actions, group + ): + if exc: + exceptions.append(exc) + + # post link scripts may employ entry points. Do them before post-link. + if install_side: + for axngroup in entry_point_actions: + UnlinkLinkTransaction._execute_actions(axngroup) + + # Run post-link or post-unlink scripts and registering AFTER link/unlink, + # because they may depend on files in the prefix. Additionally, run + # them serially, just in case order matters (hopefully not) + for axngroup in group: + exc = UnlinkLinkTransaction._execute_post_link_actions(axngroup) + if exc: + exceptions.append(exc) + + # parallel block 2: + composite_ag = [] + if install_side: + # consolidate compile actions into one big'un for better efficiency + # note: compile must run before record so that we capture pyc_file + # sizes in the manifest. + individual_actions = [ + axn for ag in compile_actions for axn in ag.actions + ] + if individual_actions: + composite = AggregateCompileMultiPycAction( + *individual_actions + ) + composite_ag.append( + ActionGroup( + "compile", + None, + [composite], + composite.target_prefix, + ) + ) + composite_ag.extend(record_actions) + # functions return None unless there was an exception + for exc in self.execute_executor.map( + UnlinkLinkTransaction._execute_actions, composite_ag + ): + if exc: + exceptions.append(exc) + + # must do the register actions AFTER all link/unlink is done + register_actions = tuple( + group + for group in all_action_groups + if group.type == register_group + ) + for axngroup in register_actions: + exc = UnlinkLinkTransaction._execute_actions(axngroup) + if exc: + exceptions.append(exc) + if exceptions: + break + if install_side: + # uninstalling menus must happen prior to unlinking, or else they might + # call something that isn't there anymore + for axngroup in make_menu_actions: + UnlinkLinkTransaction._execute_actions(axngroup) + + # Execute any user-defined post-transaction actions + for exc in self.execute_executor.map( + UnlinkLinkTransaction._execute_actions, + post_transaction_actions, + ): + if exc: + exceptions.append(exc) + + if exceptions: + # might be good to show all errors, but right now we only show the first + e = exceptions[0] + axngroup = e.errors[1] + + action, is_unlink = (None, axngroup.type == "unlink") + prec = axngroup.pkg_data + + if prec: + log.error( + "An error occurred while {} package '{}'.".format( + "uninstalling" if is_unlink else "installing", + prec.dist_str(), + ) + ) + + # reverse all executed packages except the one that failed + rollback_excs = [] + if context.rollback_enabled: + with get_spinner("Rolling back transaction"): + reverse_actions = reversed(tuple(all_action_groups)) + for axngroup in reverse_actions: + excs = UnlinkLinkTransaction._reverse_actions(axngroup) + rollback_excs.extend(excs) + + raise CondaMultiError( + ( + *( + (e.errors[0], e.errors[2:]) + if isinstance(e, CondaMultiError) + else (e,) + ), + *rollback_excs, + ) + ) + else: + for axngroup in all_action_groups: + for action in axngroup.actions: + action.cleanup() + + @staticmethod + def _execute_actions(axngroup): + target_prefix = axngroup.target_prefix + prec = axngroup.pkg_data + + conda_meta_dir = join(target_prefix, "conda-meta") + if not isdir(conda_meta_dir): + mkdir_p(conda_meta_dir) + + try: + if axngroup.type == "unlink": + log.info( + "===> UNLINKING PACKAGE: %s <===\n prefix=%s\n", + prec.dist_str(), + target_prefix, + ) + + elif axngroup.type == "link": + log.info( + "===> LINKING PACKAGE: %s <===\n prefix=%s\n source=%s\n", + prec.dist_str(), + target_prefix, + prec.extracted_package_dir, + ) + + for action in axngroup.actions: + action.execute() + except Exception as e: # this won't be a multi error + # reverse this package + reverse_excs = () + if context.rollback_enabled: + reverse_excs = UnlinkLinkTransaction._reverse_actions(axngroup) + return CondaMultiError( + ( + e, + axngroup, + *reverse_excs, + ) + ) + + @staticmethod + def _execute_post_link_actions(axngroup): + target_prefix = axngroup.target_prefix + is_unlink = axngroup.type == "unlink" + prec = axngroup.pkg_data + if prec: + try: + run_script( + target_prefix, + prec, + "post-unlink" if is_unlink else "post-link", + activate=True, + ) + except Exception as e: # this won't be a multi error + # reverse this package + reverse_excs = () + if context.rollback_enabled: + reverse_excs = UnlinkLinkTransaction._reverse_actions(axngroup) + return CondaMultiError( + ( + e, + axngroup, + *reverse_excs, + ) + ) + + @staticmethod + def _reverse_actions(axngroup, reverse_from_idx=-1): + target_prefix = axngroup.target_prefix + + # reverse_from_idx = -1 means reverse all actions + prec = axngroup.pkg_data + + if axngroup.type == "unlink": + log.info( + "===> REVERSING PACKAGE UNLINK: %s <===\n prefix=%s\n", + prec.dist_str(), + target_prefix, + ) + + elif axngroup.type == "link": + log.info( + "===> REVERSING PACKAGE LINK: %s <===\n prefix=%s\n", + prec.dist_str(), + target_prefix, + ) + + exceptions = [] + if reverse_from_idx < 0: + reverse_actions = axngroup.actions + else: + reverse_actions = axngroup.actions[: reverse_from_idx + 1] + for axn_idx, action in reversed(tuple(enumerate(reverse_actions))): + try: + action.reverse() + except Exception as e: + log.debug("action.reverse() error in action %r", action, exc_info=True) + exceptions.append(e) + return exceptions + + @staticmethod + def _get_python_info( + target_prefix, prefix_recs_to_unlink, packages_info_to_link + ) -> tuple[str | None, str | None]: + """ + Return the python version and location of the site-packages directory at the end of the transaction + """ + + def version_and_sp(python_record) -> tuple[str | None, str | None]: + if not python_record.version: + raise ValueError("Python record version is required.") + python_version = get_major_minor_version(python_record.version) + python_site_packages = python_record.python_site_packages_path + if python_site_packages is None: + python_site_packages = get_python_site_packages_short_path( + python_version + ) + return python_version, python_site_packages + + linking_new_python = next( + ( + package_info + for package_info in packages_info_to_link + if package_info.repodata_record.name == "python" + ), + None, + ) + if linking_new_python: + python_record = linking_new_python.repodata_record + log.debug(f"found in current transaction python: {python_record}") + return version_and_sp(python_record) + python_record = PrefixData(target_prefix).get("python", None) + if python_record: + unlinking_python = next( + ( + prefix_rec_to_unlink + for prefix_rec_to_unlink in prefix_recs_to_unlink + if prefix_rec_to_unlink.name == "python" + ), + None, + ) + if unlinking_python is None: + # python is already linked and not being unlinked + log.debug(f"found in current prefix, python: {python_record}") + return version_and_sp(python_record) + # no python in the finished environment + log.debug("no python version found in prefix") + return None, None + + @staticmethod + def _make_link_actions( + transaction_context, + package_info, + target_prefix, + requested_link_type, + requested_spec, + ): + required_quad = ( + transaction_context, + package_info, + target_prefix, + requested_link_type, + ) + + file_link_actions = LinkPathAction.create_file_link_actions(*required_quad) + create_directory_actions = LinkPathAction.create_directory_actions( + *required_quad, file_link_actions=file_link_actions + ) + + # the ordering here is significant + return ( + *create_directory_actions, + *file_link_actions, + ) + + @staticmethod + def _make_entry_point_actions( + transaction_context, + package_info, + target_prefix, + requested_link_type, + requested_spec, + link_action_groups, + ): + required_quad = ( + transaction_context, + package_info, + target_prefix, + requested_link_type, + ) + return CreatePythonEntryPointAction.create_actions(*required_quad) + + @staticmethod + def _make_compile_actions( + transaction_context, + package_info, + target_prefix, + requested_link_type, + requested_spec, + link_action_groups, + ): + required_quad = ( + transaction_context, + package_info, + target_prefix, + requested_link_type, + ) + link_action_group = next( + ag for ag in link_action_groups if ag.pkg_data == package_info + ) + return CompileMultiPycAction.create_actions( + *required_quad, file_link_actions=link_action_group.actions + ) + + def _make_legacy_action_groups(self): + # this code reverts json output for plan back to previous behavior + # relied on by Anaconda Navigator and nb_conda + legacy_action_groups = [] + + if self._pfe is None: + self._get_pfe() + + for q, (prefix, setup) in enumerate(self.prefix_setups.items()): + actions = defaultdict(list) + if q == 0: + self._pfe.prepare() + download_urls = {axn.url for axn in self._pfe.cache_actions} + actions["FETCH"].extend( + prec for prec in self._pfe.link_precs if prec.url in download_urls + ) + + actions["PREFIX"] = setup.target_prefix + for prec in setup.unlink_precs: + actions["UNLINK"].append(prec) + for prec in setup.link_precs: + # TODO (AV): maybe add warnings about unverified packages here; + # be warned that doing so may break compatibility with other + # applications. + actions["LINK"].append(prec) + + legacy_action_groups.append(actions) + + return legacy_action_groups + + def print_transaction_summary(self): + legacy_action_groups = self._make_legacy_action_groups() + + download_urls = {axn.url for axn in self._pfe.cache_actions} + + for actions, (prefix, stp) in zip( + legacy_action_groups, self.prefix_setups.items() + ): + change_report = self._calculate_change_report( + prefix, + stp.unlink_precs, + stp.link_precs, + download_urls, + stp.remove_specs, + stp.update_specs, + ) + change_report_str = self._change_report_str(change_report) + print(ensure_text_type(change_report_str)) + + return legacy_action_groups + + def _change_report_str(self, change_report): + # TODO (AV): add warnings about unverified packages in this function + builder = ["", "## Package Plan ##\n"] + builder.append(f" environment location: {change_report.prefix}") + builder.append("") + if change_report.specs_to_remove: + builder.append( + " removed specs:{}".format( + dashlist( + sorted(str(s) for s in change_report.specs_to_remove), indent=4 + ) + ) + ) + builder.append("") + if change_report.specs_to_add: + builder.append( + f" added / updated specs:{dashlist(sorted(str(s) for s in change_report.specs_to_add), indent=4)}" + ) + builder.append("") + + def channel_filt(s): + if context.show_channel_urls is False: + return "" + if context.show_channel_urls is None and s == DEFAULTS_CHANNEL_NAME: + return "" + return s + + def print_dists(dists_extras): + lines = [] + fmt = " %-27s|%17s" + lines.append(fmt % ("package", "build")) + lines.append(fmt % ("-" * 27, "-" * 17)) + for prec, extra in dists_extras: + line = fmt % ( + strip_global(prec.namekey) + "-" + prec.version, + prec.build, + ) + if extra: + line += extra + lines.append(line) + return lines + + convert_namekey = lambda x: ("0:" + x[7:]) if x.startswith("global:") else x + strip_global = lambda x: x[7:] if x.startswith("global:") else x + + if change_report.fetch_precs: + builder.append("\nThe following packages will be downloaded:\n") + + disp_lst = [] + total_download_bytes = 0 + for prec in sorted( + change_report.fetch_precs, key=lambda x: convert_namekey(x.namekey) + ): + size = prec.size + extra = "%15s" % human_bytes(size) + total_download_bytes += size + schannel = channel_filt(str(prec.channel.canonical_name)) + if schannel: + extra += " " + schannel + disp_lst.append((prec, extra)) + builder.extend(print_dists(disp_lst)) + + builder.append(" " * 4 + "-" * 60) + builder.append(" " * 43 + "Total: %14s" % human_bytes(total_download_bytes)) + + def diff_strs(unlink_prec, link_prec): + channel_change = unlink_prec.channel.name != link_prec.channel.name + subdir_change = unlink_prec.subdir != link_prec.subdir + version_change = unlink_prec.version != link_prec.version + build_change = unlink_prec.build != link_prec.build + + builder_left = [] + builder_right = [] + + if channel_change or subdir_change: + if unlink_prec.channel.name is not None: + builder_left.append(unlink_prec.channel.name) + if link_prec.channel.name is not None: + builder_right.append(link_prec.channel.name) + if subdir_change: + builder_left.append("/" + unlink_prec.subdir) + builder_right.append("/" + link_prec.subdir) + if (channel_change or subdir_change) and (version_change or build_change): + builder_left.append("::" + unlink_prec.name + "-") + builder_right.append("::" + link_prec.name + "-") + if version_change or build_change: + builder_left.append(unlink_prec.version + "-" + unlink_prec.build) + builder_right.append(link_prec.version + "-" + link_prec.build) + + return "".join(builder_left), "".join(builder_right) + + def add_single(display_key, disp_str): + if len(display_key) > 18: + display_key = display_key[:17] + "~" + builder.append(" %-18s %s" % (display_key, disp_str)) + + def add_double(display_key, left_str, right_str): + if len(display_key) > 18: + display_key = display_key[:17] + "~" + if len(left_str) > 38: + left_str = left_str[:37] + "~" + builder.append(" %-18s %38s --> %s" % (display_key, left_str, right_str)) + + def summarize_double(change_report_precs, key): + for namekey in sorted(change_report_precs, key=key): + unlink_prec, link_prec = change_report_precs[namekey] + left_str, right_str = diff_strs(unlink_prec, link_prec) + add_double( + strip_global(namekey), + left_str, + f"{right_str} {' '.join(link_prec.metadata)}", + ) + + if change_report.new_precs: + builder.append("\nThe following NEW packages will be INSTALLED:\n") + for namekey in sorted(change_report.new_precs, key=convert_namekey): + link_prec = change_report.new_precs[namekey] + add_single( + strip_global(namekey), + f"{link_prec.record_id()} {' '.join(link_prec.metadata)}", + ) + + if change_report.removed_precs: + builder.append("\nThe following packages will be REMOVED:\n") + for namekey in sorted(change_report.removed_precs, key=convert_namekey): + unlink_prec = change_report.removed_precs[namekey] + builder.append( + f" {unlink_prec.name}-{unlink_prec.version}-{unlink_prec.build}" + ) + + if change_report.updated_precs: + builder.append("\nThe following packages will be UPDATED:\n") + summarize_double(change_report.updated_precs, convert_namekey) + + if change_report.superseded_precs: + builder.append( + "\nThe following packages will be SUPERSEDED " + "by a higher-priority channel:\n" + ) + summarize_double(change_report.superseded_precs, convert_namekey) + + if change_report.downgraded_precs: + builder.append("\nThe following packages will be DOWNGRADED:\n") + summarize_double(change_report.downgraded_precs, convert_namekey) + + if change_report.revised_precs: + builder.append("\nThe following packages will be REVISED:\n") + summarize_double(change_report.revised_precs, convert_namekey) + + builder.append("") + builder.append("") + return "\n".join(builder) + + @staticmethod + def _calculate_change_report( + prefix, unlink_precs, link_precs, download_urls, specs_to_remove, specs_to_add + ): + unlink_map = {prec.namekey: prec for prec in unlink_precs} + link_map = {prec.namekey: prec for prec in link_precs} + unlink_namekeys, link_namekeys = set(unlink_map), set(link_map) + + removed_precs = { + namekey: unlink_map[namekey] + for namekey in (unlink_namekeys - link_namekeys) + } + new_precs = { + namekey: link_map[namekey] for namekey in (link_namekeys - unlink_namekeys) + } + + # updated means a version increase, or a build number increase + # downgraded means a version decrease, or build number decrease, but channel canonical_name + # has to be the same + # revised means the version and channel canonical_name is the same, but the build variant + # is different. The build variant is the build string and build number. + # superseded then should be everything else left over (eg. changed channel) + updated_precs = {} + downgraded_precs = {} + revised_precs = {} + superseded_precs = {} + + common_namekeys = link_namekeys & unlink_namekeys + for namekey in common_namekeys: + unlink_prec, link_prec = unlink_map[namekey], link_map[namekey] + unlink_vo = VersionOrder(unlink_prec.version) + link_vo = VersionOrder(link_prec.version) + build_number_increases = link_prec.build_number > unlink_prec.build_number + + if link_vo == unlink_vo and build_number_increases or link_vo > unlink_vo: + updated_precs[namekey] = (unlink_prec, link_prec) + elif ( + link_prec.channel.name == unlink_prec.channel.name + and link_prec.subdir == unlink_prec.subdir + ): + if link_prec == unlink_prec: + # noarch: python packages are re-linked on a python version change + # just leave them out of the package report + continue + if link_vo == unlink_vo and link_prec.build != unlink_prec.build: + revised_precs[namekey] = (unlink_prec, link_prec) + else: + downgraded_precs[namekey] = (unlink_prec, link_prec) + else: + superseded_precs[namekey] = (unlink_prec, link_prec) + + fetch_precs = {prec for prec in link_precs if prec.url in download_urls} + change_report = ChangeReport( + prefix, + specs_to_remove, + specs_to_add, + removed_precs, + new_precs, + updated_precs, + downgraded_precs, + superseded_precs, + fetch_precs, + revised_precs, + ) + return change_report + + +def run_script( + prefix: str, + prec, + action: str = "post-link", + env_prefix: str = None, + activate: bool = False, +) -> bool: + """ + Call the post-link (or pre-unlink) script, returning True on success, + False on failure. + """ + path = join( + prefix, + BIN_DIRECTORY, + ".{}-{}.{}".format(prec.name, action, "bat" if on_win else "sh"), + ) + if not isfile(path): + return True + + env = os.environ.copy() + + if action == "pre-link": # pragma: no cover + # old no-arch support; deprecated + is_old_noarch = False + try: + with open(path) as f: + script_text = ensure_text_type(f.read()) + if ( + on_win and "%PREFIX%\\python.exe %SOURCE_DIR%\\link.py" in script_text + ) or "$PREFIX/bin/python $SOURCE_DIR/link.py" in script_text: + is_old_noarch = True + except Exception as e: + log.debug(e, exc_info=True) + + env["SOURCE_DIR"] = prefix + if not is_old_noarch: + warnings.warn( + dals( + """ + Package %s uses a pre-link script. Pre-link scripts are potentially dangerous. + This is because pre-link scripts have the ability to change the package contents in the + package cache, and therefore modify the underlying files for already-created conda + environments. Future versions of conda may deprecate and ignore pre-link scripts. + """ + ) + % prec.dist_str() + ) + + script_caller = None + if on_win: + try: + comspec = get_comspec() # fail early with KeyError if undefined + except KeyError: + log.info( + "failed to run %s for %s due to COMSPEC KeyError", + action, + prec.dist_str(), + ) + return False + if activate: + script_caller, command_args = wrap_subprocess_call( + context.root_prefix, + prefix, + context.dev, + False, + ("@CALL", path), + ) + else: + command_args = [comspec, "/d", "/c", path] + else: + shell_path = "sh" if "bsd" in sys.platform else "bash" + if activate: + script_caller, command_args = wrap_subprocess_call( + context.root_prefix, + prefix, + context.dev, + False, + (".", path), + ) + else: + shell_path = "sh" if "bsd" in sys.platform else "bash" + command_args = [shell_path, "-x", path] + + env["ROOT_PREFIX"] = context.root_prefix + env["PREFIX"] = env_prefix or prefix + env["PKG_NAME"] = prec.name + env["PKG_VERSION"] = prec.version + env["PKG_BUILDNUM"] = prec.build_number + env["PATH"] = os.pathsep.join((dirname(path), env.get("PATH", ""))) + + log.debug( + "for %s at %s, executing script: $ %s", + prec.dist_str(), + env["PREFIX"], + " ".join(command_args), + ) + try: + response = subprocess_call( + command_args, env=env, path=dirname(path), raise_on_error=False + ) + if response.rc != 0: + m = messages(prefix) + if action in ("pre-link", "post-link"): + if "openssl" in prec.dist_str(): + # this is a hack for conda-build string parsing in the conda_build/build.py + # create_env function + message = f"{action} failed for: {prec}" + else: + message = dals( + """ + %s script failed for package %s + location of failed script: %s + ==> script messages <== + %s + ==> script output <== + stdout: %s + stderr: %s + return code: %s + """ + ) % ( + action, + prec.dist_str(), + path, + m or "", + response.stdout, + response.stderr, + response.rc, + ) + raise LinkError(message) + else: + log.warning( + "%s script failed for package %s\n" + "consider notifying the package maintainer", + action, + prec.dist_str(), + ) + return False + else: + messages(prefix) + return True + finally: + if script_caller is not None: + if "CONDA_TEST_SAVE_TEMPS" not in os.environ: + rm_rf(script_caller) + else: + log.warning( + f"CONDA_TEST_SAVE_TEMPS :: retaining run_script {script_caller}" + ) + + +def messages(prefix): + path = join(prefix, ".messages.txt") + try: + if isfile(path): + with open(path) as fi: + m = fi.read() + if hasattr(m, "decode"): + m = m.decode("utf-8") + print(m, file=sys.stderr if context.json else sys.stdout) + return m + finally: + rm_rf(path) diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/package_cache_data.py b/miniconda3/lib/python3.13/site-packages/conda/core/package_cache_data.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1f3841e29353c1c5eb55b2f33e7ea148774a42 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/package_cache_data.py @@ -0,0 +1,1030 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools for managing the package cache (previously downloaded packages).""" + +from __future__ import annotations + +import os +from collections import defaultdict +from concurrent.futures import CancelledError, ThreadPoolExecutor, as_completed +from errno import EACCES, ENOENT, EPERM, EROFS +from functools import partial +from itertools import chain +from logging import getLogger +from os import scandir +from os.path import basename, dirname, getsize, join +from sys import platform +from tarfile import ReadError +from typing import TYPE_CHECKING + +from .. import CondaError, CondaMultiError, conda_signal_handler +from ..auxlib.collection import first +from ..auxlib.decorators import memoizemethod +from ..auxlib.entity import ValidationError +from ..base.constants import ( + CONDA_PACKAGE_EXTENSION_V1, + CONDA_PACKAGE_EXTENSION_V2, + PACKAGE_CACHE_MAGIC_FILE, +) +from ..base.context import context +from ..common.constants import NULL, TRACE +from ..common.io import IS_INTERACTIVE, time_recorder +from ..common.iterators import groupby_to_dict as groupby +from ..common.path import expand, strip_pkg_extension, url_to_path +from ..common.serialize import json +from ..common.signals import signal_handler +from ..common.url import path_to_url +from ..exceptions import NotWritableError, NoWritablePkgsDirError +from ..gateways.disk.create import ( + create_package_cache_directory, + write_as_json_to_file, +) +from ..gateways.disk.delete import rm_rf +from ..gateways.disk.read import ( + compute_sum, + isdir, + isfile, + islink, + read_index_json, + read_index_json_from_tarball, + read_repodata_json, +) +from ..gateways.disk.test import file_path_is_writable +from ..models.match_spec import MatchSpec +from ..models.records import PackageCacheRecord, PackageRecord +from ..reporters import get_progress_bar, get_progress_bar_context_manager +from ..utils import human_bytes +from .path_actions import CacheUrlAction, ExtractPackageAction + +if TYPE_CHECKING: + from concurrent.futures import Future + from pathlib import Path + + from ..plugins.types import ProgressBarBase + +log = getLogger(__name__) + +FileNotFoundError = IOError + +try: + from conda_package_handling.api import THREADSAFE_EXTRACT +except ImportError: + THREADSAFE_EXTRACT = False +# On the machines we tested, extraction doesn't get any faster after 3 threads +EXTRACT_THREADS = min(os.cpu_count() or 1, 3) if THREADSAFE_EXTRACT else 1 + + +class PackageCacheType(type): + """This metaclass does basic caching of PackageCache instance objects.""" + + def __call__(cls, pkgs_dir: str | os.PathLike | Path): + if isinstance(pkgs_dir, PackageCacheData): + return pkgs_dir + elif (pkgs_dir := str(pkgs_dir)) in PackageCacheData._cache_: + return PackageCacheData._cache_[pkgs_dir] + else: + package_cache_instance = super().__call__(pkgs_dir) + PackageCacheData._cache_[pkgs_dir] = package_cache_instance + return package_cache_instance + + +class PackageCacheData(metaclass=PackageCacheType): + _cache_: dict[str, PackageCacheData] = {} + + def __init__(self, pkgs_dir): + self.pkgs_dir = pkgs_dir + self.__package_cache_records = None + self.__is_writable = NULL + + self._urls_data = UrlsData(pkgs_dir) + + def insert(self, package_cache_record): + meta = join( + package_cache_record.extracted_package_dir, "info", "repodata_record.json" + ) + write_as_json_to_file(meta, PackageRecord.from_objects(package_cache_record)) + + self._package_cache_records[package_cache_record] = package_cache_record + + def load(self): + self.__package_cache_records = _package_cache_records = {} + self._check_writable() # called here to create the cache if it doesn't exist + if not isdir(self.pkgs_dir): + # no directory exists, and we didn't have permissions to create it + return + + pkgs_dir_contents = tuple(entry.name for entry in scandir(self.pkgs_dir)) + for base_name in self._dedupe_pkgs_dir_contents(pkgs_dir_contents): + full_path = join(self.pkgs_dir, base_name) + if islink(full_path): + continue + elif ( + isdir(full_path) + and isfile(join(full_path, "info", "index.json")) + or isfile(full_path) + and context.plugin_manager.has_package_extension(full_path) + ): + try: + package_cache_record = self._make_single_record(base_name) + except ValidationError as err: + # ValidationError: package fields are invalid + log.warning( + f"Failed to create package cache record for '{base_name}'. {err}" + ) + package_cache_record = None + + # if package_cache_record is None, it means we couldn't create a record, ignore + if package_cache_record: + _package_cache_records[package_cache_record] = package_cache_record + + def reload(self): + self.load() + return self + + def get(self, package_ref: PackageRecord, default=NULL): + if not isinstance(package_ref, PackageRecord): + raise TypeError("`package_ref` must be a PackageRecord instance.") + try: + return self._package_cache_records[package_ref] + except KeyError: + if default is not NULL: + return default + else: + raise + + def remove(self, package_ref, default=NULL): + if default is NULL: + return self._package_cache_records.pop(package_ref) + else: + return self._package_cache_records.pop(package_ref, default) + + def query(self, package_ref_or_match_spec): + # returns a generator + param = package_ref_or_match_spec + if isinstance(param, str): + param = MatchSpec(param) + if isinstance(param, MatchSpec): + return ( + pcrec + for pcrec in self._package_cache_records.values() + if param.match(pcrec) + ) + else: + if not isinstance(param, PackageRecord): + raise TypeError("`package_ref` must be a PackageRecord instance.") + return ( + pcrec + for pcrec in self._package_cache_records.values() + if pcrec == param + ) + + def iter_records(self): + return iter(self._package_cache_records) + + @classmethod + def query_all(cls, package_ref_or_match_spec, pkgs_dirs=None): + if pkgs_dirs is None: + pkgs_dirs = context.pkgs_dirs + + return chain.from_iterable( + pcache.query(package_ref_or_match_spec) + for pcache in cls.all_caches_writable_first(pkgs_dirs) + ) + + # ########################################################################################## + # these class methods reach across all package cache directories (usually context.pkgs_dirs) + # ########################################################################################## + + @classmethod + def first_writable(cls, pkgs_dirs=None): + # Calling this method will *create* a package cache directory if one does not already + # exist. Any caller should intend to *use* that directory for *writing*, not just reading. + if pkgs_dirs is None: + pkgs_dirs = context.pkgs_dirs + for pkgs_dir in pkgs_dirs: + package_cache = cls(pkgs_dir) + i_wri = package_cache.is_writable + if i_wri is True: + return package_cache + elif i_wri is None: + # means package cache directory doesn't exist, need to try to create it + try: + created = create_package_cache_directory(package_cache.pkgs_dir) + except NotWritableError: + continue + if created: + package_cache.__is_writable = True + return package_cache + + raise NoWritablePkgsDirError(pkgs_dirs) + + @classmethod + def writable_caches(cls, pkgs_dirs=None): + if pkgs_dirs is None: + pkgs_dirs = context.pkgs_dirs + writable_caches = tuple( + filter(lambda c: c.is_writable, (cls(pd) for pd in pkgs_dirs)) + ) + return writable_caches + + @classmethod + def read_only_caches(cls, pkgs_dirs=None): + if pkgs_dirs is None: + pkgs_dirs = context.pkgs_dirs + read_only_caches = tuple( + filter(lambda c: not c.is_writable, (cls(pd) for pd in pkgs_dirs)) + ) + return read_only_caches + + @classmethod + def all_caches_writable_first(cls, pkgs_dirs=None): + if pkgs_dirs is None: + pkgs_dirs = context.pkgs_dirs + pc_groups = groupby(lambda pc: pc.is_writable, (cls(pd) for pd in pkgs_dirs)) + return (*pc_groups.get(True, ()), *pc_groups.get(False, ())) + + @classmethod + def get_all_extracted_entries(cls): + package_caches = (cls(pd) for pd in context.pkgs_dirs) + return tuple( + pc_entry + for pc_entry in chain.from_iterable( + package_cache.values() for package_cache in package_caches + ) + if pc_entry.is_extracted + ) + + @classmethod + def get_entry_to_link(cls, package_ref): + pc_entry = next( + (pcrec for pcrec in cls.query_all(package_ref) if pcrec.is_extracted), None + ) + if pc_entry is not None: + return pc_entry + + # this can happen with `conda install path/to/package.tar.bz2` + # because dist has channel '' + # if ProgressiveFetchExtract did its job correctly, what we're looking for + # should be the matching dist_name in the first writable package cache + # we'll search all caches for a match, but search writable caches first + dist_str = package_ref.dist_str().rsplit(":", 1)[-1] + pc_entry = next( + ( + cache._scan_for_dist_no_channel(dist_str) + for cache in cls.all_caches_writable_first() + if cache + ), + None, + ) + if pc_entry is not None: + return pc_entry + raise CondaError( + f"No package '{package_ref.dist_str()}' found in cache directories." + ) + + @classmethod + def tarball_file_in_cache(cls, tarball_path, md5sum=None, exclude_caches=()): + tarball_full_path, md5sum = cls._clean_tarball_path_and_get_md5sum( + tarball_path, md5sum + ) + pc_entry = first( + cls(pkgs_dir).tarball_file_in_this_cache(tarball_full_path, md5sum) + for pkgs_dir in context.pkgs_dirs + if pkgs_dir not in exclude_caches + ) + return pc_entry + + @classmethod + def clear(cls): + cls._cache_.clear() + + def tarball_file_in_this_cache(self, tarball_path, md5sum=None): + tarball_full_path, md5sum = self._clean_tarball_path_and_get_md5sum( + tarball_path, md5sum + ) + tarball_basename = basename(tarball_full_path) + pc_entry = first( + (pc_entry for pc_entry in self.values()), + key=lambda pce: pce.tarball_basename == tarball_basename + and pce.md5 == md5sum, + ) + return pc_entry + + @property + def _package_cache_records(self): + # don't actually populate _package_cache_records until we need it + if self.__package_cache_records is None: + self.load() + return self.__package_cache_records + + @property + def is_writable(self): + # returns None if package cache directory does not exist / has not been created + if self.__is_writable is NULL: + return self._check_writable() + return self.__is_writable + + def _check_writable(self): + magic_file = join(self.pkgs_dir, PACKAGE_CACHE_MAGIC_FILE) + if isfile(magic_file): + i_wri = file_path_is_writable(join(self.pkgs_dir, PACKAGE_CACHE_MAGIC_FILE)) + self.__is_writable = i_wri + log.debug("package cache directory '%s' writable: %s", self.pkgs_dir, i_wri) + else: + log.log(TRACE, "package cache directory '%s' does not exist", self.pkgs_dir) + self.__is_writable = i_wri = None + return i_wri + + @staticmethod + def _clean_tarball_path_and_get_md5sum(tarball_path, md5sum=None): + if tarball_path.startswith("file:/"): + tarball_path = url_to_path(tarball_path) + tarball_full_path = expand(tarball_path) + + if isfile(tarball_full_path) and md5sum is None: + md5sum = compute_sum(tarball_full_path, "md5") + + return tarball_full_path, md5sum + + def _scan_for_dist_no_channel(self, dist_str): + return next( + ( + pcrec + for pcrec in self._package_cache_records + if pcrec.dist_str().rsplit(":", 1)[-1] == dist_str + ), + None, + ) + + def itervalues(self): + return iter(self.values()) + + def values(self): + return self._package_cache_records.values() + + def __repr__(self): + args = (f"{key}={getattr(self, key)!r}" for key in ("pkgs_dir",)) + return "{}({})".format(self.__class__.__name__, ", ".join(args)) + + def _make_single_record(self, package_filename): + # delay-load this to help make sure libarchive can be found + from conda_package_handling.api import InvalidArchiveError + + package_tarball_full_path = join(self.pkgs_dir, package_filename) + log.log(TRACE, "adding to package cache %s", package_tarball_full_path) + extracted_package_dir, pkg_ext = strip_pkg_extension(package_tarball_full_path) + + # try reading info/repodata_record.json + try: + repodata_record = read_repodata_json(extracted_package_dir) + package_cache_record = PackageCacheRecord.from_objects( + repodata_record, + package_tarball_full_path=package_tarball_full_path, + extracted_package_dir=extracted_package_dir, + ) + return package_cache_record + except (OSError, json.JSONDecodeError, ValueError, FileNotFoundError) as e: + # EnvironmentError: info/repodata_record.json doesn't exists + # json.JSONDecodeError: info/repodata_record.json is partially extracted or corrupted + # python 2.7 raises ValueError instead of json.JSONDecodeError + # ValueError("No JSON object could be decoded") + log.debug( + "unable to read %s\n because %r", + join(extracted_package_dir, "info", "repodata_record.json"), + e, + ) + + # try reading info/index.json + try: + raw_json_record = read_index_json(extracted_package_dir) + except (OSError, json.JSONDecodeError, ValueError, FileNotFoundError) as e: + # EnvironmentError: info/index.json doesn't exist + # json.JSONDecodeError: info/index.json is partially extracted or corrupted + # python 2.7 raises ValueError instead of json.JSONDecodeError + # ValueError("No JSON object could be decoded") + log.debug( + "unable to read %s\n because %r", + join(extracted_package_dir, "info", "index.json"), + e, + ) + + if isdir(extracted_package_dir) and not isfile( + package_tarball_full_path + ): + # We have a directory that looks like a conda package, but without + # (1) info/repodata_record.json or info/index.json, and (2) a conda package + # tarball, there's not much we can do. We'll just ignore it. + return None + + try: + if self.is_writable: + if isdir(extracted_package_dir): + # We have a partially unpacked conda package directory. Best thing + # to do is remove it and try extracting. + rm_rf(extracted_package_dir) + try: + context.plugin_manager.extract_package( + package_tarball_full_path, + extracted_package_dir, + ) + except (OSError, InvalidArchiveError) as e: + if e.errno == ENOENT: + # FileNotFoundError(2, 'No such file or directory') + # At this point, we can assume the package tarball is bad. + # Remove everything and move on. + # see https://github.com/conda/conda/issues/6707 + rm_rf(package_tarball_full_path) + rm_rf(extracted_package_dir) + return None + try: + raw_json_record = read_index_json(extracted_package_dir) + except (OSError, json.JSONDecodeError, FileNotFoundError): + # At this point, we can assume the package tarball is bad. + # Remove everything and move on. + rm_rf(package_tarball_full_path) + rm_rf(extracted_package_dir) + return None + else: + raw_json_record = read_index_json_from_tarball( + package_tarball_full_path + ) + except ( + EOFError, + ReadError, + FileNotFoundError, + InvalidArchiveError, + ) as e: + # EOFError: Compressed file ended before the end-of-stream marker was reached + # tarfile.ReadError: file could not be opened successfully + # We have a corrupted tarball. Remove the tarball so it doesn't affect + # anything, and move on. + log.debug( + "unable to extract info/index.json from %s\n because %r", + package_tarball_full_path, + e, + ) + rm_rf(package_tarball_full_path) + return None + + # we were able to read info/index.json, so let's continue + if isfile(package_tarball_full_path): + md5 = compute_sum(package_tarball_full_path, "md5") + else: + md5 = None + + url = self._urls_data.get_url(package_filename) + package_cache_record = PackageCacheRecord.from_objects( + raw_json_record, + url=url, + fn=basename(package_tarball_full_path), + md5=md5, + size=getsize(package_tarball_full_path), + package_tarball_full_path=package_tarball_full_path, + extracted_package_dir=extracted_package_dir, + ) + + # write the info/repodata_record.json file so we can short-circuit this next time + if self.is_writable: + repodata_record = PackageRecord.from_objects(package_cache_record) + repodata_record_path = join( + extracted_package_dir, "info", "repodata_record.json" + ) + try: + write_as_json_to_file(repodata_record_path, repodata_record) + except OSError as e: + if e.errno in (EACCES, EPERM, EROFS) and isdir( + dirname(repodata_record_path) + ): + raise NotWritableError( + repodata_record_path, e.errno, caused_by=e + ) + else: + raise + + return package_cache_record + + @staticmethod + def _dedupe_pkgs_dir_contents(pkgs_dir_contents): + # if both 'six-1.10.0-py35_0/' and 'six-1.10.0-py35_0.tar.bz2' are in pkgs_dir, + # only 'six-1.10.0-py35_0.tar.bz2' will be in the return contents + if not pkgs_dir_contents: + return [] + _CONDA_TARBALL_EXTENSION_V1 = CONDA_PACKAGE_EXTENSION_V1 + _CONDA_TARBALL_EXTENSION_V2 = CONDA_PACKAGE_EXTENSION_V2 + _strip_pkg_extension = strip_pkg_extension + groups = defaultdict(set) + any( + groups[ext].add(fn_root) + for fn_root, ext in (_strip_pkg_extension(fn) for fn in pkgs_dir_contents) + ) + conda_extensions = groups[_CONDA_TARBALL_EXTENSION_V2] + tar_bz2_extensions = groups[_CONDA_TARBALL_EXTENSION_V1] - conda_extensions + others = groups[None] - conda_extensions - tar_bz2_extensions + return sorted( + ( + *(path + _CONDA_TARBALL_EXTENSION_V2 for path in conda_extensions), + *(path + _CONDA_TARBALL_EXTENSION_V1 for path in tar_bz2_extensions), + *others, + ) + ) + + +class UrlsData: + # this is a class to manage urls.txt + # it should basically be thought of as a sequence + # in this class I'm breaking the rule that all disk access goes through conda.gateways + + def __init__(self, pkgs_dir): + self.pkgs_dir = pkgs_dir + self.urls_txt_path = urls_txt_path = join(pkgs_dir, "urls.txt") + if isfile(urls_txt_path): + with open(urls_txt_path, "rb") as fh: + self._urls_data = [line.strip().decode("utf-8") for line in fh] + self._urls_data.reverse() + else: + self._urls_data = [] + + def __contains__(self, url): + return url in self._urls_data + + def __iter__(self): + return iter(self._urls_data) + + def add_url(self, url): + with open(self.urls_txt_path, mode="a", encoding="utf-8") as fh: + linefeed = "\r\n" if platform == "win32" else "\n" + fh.write(url + linefeed) + self._urls_data.insert(0, url) + + @memoizemethod + def get_url(self, package_path): + # package path can be a full path or just a basename + # can be either an extracted directory or tarball + package_path = basename(package_path) + # NOTE: This makes an assumption that all extensionless packages came from a .tar.bz2. + # That's probably a good assumption going forward, because we should now always + # be recording the extension in urls.txt. The extensionless situation should be + # legacy behavior only. + if not context.plugin_manager.has_package_extension(package_path): + package_path += CONDA_PACKAGE_EXTENSION_V1 + return first(self, lambda url: basename(url) == package_path) + + +# ############################## +# downloading +# ############################## + + +class ProgressiveFetchExtract: + @staticmethod + def make_actions_for_record(pref_or_spec): + if pref_or_spec is None: + raise TypeError("`pref_or_spec` cannot be None.") + # returns a cache_action and extract_action + + # if the pref or spec has an md5 value + # look in all caches for package cache record that is + # (1) already extracted, and + # (2) matches the md5 + # If one exists, no actions are needed. + sha256 = pref_or_spec.get("sha256") + size = pref_or_spec.get("size") + md5 = pref_or_spec.get("md5") + legacy_bz2_size = pref_or_spec.get("legacy_bz2_size") + legacy_bz2_md5 = pref_or_spec.get("legacy_bz2_md5") + + def pcrec_matches(pcrec): + matches = True + # sha256 is overkill for things that are already in the package cache. + # It's just a quick match. + # if sha256 is not None and pcrec.sha256 is not None: + # matches = sha256 == pcrec.sha256 + if size is not None and pcrec.get("size") is not None: + matches = pcrec.size in (size, legacy_bz2_size) + if matches and md5 is not None and pcrec.get("md5") is not None: + matches = pcrec.md5 in (md5, legacy_bz2_md5) + return matches + + extracted_pcrec = next( + ( + pcrec + for pcrec in chain.from_iterable( + PackageCacheData(pkgs_dir).query(pref_or_spec) + for pkgs_dir in context.pkgs_dirs + ) + if pcrec.is_extracted + ), + None, + ) + if ( + extracted_pcrec + and pcrec_matches(extracted_pcrec) + and extracted_pcrec.get("url") + ): + return None, None + + # there is no extracted dist that can work, so now we look for tarballs that + # aren't extracted + # first we look in all writable caches, and if we find a match, we extract in place + # otherwise, if we find a match in a non-writable cache, we link it to the first writable + # cache, and then extract + pcrec_from_writable_cache = next( + ( + pcrec + for pcrec in chain.from_iterable( + pcache.query(pref_or_spec) + for pcache in PackageCacheData.writable_caches() + ) + if pcrec.is_fetched + ), + None, + ) + if ( + pcrec_from_writable_cache + and pcrec_matches(pcrec_from_writable_cache) + and pcrec_from_writable_cache.get("url") + ): + # extract in place + extract_action = ExtractPackageAction( + source_full_path=pcrec_from_writable_cache.package_tarball_full_path, + target_pkgs_dir=dirname( + pcrec_from_writable_cache.package_tarball_full_path + ), + target_extracted_dirname=basename( + pcrec_from_writable_cache.extracted_package_dir + ), + record_or_spec=pcrec_from_writable_cache, + sha256=pcrec_from_writable_cache.sha256 or sha256, + size=pcrec_from_writable_cache.size or size, + md5=pcrec_from_writable_cache.md5 or md5, + ) + return None, extract_action + + pcrec_from_read_only_cache = next( + ( + pcrec + for pcrec in chain.from_iterable( + pcache.query(pref_or_spec) + for pcache in PackageCacheData.read_only_caches() + ) + if pcrec.is_fetched + ), + None, + ) + + first_writable_cache = PackageCacheData.first_writable() + if pcrec_from_read_only_cache and pcrec_matches(pcrec_from_read_only_cache): + # we found a tarball, but it's in a read-only package cache + # we need to link the tarball into the first writable package cache, + # and then extract + cache_action = CacheUrlAction( + url=path_to_url(pcrec_from_read_only_cache.package_tarball_full_path), + target_pkgs_dir=first_writable_cache.pkgs_dir, + target_package_basename=pcrec_from_read_only_cache.fn, + sha256=pcrec_from_read_only_cache.get("sha256") or sha256, + size=pcrec_from_read_only_cache.get("size") or size, + md5=pcrec_from_read_only_cache.get("md5") or md5, + ) + trgt_extracted_dirname = strip_pkg_extension(pcrec_from_read_only_cache.fn)[ + 0 + ] + extract_action = ExtractPackageAction( + source_full_path=cache_action.target_full_path, + target_pkgs_dir=first_writable_cache.pkgs_dir, + target_extracted_dirname=trgt_extracted_dirname, + record_or_spec=pcrec_from_read_only_cache, + sha256=pcrec_from_read_only_cache.get("sha256") or sha256, + size=pcrec_from_read_only_cache.get("size") or size, + md5=pcrec_from_read_only_cache.get("md5") or md5, + ) + return cache_action, extract_action + + # if we got here, we couldn't find a matching package in the caches + # we'll have to download one; fetch and extract + url = pref_or_spec.get("url") + if not url: + raise ValueError(".url field is required and must be non-empty.") + + # Determine the target filename for the downloaded package. + # For the draft repodata v3 format (especially packages.whl), while the + # repodata contains the correct fn field (e.g., idna-3.10-py3-none-any.whl), + # rattler sanitizes it internally to a conda-style identifier + # (e.g., idna-3.10-py3_none_any_0). We extract from URL which always + # contains the correct filename. + # See: https://github.com/conda/conda/issues/15620 + target_package_basename = basename(url) or pref_or_spec.fn + + cache_action = CacheUrlAction( + url=url, + target_pkgs_dir=first_writable_cache.pkgs_dir, + target_package_basename=target_package_basename, + sha256=sha256, + size=size, + md5=md5, + ) + extract_action = ExtractPackageAction( + source_full_path=cache_action.target_full_path, + target_pkgs_dir=first_writable_cache.pkgs_dir, + target_extracted_dirname=strip_pkg_extension(target_package_basename)[0], + record_or_spec=pref_or_spec, + sha256=sha256, + size=size, + md5=md5, + ) + return cache_action, extract_action + + def __init__(self, link_prefs): + """ + Args: + link_prefs (tuple[PackageRecord]): + A sequence of :class:`PackageRecord`s to ensure available in a known + package cache, typically for a follow-on :class:`UnlinkLinkTransaction`. + Here, "available" means the package tarball is both downloaded and extracted + to a package directory. + """ + self.link_precs = link_prefs + + log.debug( + "instantiating ProgressiveFetchExtract with\n %s\n", + "\n ".join(pkg_rec.dist_str() for pkg_rec in link_prefs), + ) + + self.paired_actions = {} # Map[pref, Tuple(CacheUrlAction, ExtractPackageAction)] + + self._prepared = False + self._executed = False + + @time_recorder("fetch_extract_prepare") + def prepare(self): + if self._prepared: + return + + # Download largest first + def by_size(prec: PackageRecord | MatchSpec): + # the test suite passes MatchSpec in here, is that an intentional + # feature? + try: + return int(prec.size) # type: ignore + except (LookupError, ValueError, AttributeError): + return 0 + + largest_first = sorted(self.link_precs, key=by_size, reverse=True) + + self.paired_actions.update( + (prec, self.make_actions_for_record(prec)) for prec in largest_first + ) + self._prepared = True + + @property + def cache_actions(self): + return tuple(axns[0] for axns in self.paired_actions.values() if axns[0]) + + @property + def extract_actions(self): + return tuple(axns[1] for axns in self.paired_actions.values() if axns[1]) + + def execute(self): + """ + Run each action in self.paired_actions. Each action in cache_actions + runs before its corresponding extract_actions. + """ + if self._executed: + return + if not self._prepared: + self.prepare() + + if context.dry_run: + raise RuntimeError("Cannot run .execute() in dry-run mode.") + + with get_progress_bar_context_manager() as pbar_context: + if self._executed: + return + if not self._prepared: + self.prepare() + + if not context.verbose and not context.quiet and not context.json: + print( + "\nDownloading and Extracting Packages:", + end="\n" if IS_INTERACTIVE else " ...working...", + ) + else: + log.debug( + "prepared package cache actions:\n" + " cache_actions:\n" + " %s\n" + " extract_actions:\n" + " %s\n", + "\n ".join(str(ca) for ca in self.cache_actions), + "\n ".join(str(ea) for ea in self.extract_actions), + ) + + exceptions = [] + progress_bars = {} + futures: list[Future] = [] + + cancelled_flag = False + + def cancelled(): + """ + Used to cancel download threads. + """ + nonlocal cancelled_flag + return cancelled_flag + + with ( + signal_handler(conda_signal_handler), + time_recorder("fetch_extract_execute"), + ThreadPoolExecutor(context.fetch_threads) as fetch_executor, + ThreadPoolExecutor(EXTRACT_THREADS) as extract_executor, + ): + for prec_or_spec, ( + cache_action, + extract_action, + ) in self.paired_actions.items(): + if cache_action is None and extract_action is None: + # Not sure when this is reached. + continue + + progress_bar = self._progress_bar( + prec_or_spec, context_manager=pbar_context, leave=False + ) + + progress_bars[prec_or_spec] = progress_bar + + future = fetch_executor.submit( + do_cache_action, + prec_or_spec, + cache_action, + progress_bar, + cancelled=cancelled, + ) + + future.add_done_callback( + partial( + done_callback, + actions=(cache_action,), + exceptions=exceptions, + progress_bar=progress_bar, + finish=True, + ) + ) + futures.append(future) + + try: + for completed_future in as_completed(futures): + futures.remove(completed_future) + prec_or_spec = completed_future.result() + + cache_action, extract_action = self.paired_actions[prec_or_spec] + extract_future = extract_executor.submit( + do_extract_action, + prec_or_spec, + extract_action, + progress_bars[prec_or_spec], + ) + extract_future.add_done_callback( + partial( + done_callback, + actions=(cache_action, extract_action), + exceptions=exceptions, + progress_bar=progress_bars[prec_or_spec], + finish=True, + ) + ) + except BaseException as e: + # We are interested in KeyboardInterrupt delivered to + # as_completed() while waiting, or any exception raised from + # completed_future.result(). cancelled_flag is checked in the + # progress callback to stop running transfers, shutdown() should + # prevent new downloads from starting. + cancelled_flag = True + for future in futures: # needed on top of .shutdown() + future.cancel() + # Has a Python >=3.9 cancel_futures= parameter that does not + # replace the above loop: + fetch_executor.shutdown(wait=False) + exceptions.append(e) + + for bar in progress_bars.values(): + bar.close() + + if not context.verbose and not context.quiet and not context.json: + if IS_INTERACTIVE: + print("\r") # move to column 0 + else: + print(" done") + + if exceptions: + # avoid printing one CancelledError() per pending download + not_cancelled = [ + exception + for exception in exceptions + if not isinstance(exception, CancelledError) + ] + raise CondaMultiError(not_cancelled) + + self._executed = True + + @staticmethod + def _progress_bar( + prec_or_spec, position=None, leave=False, context_manager=None + ) -> ProgressBarBase: + description = "" + if prec_or_spec.name and prec_or_spec.version: + description = "{}-{}".format( + prec_or_spec.name or "", prec_or_spec.version or "" + ) + size = getattr(prec_or_spec, "size", None) + size_str = size and human_bytes(size) or "" + if len(description) > 0: + description = "%-20.20s | " % description + if len(size_str) > 0: + description += "%-9s | " % size_str + + progress_bar = get_progress_bar( + description, + context_manager=context_manager, + position=position, + leave=leave, + enabled=not context.verbose and not context.quiet and IS_INTERACTIVE, + ) + + return progress_bar + + def __hash__(self): + return hash(self.link_precs) + + def __eq__(self, other): + return hash(self) == hash(other) + + +def do_cache_action(prec, cache_action, progress_bar, download_total=1.0, *, cancelled): + """This function gets called from `ProgressiveFetchExtract.execute`.""" + # pass None if already cached (simplifies code) + if not cache_action: + return prec + cache_action.verify() + + if not cache_action.url.startswith("file:/"): + + def progress_update_cache_action(pct_completed): + if cancelled(): + """ + Used to cancel dowload threads when parent thread is interrupted. + """ + raise CancelledError() + progress_bar.update_to(pct_completed * download_total) + + else: + download_total = 0 + progress_update_cache_action = None + + cache_action.execute(progress_update_cache_action) + return prec + + +def do_extract_action(prec, extract_action, progress_bar): + """This function gets called after do_cache_action completes.""" + # pass None if already extracted (simplifies code) + if not extract_action: + return prec + extract_action.verify() + # currently unable to do updates on extract; + # likely too fast to bother + extract_action.execute(None) + progress_bar.update_to(1.0) + return prec + + +def do_cleanup(actions): + for action in actions: + if action: + action.cleanup() + + +def do_reverse(actions): + for action in actions: + if action: + action.reverse() + + +def done_callback( + future: Future, + actions: tuple[CacheUrlAction | ExtractPackageAction, ...], + progress_bar: ProgressBarBase, + exceptions: list[Exception], + finish: bool = False, +): + try: + future.result() + except Exception as e: + # if it was interrupted with CTRL-C this might be BaseException and not + # get caught here, but conda's signal handler also converts that to + # CondaError which is just Exception. + do_reverse(reversed(actions)) + exceptions.append(e) + else: + do_cleanup(actions) + if finish: + progress_bar.finish() + progress_bar.refresh() diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/path_actions.py b/miniconda3/lib/python3.13/site-packages/conda/core/path_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed4daddcd6435d690e2cc17ffe5a1ccae165903 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/path_actions.py @@ -0,0 +1,1537 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Atomic actions that make up a package installation or removal transaction.""" + +from __future__ import annotations + +import re +import sys +from abc import ABCMeta, abstractmethod, abstractproperty +from itertools import chain +from logging import getLogger +from os.path import basename, dirname, getsize, isdir, isfile, join +from typing import TYPE_CHECKING +from uuid import uuid4 + +from .. import CondaError +from ..auxlib.ish import dals +from ..base.constants import CONDA_TEMP_EXTENSION +from ..base.context import context +from ..common.compat import on_win +from ..common.constants import TRACE +from ..common.path import ( + BIN_DIRECTORY, + get_leaf_directories, + get_python_noarch_target_path, + get_python_short_path, + parse_entry_point_def, + pyc_path, + url_to_path, + win_path_ok, +) +from ..common.serialize import json +from ..common.url import has_platform, path_to_url +from ..deprecations import deprecated +from ..exceptions import ( + CondaUpgradeError, + CondaVerificationError, + NotWritableError, + PaddingError, + SafetyError, +) +from ..gateways.connection.download import download +from ..gateways.disk.create import ( + compile_multiple_pyc, + copy, + create_hard_link_or_copy, + create_link, + create_python_entry_point, + make_menu, + mkdir_p, + write_as_json_to_file, +) +from ..gateways.disk.delete import rm_rf +from ..gateways.disk.permissions import make_writable +from ..gateways.disk.read import compute_sum, islink, lexists, read_index_json +from ..gateways.disk.update import backoff_rename, touch +from ..history import History +from ..models.channel import Channel +from ..models.enums import LinkType, NoarchType, PathEnum +from ..models.match_spec import MatchSpec +from ..models.records import ( + Link, + PackageCacheRecord, + PackageRecord, + PathDataV1, + PathsData, + PrefixRecord, +) +from .envs_manager import get_user_environments_txt_file, register_env, unregister_env +from .portability import _PaddingError, update_prefix +from .prefix_data import PrefixData + +if TYPE_CHECKING: + from collections.abc import Iterable + +try: + FileNotFoundError +except NameError: + FileNotFoundError = IOError + +log = getLogger(__name__) + +_MENU_RE = re.compile(r"^menu/.*\.json$", re.IGNORECASE) +REPR_IGNORE_KWARGS = ( + "transaction_context", + "package_info", + "hold_path", +) + + +class Action: + """Base class for path manipulation actions, including linking, unlinking, and others. + + Pre and post-transaction plugins should inherit this class to implement their + own verification, execution, reversing, and cleanup steps. These methods are + guaranteed to be called in the following order: + + 1. ``verify`` + 2. ``execute`` + 3. ``reverse`` (only if ``execute`` raises an exception) + 4. ``cleanup`` + + + :param transaction_context: Mapping between target prefixes and PrefixActions + instances + :param target_prefix: Target prefix for the action + :param unlink_precs: Package records to be unlinked + :param link_precs: Package records to link + :param remove_specs: Specs to be removed + :param update_specs: Specs to be updated + :param neutered_specs: Specs to be neutered + """ + + _verified = False + + def __init__( + self, + transaction_context: dict[str, str] | None = None, + target_prefix: str | None = None, + unlink_precs: Iterable[PackageRecord] | None = None, + link_precs: Iterable[PackageRecord] | None = None, + remove_specs: Iterable[MatchSpec] | None = None, + update_specs: Iterable[MatchSpec] | None = None, + neutered_specs: Iterable[MatchSpec] | None = None, + ): + self.transaction_context = transaction_context + self.target_prefix = target_prefix + self.unlink_precs = unlink_precs + self.link_precs = link_precs + self.remove_specs = remove_specs + self.update_specs = update_specs + self.neutered_specs = neutered_specs + + @abstractmethod + def verify(self) -> Exception | None: + """Carry out any pre-execution verification. + + Should set self._verified = True upon success. + + :return: On failure, this function should return (not raise!) an exception + object. At the end of the verification run, all errors will be raised as a + CondaMultiError. + """ + + @abstractmethod + def execute(self) -> None: + """Execute the action. + + Called after ``self.verify()``. If this function raises an exception, + ``self.reverse()`` will be called. + """ + + @abstractmethod + def reverse(self) -> None: + """Reverse what was done in execute. + + Called only if ``self.execute()`` raises an exception. + """ + pass + + @abstractmethod + def cleanup(self) -> None: + """Carry out any post-execution tasks.""" + pass + + @property + def verified(self): + return self._verified + + def __repr__(self): + args = ( + f"{key}={value!r}" + for key, value in vars(self).items() + if key not in REPR_IGNORE_KWARGS + ) + return "{}({})".format(self.__class__.__name__, ", ".join(args)) + + +deprecated.constant( + "25.9", + "26.3", + "_Action", + Action, + addendum="Use `conda.core.path_actions.Action` instead.", +) + + +class PathAction(Action, metaclass=ABCMeta): + @abstractproperty + def target_full_path(self): + raise NotImplementedError() + + +class MultiPathAction(Action, metaclass=ABCMeta): + @abstractproperty + def target_full_paths(self): + raise NotImplementedError() + + +class PrefixPathAction(PathAction, metaclass=ABCMeta): + def __init__(self, transaction_context, target_prefix, target_short_path): + self.transaction_context = transaction_context + self.target_prefix = target_prefix + self.target_short_path = target_short_path + + @property + def target_short_paths(self): + return (self.target_short_path,) + + @property + def target_full_path(self): + trgt, shrt_pth = self.target_prefix, self.target_short_path + if trgt is not None and shrt_pth is not None: + return join(trgt, win_path_ok(shrt_pth)) + else: + return None + + +# ###################################################### +# Creation of Paths within a Prefix +# ###################################################### + + +class CreateInPrefixPathAction(PrefixPathAction, metaclass=ABCMeta): + # All CreatePathAction subclasses must create a SINGLE new path + # the short/in-prefix version of that path must be returned by execute() + + def __init__( + self, + transaction_context, + package_info, + source_prefix, + source_short_path, + target_prefix, + target_short_path, + ): + super().__init__(transaction_context, target_prefix, target_short_path) + self.package_info = package_info + self.source_prefix = source_prefix + self.source_short_path = source_short_path + + def verify(self): + self._verified = True + + def cleanup(self): + # create actions typically won't need cleanup + pass + + @property + def source_full_path(self): + prfx, shrt_pth = self.source_prefix, self.source_short_path + return join(prfx, win_path_ok(shrt_pth)) if prfx and shrt_pth else None + + +class LinkPathAction(CreateInPrefixPathAction): + @classmethod + def create_file_link_actions( + cls, transaction_context, package_info, target_prefix, requested_link_type + ): + def get_prefix_replace(source_path_data): + if source_path_data.path_type == PathEnum.softlink: + link_type = LinkType.copy + prefix_placehoder, file_mode = "", None + elif source_path_data.prefix_placeholder: + link_type = LinkType.copy + prefix_placehoder = source_path_data.prefix_placeholder + file_mode = source_path_data.file_mode + elif source_path_data.no_link: + link_type = LinkType.copy + prefix_placehoder, file_mode = "", None + else: + link_type = requested_link_type + prefix_placehoder, file_mode = "", None + + return link_type, prefix_placehoder, file_mode + + def make_file_link_action(source_path_data): + # TODO: this inner function is still kind of a mess + noarch = package_info.repodata_record.noarch + if noarch is None and package_info.package_metadata is not None: + # Look in package metadata in case it was omitted from repodata (see issue #8311) + noarch = package_info.package_metadata.noarch + if noarch is not None: + noarch = noarch.type + if noarch == NoarchType.python: + sp_dir = transaction_context["target_site_packages_short_path"] + if sp_dir is None: + raise CondaError( + "Unable to determine python site-packages " + "dir in target_prefix!\nPlease make sure " + f"python is installed in {target_prefix}" + ) + target_short_path = get_python_noarch_target_path( + source_path_data.path, sp_dir + ) + elif noarch is None or noarch == NoarchType.generic: + target_short_path = source_path_data.path + else: + raise CondaUpgradeError( + dals( + """ + The current version of conda is too old to install this package. + Please update conda.""" + ) + ) + + link_type, placeholder, fmode = get_prefix_replace(source_path_data) + + if placeholder: + return PrefixReplaceLinkAction( + transaction_context, + package_info, + package_info.extracted_package_dir, + source_path_data.path, + target_prefix, + target_short_path, + requested_link_type, + placeholder, + fmode, + source_path_data, + ) + else: + return LinkPathAction( + transaction_context, + package_info, + package_info.extracted_package_dir, + source_path_data.path, + target_prefix, + target_short_path, + link_type, + source_path_data, + ) + + return tuple( + make_file_link_action(spi) for spi in package_info.paths_data.paths + ) + + @classmethod + def create_directory_actions( + cls, + transaction_context, + package_info, + target_prefix, + requested_link_type, + file_link_actions, + ): + leaf_directories = get_leaf_directories( + axn.target_short_path for axn in file_link_actions + ) + return tuple( + cls( + transaction_context, + package_info, + None, + None, + target_prefix, + directory_short_path, + LinkType.directory, + None, + ) + for directory_short_path in leaf_directories + ) + + @classmethod + def create_python_entry_point_windows_exe_action( + cls, + transaction_context, + package_info, + target_prefix, + requested_link_type, + entry_point_def, + ): + source_directory = context.conda_prefix + source_short_path = "Scripts/conda.exe" + command, _, _ = parse_entry_point_def(entry_point_def) + target_short_path = f"Scripts/{command}.exe" + source_path_data = PathDataV1( + _path=target_short_path, + path_type=PathEnum.windows_python_entry_point_exe, + ) + return cls( + transaction_context, + package_info, + source_directory, + source_short_path, + target_prefix, + target_short_path, + requested_link_type, + source_path_data, + ) + + def __init__( + self, + transaction_context, + package_info, + extracted_package_dir, + source_short_path, + target_prefix, + target_short_path, + link_type, + source_path_data, + ): + super().__init__( + transaction_context, + package_info, + extracted_package_dir, + source_short_path, + target_prefix, + target_short_path, + ) + self.link_type = link_type + self._execute_successful = False + self.source_path_data = source_path_data + self.prefix_path_data = None + + def verify(self): + if self.link_type != LinkType.directory and not lexists( + self.source_full_path + ): # pragma: no cover + return CondaVerificationError( + dals( + f""" + The package for {self.package_info.repodata_record.name} located at {self.package_info.extracted_package_dir} + appears to be corrupted. The path '{self.source_short_path}' + specified in the package manifest cannot be found. + """ + ) + ) + + source_path_data = self.source_path_data + try: + source_path_type = source_path_data.path_type + except AttributeError: + source_path_type = None + if source_path_type in PathEnum.basic_types: + # this let's us keep the non-generic path types like windows_python_entry_point_exe + source_path_type = None + + if self.link_type == LinkType.directory: + self.prefix_path_data = None + elif self.link_type == LinkType.softlink: + self.prefix_path_data = PathDataV1.from_objects( + self.source_path_data, + path_type=source_path_type or PathEnum.softlink, + ) + elif ( + self.link_type == LinkType.copy + and source_path_data.path_type == PathEnum.softlink + ): + self.prefix_path_data = PathDataV1.from_objects( + self.source_path_data, + path_type=source_path_type or PathEnum.softlink, + ) + + elif source_path_data.path_type == PathEnum.hardlink: + try: + reported_size_in_bytes = source_path_data.size_in_bytes + except AttributeError: + reported_size_in_bytes = None + source_size_in_bytes = 0 + if reported_size_in_bytes: + source_size_in_bytes = getsize(self.source_full_path) + if reported_size_in_bytes != source_size_in_bytes: + return SafetyError( + dals( + f""" + The package for {self.package_info.repodata_record.name} located at {self.package_info.extracted_package_dir} + appears to be corrupted. The path '{self.source_short_path}' + has an incorrect size. + reported size: {reported_size_in_bytes} bytes + actual size: {source_size_in_bytes} bytes + """ + ) + ) + + try: + reported_sha256 = source_path_data.sha256 + except AttributeError: + reported_sha256 = None + # sha256 is expensive. Only run if file sizes agree, and then only if enabled + if ( + source_size_in_bytes + and reported_size_in_bytes == source_size_in_bytes + and context.extra_safety_checks + ): + source_sha256 = compute_sum(self.source_full_path, "sha256") + + if reported_sha256 and reported_sha256 != source_sha256: + return SafetyError( + dals( + f""" + The package for {self.package_info.repodata_record.name} located at {self.package_info.extracted_package_dir} + appears to be corrupted. The path '{self.source_short_path}' + has a sha256 mismatch. + reported sha256: {reported_sha256} + actual sha256: {source_sha256} + """ + ) + ) + self.prefix_path_data = PathDataV1.from_objects( + source_path_data, + sha256=reported_sha256, + sha256_in_prefix=reported_sha256, + path_type=source_path_type or PathEnum.hardlink, + ) + elif source_path_data.path_type == PathEnum.windows_python_entry_point_exe: + self.prefix_path_data = source_path_data + else: + raise NotImplementedError() + + self._verified = True + + def execute(self): + log.log(TRACE, "linking %s => %s", self.source_full_path, self.target_full_path) + create_link( + self.source_full_path, + self.target_full_path, + self.link_type, + force=context.force, + ) + self._execute_successful = True + + def reverse(self): + if self._execute_successful: + log.log(TRACE, "reversing link creation %s", self.target_prefix) + if not isdir(self.target_full_path): + rm_rf(self.target_full_path, clean_empty_parents=True) + + +class PrefixReplaceLinkAction(LinkPathAction): + def __init__( + self, + transaction_context, + package_info, + extracted_package_dir, + source_short_path, + target_prefix, + target_short_path, + link_type, + prefix_placeholder, + file_mode, + source_path_data, + ): + # This link_type used in execute(). Make sure we always respect LinkType.copy request. + link_type = LinkType.copy if link_type == LinkType.copy else LinkType.hardlink + super().__init__( + transaction_context, + package_info, + extracted_package_dir, + source_short_path, + target_prefix, + target_short_path, + link_type, + source_path_data, + ) + self.prefix_placeholder = prefix_placeholder + self.file_mode = file_mode + self.intermediate_path = None + + def verify(self): + validation_error = super().verify() + if validation_error: + return validation_error + + if islink(self.source_full_path): + log.log( + TRACE, + "ignoring prefix update for symlink with source path %s", + self.source_full_path, + ) + # return + raise RuntimeError( + f"Ignoring prefix update for symlink with source path {self.source_full_path}" + ) + + mkdir_p(self.transaction_context["temp_dir"]) + self.intermediate_path = join( + self.transaction_context["temp_dir"], str(uuid4()) + ) + + log.log( + TRACE, "copying %s => %s", self.source_full_path, self.intermediate_path + ) + create_link(self.source_full_path, self.intermediate_path, LinkType.copy) + make_writable(self.intermediate_path) + + try: + log.log(TRACE, "rewriting prefixes in %s", self.target_full_path) + update_prefix( + self.intermediate_path, + context.target_prefix_override or self.target_prefix, + self.prefix_placeholder, + self.file_mode, + subdir=self.package_info.repodata_record.subdir, + ) + except _PaddingError: + raise PaddingError( + self.target_full_path, + self.prefix_placeholder, + len(self.prefix_placeholder), + ) + + sha256_in_prefix = compute_sum(self.intermediate_path, "sha256") + + self.prefix_path_data = PathDataV1.from_objects( + self.prefix_path_data, + file_mode=self.file_mode, + path_type=PathEnum.hardlink, + prefix_placeholder=self.prefix_placeholder, + sha256_in_prefix=sha256_in_prefix, + ) + + self._verified = True + + def execute(self): + if not self._verified: + self.verify() + source_path = self.intermediate_path or self.source_full_path + log.log(TRACE, "linking %s => %s", source_path, self.target_full_path) + create_link(source_path, self.target_full_path, self.link_type) + self._execute_successful = True + + +class MakeMenuAction(CreateInPrefixPathAction): + @classmethod + def create_actions( + cls, transaction_context, package_info, target_prefix, requested_link_type + ): + shorcuts_lower = [name.lower() for name in (context.shortcuts_only or ())] + if context.shortcuts and ( + not context.shortcuts_only + or (shorcuts_lower and package_info.name.lower() in shorcuts_lower) + ): + return tuple( + cls(transaction_context, package_info, target_prefix, spi.path) + for spi in package_info.paths_data.paths + if bool(_MENU_RE.match(spi.path)) + ) + else: + return () + + def __init__( + self, transaction_context, package_info, target_prefix, target_short_path + ): + super().__init__( + transaction_context, + package_info, + None, + None, + target_prefix, + target_short_path, + ) + self._execute_successful = False + + def execute(self): + log.log(TRACE, "making menu for %s", self.target_full_path) + make_menu(self.target_prefix, self.target_short_path, remove=False) + self._execute_successful = True + + def reverse(self): + if self._execute_successful: + log.log(TRACE, "removing menu for %s", self.target_full_path) + make_menu(self.target_prefix, self.target_short_path, remove=True) + + +class CompileMultiPycAction(MultiPathAction): + @classmethod + def create_actions( + cls, + transaction_context, + package_info, + target_prefix, + requested_link_type, + file_link_actions, + ): + noarch = package_info.package_metadata and package_info.package_metadata.noarch + if noarch is not None and noarch.type == NoarchType.python: + noarch_py_file_re = re.compile(r"^site-packages[/\\][^\t\n\r\f\v]+\.py$") + py_ver = transaction_context["target_python_version"] + py_files = tuple( + axn.target_short_path + for axn in file_link_actions + if getattr(axn, "source_short_path") + and noarch_py_file_re.match(axn.source_short_path) + ) + pyc_files = tuple(pyc_path(pf, py_ver) for pf in py_files) + return ( + cls( + transaction_context, + package_info, + target_prefix, + py_files, + pyc_files, + ), + ) + else: + return () + + def __init__( + self, + transaction_context, + package_info, + target_prefix, + source_short_paths, + target_short_paths, + ): + self.transaction_context = transaction_context + self.package_info = package_info + self.target_prefix = target_prefix + self.source_short_paths = source_short_paths + self.target_short_paths = target_short_paths + self.prefix_path_data = None + self.prefix_paths_data = [ + PathDataV1( + _path=p, + path_type=PathEnum.pyc_file, + ) + for p in self.target_short_paths + ] + self._execute_successful = False + + @property + def target_full_paths(self): + def join_or_none(prefix, short_path): + if prefix is None or short_path is None: + return None + else: + return join(prefix, win_path_ok(short_path)) + + return (join_or_none(self.target_prefix, p) for p in self.target_short_paths) + + @property + def source_full_paths(self): + def join_or_none(prefix, short_path): + if prefix is None or short_path is None: + return None + else: + return join(prefix, win_path_ok(short_path)) + + return (join_or_none(self.target_prefix, p) for p in self.source_short_paths) + + def verify(self): + self._verified = True + + def cleanup(self): + # create actions typically won't need cleanup + pass + + def execute(self): + # compile_pyc is sometimes expected to fail, for example a python 3.6 file + # installed into a python 2 environment, but no code paths actually importing it + # technically then, this file should be removed from the manifest in conda-meta, but + # at the time of this writing that's not currently happening + log.log(TRACE, "compiling %s", " ".join(self.target_full_paths)) + target_python_version = self.transaction_context["target_python_version"] + python_short_path = get_python_short_path(target_python_version) + python_full_path = join(self.target_prefix, win_path_ok(python_short_path)) + compile_multiple_pyc( + python_full_path, + self.source_full_paths, + self.target_full_paths, + self.target_prefix, + self.transaction_context["target_python_version"], + ) + self._execute_successful = True + + # Update prefix_paths_data with the file sizes now that the .pyc files exist. + # Note: when used via AggregateCompileMultiPycAction, this updates the + # aggregate's prefix_paths_data. The aggregate's execute() will separately + # update each individual action's data. + for path_data in self.prefix_paths_data: + pyc_full_path = join(self.target_prefix, win_path_ok(path_data._path)) + try: + path_data.size_in_bytes = getsize(pyc_full_path) + except OSError: + log.log(TRACE, "could not get size for %s", pyc_full_path) + + def reverse(self): + # this removes all pyc files even if they were not created + if self._execute_successful: + log.log( + TRACE, "reversing pyc creation %s", " ".join(self.target_full_paths) + ) + for target_full_path in self.target_full_paths: + rm_rf(target_full_path) + + +class AggregateCompileMultiPycAction(CompileMultiPycAction): + """Bunch up all of our compile actions, so that they all get carried out at once. + This avoids clobbering and is faster when we have several individual packages requiring + compilation. + """ + + def __init__(self, *individuals, **kw): + self._individuals = individuals + transaction_context = individuals[0].transaction_context + # not used; doesn't matter + package_info = individuals[0].package_info + target_prefix = individuals[0].target_prefix + source_short_paths = set() + target_short_paths = set() + for individual in individuals: + source_short_paths.update(individual.source_short_paths) + target_short_paths.update(individual.target_short_paths) + super().__init__( + transaction_context, + package_info, + target_prefix, + source_short_paths, + target_short_paths, + ) + + def execute(self): + super().execute() + # Update each individual action's prefix_paths_data with file sizes. + # The manifest is written using individual actions' data, not the aggregate's. + for individual in self._individuals: + for path_data in individual.prefix_paths_data: + pyc_full_path = join(self.target_prefix, win_path_ok(path_data._path)) + try: + path_data.size_in_bytes = getsize(pyc_full_path) + except OSError: + log.log(TRACE, "could not get size for %s", pyc_full_path) + + +class CreatePythonEntryPointAction(CreateInPrefixPathAction): + @classmethod + def create_actions( + cls, transaction_context, package_info, target_prefix, requested_link_type + ): + noarch = package_info.package_metadata and package_info.package_metadata.noarch + if noarch is not None and noarch.type == NoarchType.python: + + def this_triplet(entry_point_def): + command, module, func = parse_entry_point_def(entry_point_def) + target_short_path = f"{BIN_DIRECTORY}/{command}" + if on_win: + target_short_path += "-script.py" + return target_short_path, module, func + + actions = tuple( + cls( + transaction_context, + package_info, + target_prefix, + *this_triplet(ep_def), + ) + for ep_def in noarch.entry_points or () + ) + + if on_win: # pragma: unix no cover + actions += tuple( + LinkPathAction.create_python_entry_point_windows_exe_action( + transaction_context, + package_info, + target_prefix, + requested_link_type, + ep_def, + ) + for ep_def in noarch.entry_points or () + ) + + return actions + else: + return () + + def __init__( + self, + transaction_context, + package_info, + target_prefix, + target_short_path, + module, + func, + ): + super().__init__( + transaction_context, + package_info, + None, + None, + target_prefix, + target_short_path, + ) + self.module = module + self.func = func + + if on_win: + path_type = PathEnum.windows_python_entry_point_script + else: + path_type = PathEnum.unix_python_entry_point + self.prefix_path_data = PathDataV1( + _path=self.target_short_path, + path_type=path_type, + ) + + self._execute_successful = False + + def execute(self): + log.log(TRACE, "creating python entry point %s", self.target_full_path) + if on_win: + python_full_path = None + else: + target_python_version = self.transaction_context["target_python_version"] + python_short_path = get_python_short_path(target_python_version) + python_full_path = join( + context.target_prefix_override or self.target_prefix, + win_path_ok(python_short_path), + ) + + create_python_entry_point( + self.target_full_path, python_full_path, self.module, self.func + ) + try: + self.prefix_path_data.size_in_bytes = getsize(self.target_full_path) + except OSError: + log.log(TRACE, "could not get size for %s", self.target_full_path) + self._execute_successful = True + + def reverse(self): + if self._execute_successful: + log.log( + TRACE, "reversing python entry point creation %s", self.target_full_path + ) + rm_rf(self.target_full_path) + + +class CreatePrefixRecordAction(CreateInPrefixPathAction): + # this is the action that creates a packages json file in the conda-meta/ directory + + @classmethod + def create_actions( + cls, + transaction_context, + package_info, + target_prefix, + requested_link_type, + requested_spec, + all_link_path_actions, + ): + extracted_package_dir = package_info.extracted_package_dir + target_short_path = f"conda-meta/{basename(extracted_package_dir)}.json" + return ( + cls( + transaction_context, + package_info, + target_prefix, + target_short_path, + requested_link_type, + requested_spec, + all_link_path_actions, + ), + ) + + def __init__( + self, + transaction_context, + package_info, + target_prefix, + target_short_path, + requested_link_type, + requested_spec, + all_link_path_actions, + ): + super().__init__( + transaction_context, + package_info, + None, + None, + target_prefix, + target_short_path, + ) + self.requested_link_type = requested_link_type + self.requested_spec = requested_spec + self.all_link_path_actions = list(all_link_path_actions) + self._execute_successful = False + + def execute(self): + link = Link( + source=self.package_info.extracted_package_dir, + type=self.requested_link_type, + ) + extracted_package_dir = self.package_info.extracted_package_dir + package_tarball_full_path = self.package_info.package_tarball_full_path + + def files_from_action(link_path_action): + if isinstance(link_path_action, CompileMultiPycAction): + return link_path_action.target_short_paths + else: + return ( + (link_path_action.target_short_path,) + if isinstance(link_path_action, CreateInPrefixPathAction) + and ( + not hasattr(link_path_action, "link_type") + or link_path_action.link_type != LinkType.directory + ) + else () + ) + + def paths_from_action(link_path_action): + if isinstance(link_path_action, CompileMultiPycAction): + return link_path_action.prefix_paths_data + else: + if ( + not hasattr(link_path_action, "prefix_path_data") + or link_path_action.prefix_path_data is None + ): + return () + else: + return (link_path_action.prefix_path_data,) + + files = list( + chain.from_iterable( + files_from_action(x) for x in self.all_link_path_actions if x + ) + ) + paths_data = PathsData( + paths_version=1, + paths=chain.from_iterable( + paths_from_action(x) for x in self.all_link_path_actions if x + ), + ) + + self.prefix_record = PrefixRecord.from_objects( + self.package_info.repodata_record, + # self.package_info.index_json_record, + self.package_info.package_metadata, + requested_spec=str(self.requested_spec), + paths_data=paths_data, + files=files, + link=link, + url=self.package_info.url, + extracted_package_dir=extracted_package_dir, + package_tarball_full_path=package_tarball_full_path, + ) + + log.log(TRACE, "creating linked package record %s", self.target_full_path) + PrefixData(self.target_prefix).insert(self.prefix_record) + self._execute_successful = True + + def reverse(self): + log.log( + TRACE, "reversing linked package record creation %s", self.target_full_path + ) + if self._execute_successful: + PrefixData(self.target_prefix).remove( + self.package_info.repodata_record.name + ) + + +class UpdateHistoryAction(CreateInPrefixPathAction): + @classmethod + def create_actions( + cls, + transaction_context, + target_prefix, + remove_specs, + update_specs, + neutered_specs, + ): + target_short_path = join("conda-meta", "history") + return ( + cls( + transaction_context, + target_prefix, + target_short_path, + remove_specs, + update_specs, + neutered_specs, + ), + ) + + def __init__( + self, + transaction_context, + target_prefix, + target_short_path, + remove_specs, + update_specs, + neutered_specs, + ): + super().__init__( + transaction_context, None, None, None, target_prefix, target_short_path + ) + self.remove_specs = remove_specs + self.update_specs = update_specs + self.neutered_specs = neutered_specs + + self.hold_path = self.target_full_path + CONDA_TEMP_EXTENSION + + def execute(self): + log.log(TRACE, "updating environment history %s", self.target_full_path) + + if lexists(self.target_full_path): + copy(self.target_full_path, self.hold_path) + + h = History(self.target_prefix) + if not isfile(h.path): + PrefixData(self.target_prefix).set_creation_time() + h.update() + h.write_specs(self.remove_specs, self.update_specs, self.neutered_specs) + + def reverse(self): + if lexists(self.hold_path): + log.log(TRACE, "moving %s => %s", self.hold_path, self.target_full_path) + backoff_rename(self.hold_path, self.target_full_path, force=True) + if isfile(hpath := History(self.target_prefix).path): + rm_rf(hpath) + + def cleanup(self): + rm_rf(self.hold_path) + + +class RegisterEnvironmentLocationAction(PathAction): + def __init__(self, transaction_context, target_prefix): + self.transaction_context = transaction_context + self.target_prefix = target_prefix + + self._execute_successful = False + + def verify(self): + user_environments_txt_file = get_user_environments_txt_file() + try: + touch(user_environments_txt_file, mkdir=True, sudo_safe=True) + self._verified = True + except NotWritableError: + log.warning( + "Unable to create environments file. Path not writable.\n" + " environment location: %s\n", + user_environments_txt_file, + ) + + def execute(self): + log.log(TRACE, "registering environment in catalog %s", self.target_prefix) + + register_env(self.target_prefix) + self._execute_successful = True + + def reverse(self): + pass + + def cleanup(self): + pass + + @property + def target_full_path(self): + raise NotImplementedError() + + +# ###################################################### +# Removal of Paths within a Prefix +# ###################################################### + + +class RemoveFromPrefixPathAction(PrefixPathAction, metaclass=ABCMeta): + def __init__( + self, transaction_context, linked_package_data, target_prefix, target_short_path + ): + super().__init__(transaction_context, target_prefix, target_short_path) + self.linked_package_data = linked_package_data + + def verify(self): + # inability to remove will trigger a rollback + # can't definitely know if path can be removed until it's attempted and failed + self._verified = True + + +class UnlinkPathAction(RemoveFromPrefixPathAction): + def __init__( + self, + transaction_context, + linked_package_data, + target_prefix, + target_short_path, + link_type=LinkType.hardlink, + ): + super().__init__( + transaction_context, linked_package_data, target_prefix, target_short_path + ) + self.holding_short_path = self.target_short_path + CONDA_TEMP_EXTENSION + self.holding_full_path = self.target_full_path + CONDA_TEMP_EXTENSION + self.link_type = link_type + + def execute(self): + if self.link_type != LinkType.directory: + log.log( + TRACE, + "renaming %s => %s", + self.target_short_path, + self.holding_short_path, + ) + backoff_rename(self.target_full_path, self.holding_full_path, force=True) + + def reverse(self): + if self.link_type != LinkType.directory and lexists(self.holding_full_path): + log.log( + TRACE, + "reversing rename %s => %s", + self.holding_short_path, + self.target_short_path, + ) + backoff_rename(self.holding_full_path, self.target_full_path, force=True) + + def cleanup(self): + if not isdir(self.holding_full_path): + rm_rf(self.holding_full_path, clean_empty_parents=True) + + +class RemoveMenuAction(RemoveFromPrefixPathAction): + @classmethod + def create_actions(cls, transaction_context, linked_package_data, target_prefix): + return tuple( + cls(transaction_context, linked_package_data, target_prefix, trgt) + for trgt in linked_package_data.files + if bool(_MENU_RE.match(trgt)) + ) + + def __init__( + self, transaction_context, linked_package_data, target_prefix, target_short_path + ): + super().__init__( + transaction_context, linked_package_data, target_prefix, target_short_path + ) + + def execute(self): + log.log(TRACE, "removing menu for %s ", self.target_prefix) + make_menu(self.target_prefix, self.target_short_path, remove=True) + + def reverse(self): + log.log(TRACE, "re-creating menu for %s ", self.target_prefix) + make_menu(self.target_prefix, self.target_short_path, remove=False) + + def cleanup(self): + pass + + +class RemoveLinkedPackageRecordAction(UnlinkPathAction): + def __init__( + self, transaction_context, linked_package_data, target_prefix, target_short_path + ): + super().__init__( + transaction_context, linked_package_data, target_prefix, target_short_path + ) + + def execute(self): + super().execute() + PrefixData(self.target_prefix).remove(self.linked_package_data.name) + + def reverse(self): + super().reverse() + PrefixData(self.target_prefix)._load_single_record(self.target_full_path) + + +class UnregisterEnvironmentLocationAction(PathAction): + def __init__(self, transaction_context, target_prefix): + self.transaction_context = transaction_context + self.target_prefix = target_prefix + + self._execute_successful = False + + def verify(self): + self._verified = True + + def execute(self): + log.log(TRACE, "unregistering environment in catalog %s", self.target_prefix) + + unregister_env(self.target_prefix) + self._execute_successful = True + + def reverse(self): + pass + + def cleanup(self): + pass + + @property + def target_full_path(self): + raise NotImplementedError() + + +# ###################################################### +# Fetch / Extract Actions +# ###################################################### + + +class CacheUrlAction(PathAction): + def __init__( + self, + url, + target_pkgs_dir, + target_package_basename, + sha256=None, + size=None, + md5=None, + ): + self.url = url + self.target_pkgs_dir = target_pkgs_dir + self.target_package_basename = target_package_basename + self.sha256 = sha256 + self.size = size + self.md5 = md5 + self.hold_path = self.target_full_path + CONDA_TEMP_EXTENSION + + def verify(self): + if "::" in self.url: + raise ValueError("URL cannot contain '::'") + self._verified = True + + def execute(self, progress_update_callback=None): + # I hate inline imports, but I guess it's ok since we're importing from the conda.core + # The alternative is passing the PackageCache class to CacheUrlAction __init__ + from .package_cache_data import PackageCacheData + + target_package_cache = PackageCacheData(self.target_pkgs_dir) + + log.log(TRACE, "caching url %s => %s", self.url, self.target_full_path) + + if lexists(self.hold_path): + rm_rf(self.hold_path) + + if lexists(self.target_full_path): + if self.url.startswith("file:/") and self.url == path_to_url( + self.target_full_path + ): + # the source and destination are the same file, so we're done + return + else: + backoff_rename(self.target_full_path, self.hold_path, force=True) + + if self.url.startswith("file:/"): + source_path = url_to_path(self.url) + self._execute_local( + source_path, target_package_cache, progress_update_callback + ) + else: + self._execute_channel(target_package_cache, progress_update_callback) + + def _execute_local( + self, source_path, target_package_cache, progress_update_callback=None + ): + from .package_cache_data import PackageCacheData + + if dirname(source_path) in context.pkgs_dirs: + # if url points to another package cache, link to the writable cache + create_hard_link_or_copy(source_path, self.target_full_path) + source_package_cache = PackageCacheData(dirname(source_path)) + + # the package is already in a cache, so it came from a remote url somewhere; + # make sure that remote url is the most recent url in the + # writable cache urls.txt + origin_url = source_package_cache._urls_data.get_url( + self.target_package_basename + ) + if origin_url and has_platform(origin_url, context.known_subdirs): + target_package_cache._urls_data.add_url(origin_url) + else: + # so our tarball source isn't a package cache, but that doesn't mean it's not + # in another package cache somewhere + # let's try to find the actual, remote source url by matching md5sums, and then + # record that url as the remote source url in urls.txt + # we do the search part of this operation before the create_link so that we + # don't md5sum-match the file created by 'create_link' + # there is no point in looking for the tarball in the cache that we are writing + # this file into because we have already removed the previous file if there was + # any. This also makes sure that we ignore the md5sum of a possible extracted + # directory that might exist in this cache because we are going to overwrite it + # anyway when we extract the tarball. + source_md5sum = compute_sum(source_path, "md5") + exclude_caches = (self.target_pkgs_dir,) + pc_entry = PackageCacheData.tarball_file_in_cache( + source_path, source_md5sum, exclude_caches=exclude_caches + ) + + if pc_entry: + origin_url = target_package_cache._urls_data.get_url( + pc_entry.extracted_package_dir + ) + else: + origin_url = None + + # copy the tarball to the writable cache + create_link( + source_path, + self.target_full_path, + link_type=LinkType.copy, + force=context.force, + ) + + if origin_url and has_platform(origin_url, context.known_subdirs): + target_package_cache._urls_data.add_url(origin_url) + else: + target_package_cache._urls_data.add_url(self.url) + + def _execute_channel(self, target_package_cache, progress_update_callback=None): + kwargs = {} + if self.size is not None: + kwargs["size"] = self.size + if self.sha256: + kwargs["sha256"] = self.sha256 + elif self.md5: + kwargs["md5"] = self.md5 + download( + self.url, + self.target_full_path, + progress_update_callback=progress_update_callback, + **kwargs, + ) + target_package_cache._urls_data.add_url(self.url) + + def reverse(self): + if lexists(self.hold_path): + log.log(TRACE, "moving %s => %s", self.hold_path, self.target_full_path) + backoff_rename(self.hold_path, self.target_full_path, force=True) + + def cleanup(self): + rm_rf(self.hold_path) + + @property + def target_full_path(self): + return join(self.target_pkgs_dir, self.target_package_basename) + + def __str__(self): + return f"CacheUrlAction" + + +class ExtractPackageAction(PathAction): + def __init__( + self, + source_full_path, + target_pkgs_dir, + target_extracted_dirname, + record_or_spec, + sha256, + size, + md5, + ): + self.source_full_path = source_full_path + self.target_pkgs_dir = target_pkgs_dir + self.target_extracted_dirname = target_extracted_dirname + self.hold_path = self.target_full_path + CONDA_TEMP_EXTENSION + self.record_or_spec = record_or_spec + self.sha256 = sha256 + self.size = size + self.md5 = md5 + + def verify(self): + self._verified = True + + def execute(self, progress_update_callback=None): + # I hate inline imports, but I guess it's ok since we're importing from the conda.core + # The alternative is passing the the classes to ExtractPackageAction __init__ + from .package_cache_data import PackageCacheData + + log.log( + TRACE, "extracting %s => %s", self.source_full_path, self.target_full_path + ) + + if lexists(self.target_full_path): + rm_rf(self.target_full_path) + + # extract the package using the appropriate plugin + context.plugin_manager.extract_package( + self.source_full_path, + self.target_full_path, + ) + + try: + raw_index_json = read_index_json(self.target_full_path) + except (OSError, json.JSONDecodeError, FileNotFoundError): + # At this point, we can assume the package tarball is bad. + # Remove everything and move on. + print( + f"ERROR: Encountered corrupt package tarball at {self.source_full_path}. Conda has " + "left it in place. Please report this to the maintainers " + "of the package." + ) + sys.exit(1) + + if isinstance(self.record_or_spec, MatchSpec): + url = self.record_or_spec.get_raw_value("url") + if not url: + raise ValueError("URL cannot be empty.") + channel = ( + Channel(url) + if has_platform(url, context.known_subdirs) + else Channel(None) + ) + fn = basename(url) + sha256 = self.sha256 or compute_sum(self.source_full_path, "sha256") + size = getsize(self.source_full_path) + if self.size is not None and size != self.size: + raise RuntimeError( + f"Computed size ({size}) does not match expected value {self.size}" + ) + md5 = self.md5 or compute_sum(self.source_full_path, "md5") + repodata_record = PackageRecord.from_objects( + raw_index_json, + url=url, + channel=channel, + fn=fn, + sha256=sha256, + size=size, + md5=md5, + ) + else: + repodata_record = PackageRecord.from_objects( + self.record_or_spec, raw_index_json + ) + + repodata_record_path = join( + self.target_full_path, "info", "repodata_record.json" + ) + write_as_json_to_file(repodata_record_path, repodata_record) + + target_package_cache = PackageCacheData(self.target_pkgs_dir) + package_cache_record = PackageCacheRecord.from_objects( + repodata_record, + package_tarball_full_path=self.source_full_path, + extracted_package_dir=self.target_full_path, + ) + target_package_cache.insert(package_cache_record) + + def reverse(self): + rm_rf(self.target_full_path) + if lexists(self.hold_path): + log.log(TRACE, "moving %s => %s", self.hold_path, self.target_full_path) + rm_rf(self.target_full_path) + backoff_rename(self.hold_path, self.target_full_path) + + def cleanup(self): + rm_rf(self.hold_path) + + @property + def target_full_path(self): + return join(self.target_pkgs_dir, self.target_extracted_dirname) + + def __str__(self): + return f"ExtractPackageAction" diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/portability.py b/miniconda3/lib/python3.13/site-packages/conda/core/portability.py new file mode 100644 index 0000000000000000000000000000000000000000..543dff9c172abb7be3d74a11cc4ee10b805cdec7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/portability.py @@ -0,0 +1,392 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools for cross-OS portability.""" + +from __future__ import annotations + +import os +import re +import struct +import subprocess +from logging import getLogger +from os.path import basename, realpath + +from ..auxlib.ish import dals +from ..base.constants import PREFIX_PLACEHOLDER +from ..base.context import context +from ..common.compat import on_linux, on_mac, on_win +from ..exceptions import BinaryPrefixReplacementError, CondaIOError +from ..gateways.disk.update import CancelOperation, update_file_in_place_as_binary +from ..models.enums import FileMode + +log = getLogger(__name__) + + +# three capture groups: whole_shebang, executable, options +SHEBANG_REGEX = ( + rb"^(#!" # pretty much the whole match string + rb"(?:[ ]*)" # allow spaces between #! and beginning of the executable path + rb"(/(?:\\ |[^ \n\r\t])*)" # the executable is the next text block without an escaped space or non-space whitespace character + rb"(.*)" # the rest of the line can contain option flags + rb")$" +) # end whole_shebang group + +MAX_SHEBANG_LENGTH = 127 if on_linux else 512 # Not used on Windows + +# These are the most common file encodings that we run across when having to replace our +# PREFIX_PLACEHOLDER string. They apply to binary and text formats. +# More information/discussion: https://github.com/conda/conda/pull/9946 +POPULAR_ENCODINGS = ( + "utf-8", + "utf-16-le", + "utf-16-be", + "utf-32-le", + "utf-32-be", +) + + +class _PaddingError(Exception): + pass + + +def _subdir_is_win(subdir: str) -> bool: + """ + Determine if the given `subdir` corresponds to a Windows operating system. + + :param subdir: The subdirectory name which may contain an OS identifier. + :return: Returns True if `subdir` indicates a Windows OS; otherwise, False. + """ + if "-" in subdir: + os, _ = subdir.lower().split("-", 1) + return os == "win" + else: + # For noarch, check that we are running on windows + return on_win + + +def update_prefix( + path: str, + new_prefix: str, + placeholder: str = PREFIX_PLACEHOLDER, + mode: FileMode = FileMode.text, + subdir: str = context.subdir, +) -> None: + """ + Update the prefix in a file or directory. + + :param path: The path to the file or directory. + :param new_prefix: The new prefix to replace the old prefix with. + :param placeholder: The placeholder to use for the old prefix. Defaults to PREFIX_PLACEHOLDER. + :param mode: The file mode. Defaults to FileMode.text. + :param subdir: The subdirectory. Defaults to context.subdir. + """ + if _subdir_is_win(subdir) and mode == FileMode.text: + # force all prefix replacements to forward slashes to simplify need to escape backslashes + # replace with unix-style path separators + new_prefix = new_prefix.replace("\\", "/") + + def _update_prefix(original_data): + """ + A function that updates the prefix in a file or directory. + + :param original_data: The original data to be updated. + + :return: The updated data after prefix replacement. + """ + # Step 1. do all prefix replacement + data = replace_prefix(mode, original_data, placeholder, new_prefix, subdir) + + # Step 2. if the shebang is too long or the new prefix contains spaces, shorten it using + # /usr/bin/env trick -- NOTE: this trick assumes the environment WILL BE activated + if not _subdir_is_win(subdir): + data = replace_long_shebang(mode, data) + + # Step 3. if the before and after content is the same, skip writing + if data == original_data: + raise CancelOperation() + + # Step 4. if we have a binary file, make sure the byte size is the same before + # and after the update + if mode == FileMode.binary and len(data) != len(original_data): + raise BinaryPrefixReplacementError( + path, placeholder, new_prefix, len(original_data), len(data) + ) + + return data + + updated = update_file_in_place_as_binary(realpath(path), _update_prefix) + + if updated and mode == FileMode.binary and subdir == "osx-arm64" and on_mac: + # Apple arm64 needs signed executables + subprocess.run( + ["/usr/bin/codesign", "-s", "-", "-f", realpath(path)], capture_output=True + ) + + +def replace_prefix( + mode: FileMode, + data: bytes, + placeholder: str, + new_prefix: str, + subdir: str = "noarch", +) -> bytes: + """ + Replaces `placeholder` text with the `new_prefix` provided. The `mode` provided can + either be text or binary. + + We use the `POPULAR_ENCODINGS` module level constant defined above to make several + passes at replacing the placeholder. We do this to account for as many encodings as + possible. If this causes any performance problems in the future, it could potentially + be removed (i.e. just using the most popular "utf-8" encoding"). + + More information/discussion available here: https://github.com/conda/conda/pull/9946 + + :param mode: The mode of operation. + :param original_data: The original data to be updated. + :param placeholder: The placeholder to be replaced. + :param new_prefix: The new prefix to be used. + :param subdir: The subdirectory to be used. + :return: The updated data after prefix replacement. + """ + for encoding in POPULAR_ENCODINGS: + if mode == FileMode.text: + if not _subdir_is_win(subdir): + # if new_prefix contains spaces, it might break the shebang! + # handle this by escaping the spaces early, which will trigger a + # /usr/bin/env replacement later on + newline_pos = data.find(b"\n") + if newline_pos > -1: + shebang_line, rest_of_data = data[:newline_pos], data[newline_pos:] + shebang_placeholder = f"#!{placeholder}".encode(encoding) + if shebang_placeholder in shebang_line: + escaped_shebang = f"#!{new_prefix}".replace(" ", "\\ ").encode( + encoding + ) + shebang_line = shebang_line.replace( + shebang_placeholder, escaped_shebang + ) + data = shebang_line + rest_of_data + # the rest of the file can be replaced normally + data = data.replace( + placeholder.encode(encoding), new_prefix.encode(encoding) + ) + elif mode == FileMode.binary: + data = binary_replace( + data, + placeholder.encode(encoding), + new_prefix.encode(encoding), + encoding=encoding, + subdir=subdir, + ) + else: + raise CondaIOError(f"Invalid mode: {mode!r}") + return data + + +def binary_replace( + data: bytes, + search: bytes, + replacement: bytes, + encoding: str = "utf-8", + subdir: str = "noarch", +) -> bytes: + """ + Replaces occurrences of a search string with a replacement string in a given byte string. + + :param data: The byte string in which to perform the replacements. + :param search: The string to search for in the byte string. + :param replacement: The string to replace occurrences of the search string with. + :param encoding: The encoding to use when encoding and decoding strings. Defaults to "utf-8". + :param subdir: The subdirectory to search for. Defaults to "noarch". + :return: The byte string with the replacements made. + :raises _PaddingError: If the padding calculation results in a negative value. + + This function performs replacements only for pyzzer-type entry points on Windows. + For all other cases, it returns the original byte string unchanged. + """ + zeros = "\0".encode(encoding) + if _subdir_is_win(subdir): + # on Windows for binary files, we currently only replace a pyzzer-type entry point + # we skip all other prefix replacement + if has_pyzzer_entry_point(data): + return replace_pyzzer_entry_point_shebang(data, search, replacement) + else: + return data + + def replace(match: re.Match[bytes]) -> bytes: + """ + Replaces occurrences of the search string with the replacement string in a matched group. + + :param match: The matched group containing the search string. + + :return: The replaced string with padding. + :raises _PaddingError: If the padding calculation results in a negative value. + """ + occurrences = match.group().count(search) + padding = (len(search) - len(replacement)) * occurrences + if padding < 0: + raise _PaddingError + return match.group().replace(search, replacement) + b"\0" * padding + + original_data_len = len(data) + pat = re.compile( + re.escape(search) + b"(?:(?!(?:" + zeros + b")).)*" + zeros, flags=re.DOTALL + ) + data = pat.sub(replace, data) + if len(data) != original_data_len: + raise RuntimeError("Replaced data has different length than original.") + + return data + + +def has_pyzzer_entry_point(data: bytes) -> bool: + """ + Check if the given byte string contains a pyzzer entry point. + + :param data: The byte string to check. + :return: True if the byte string contains a pyzzer entry point, False otherwise. + """ + pos: int = data.rfind(b"PK\x05\x06") + return pos >= 0 + + +def replace_pyzzer_entry_point_shebang( + all_data: bytes, placeholder: bytes, new_prefix: str +) -> bytes: + """ + Code adapted from pyzzer. This is meant to deal with entry point exe's created by distlib, + which consist of a launcher, then a shebang, then a zip archive of the entry point code to run. + We need to change the shebang. + https://bitbucket.org/vinay.sajip/pyzzer/src/5d5740cb04308f067d5844a56fbe91e7a27efccc/pyzzer/__init__.py?at=default&fileviewer=file-view-default#__init__.py-112 # NOQA + + :param all_data: The byte string to search for the entry point. + :param placeholder: The placeholder string to search for in the entry point. + :param new_prefix: The new prefix to replace the placeholder string with. + :return: The updated byte string with the replaced shebang. + """ + # Copyright (c) 2013 Vinay Sajip. + # + # Permission is hereby granted, free of charge, to any person obtaining a copy + # of this software and associated documentation files (the "Software"), to deal + # in the Software without restriction, including without limitation the rights + # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + # copies of the Software, and to permit persons to whom the Software is + # furnished to do so, subject to the following conditions: + # + # The above copyright notice and this permission notice shall be included in + # all copies or substantial portions of the Software. + # + # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + # THE SOFTWARE. + launcher = shebang = None + pos = all_data.rfind(b"PK\x05\x06") + if pos >= 0: + end_cdr = all_data[pos + 12 : pos + 20] + cdr_size, cdr_offset = struct.unpack(" 0: + pos = all_data.rfind(b"#!", 0, arc_pos) + if pos >= 0: + shebang = all_data[pos:arc_pos] + if pos > 0: + launcher = all_data[:pos] + + if data and shebang and launcher: + if hasattr(placeholder, "encode"): + placeholder = placeholder.encode("utf-8") + if hasattr(new_prefix, "encode"): + new_prefix = new_prefix.encode("utf-8") + shebang = shebang.replace(placeholder, new_prefix) + all_data = b"".join([launcher, shebang, data]) + return all_data + + +def replace_long_shebang(mode: FileMode, data: bytes) -> bytes: + """ + Replace long shebang lines in text mode with a shorter one. + + :param mode: The file mode. + :param data: The byte string to search for the entry point. + :return: The updated byte string with the replaced shebang. + """ + # this function only changes a shebang line if it exists and is greater than 127 characters + if mode == FileMode.text: + if not isinstance(data, bytes): + try: + data = bytes(data, encoding="utf-8") + except: + data = data.encode("utf-8") + + shebang_match = re.match(SHEBANG_REGEX, data, re.MULTILINE) + if shebang_match: + whole_shebang, executable, options = shebang_match.groups() + prefix, executable_name = executable.decode("utf-8").rsplit("/", 1) + if len(whole_shebang) > MAX_SHEBANG_LENGTH or "\\ " in prefix: + new_shebang = ( + f"#!/usr/bin/env {executable_name}{options.decode('utf-8')}" + ) + data = data.replace(whole_shebang, new_shebang.encode("utf-8")) + + else: + # TODO: binary shebangs exist; figure this out in the future if text works well + pass + return data + + +def generate_shebang_for_entry_point( + executable: str, with_usr_bin_env: bool = False +) -> str: + """ + This function can be used to generate a shebang line for Python entry points. + + Use cases: + - At install/link time, to generate the `noarch: python` entry points. + - conda init uses it to create its own entry point during conda-build + + :param executable: The path to the Python executable. + :param with_usr_bin_env: Whether to use the `/usr/bin/env` approach. + :return: The generated shebang line. + """ + shebang = f"#!{executable}\n" + if os.environ.get("CONDA_BUILD") == "1" and "/_h_env_placehold" in executable: + # This is being used during a conda-build process, + # which uses long prefixes on purpose. This will be replaced + # with the real environment prefix at install time. Do not + # do nothing for now. + return shebang + + # In principle, the naive shebang will work as long as the path + # to the python executable does not contain spaces AND it's not + # longer than 127 characters. Otherwise, we must fix it + if len(shebang) > MAX_SHEBANG_LENGTH or " " in executable: + if with_usr_bin_env: + # This approach works well for all cases BUT it requires + # the executable to be in PATH. In other words, the environment + # needs to be activated! + shebang = f"#!/usr/bin/env {basename(executable)}\n" + else: + # This approach follows a method inspired by `pypa/distlib` + # https://github.com/pypa/distlib/blob/91aa92e64/distlib/scripts.py#L129 + # Explanation: these lines are both valid Python and shell :) + # 1. Python will read it as a triple-quoted string; end of story + # 2. The shell will see: + # * '' (empty string) + # * 'exec' "path/with spaces/to/python" "this file" "arguments" + # * # ''' (inline comment with three quotes, ignored by shell) + # This method works well BUT in some shells, $PS1 is dropped, which + # makes the prompt disappear. This is very problematic for the conda + # entry point! Details: https://github.com/conda/conda/issues/11885 + shebang = dals( + f""" + #!/bin/sh + '''exec' "{executable}" "$0" "$@" #''' + """ + ) + + return shebang diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/prefix_data.py b/miniconda3/lib/python3.13/site-packages/conda/core/prefix_data.py new file mode 100644 index 0000000000000000000000000000000000000000..82646dbe924dc3e6c733bef8ea32ed7815d8252d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/prefix_data.py @@ -0,0 +1,879 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools for managing the packages installed within an environment.""" + +from __future__ import annotations + +import os +import re +import warnings +from collections import UserDict +from datetime import datetime, timezone +from logging import getLogger +from os.path import basename, lexists +from pathlib import Path +from stat import S_ISDIR +from typing import TYPE_CHECKING + +from frozendict import frozendict + +from ..base.constants import ( + CONDA_ENV_VARS_UNSET_VAR, + PREFIX_CREATION_TIMESTAMP_FILE, + PREFIX_FROZEN_FILE, + PREFIX_MAGIC_FILE, + PREFIX_NAME_DISALLOWED_CHARS, + PREFIX_PINNED_FILE, + PREFIX_STATE_FILE, + RESERVED_ENV_NAMES, + RESERVED_ENV_VARS, + ROOT_ENV_NAME, +) +from ..base.context import context, locate_prefix_by_name +from ..common.compat import on_mac, on_win +from ..common.constants import NULL +from ..common.io import time_recorder +from ..common.path import expand, paths_equal, strip_pkg_extension +from ..common.serialize import json +from ..common.url import mask_anaconda_token +from ..common.url import remove_auth as url_remove_auth +from ..deprecations import deprecated +from ..exceptions import ( + BasicClobberError, + CondaDependencyError, + CondaError, + CondaValueError, + CorruptedEnvironmentError, + DirectoryNotACondaEnvironmentError, + EnvironmentIsFrozenError, + EnvironmentLocationNotFound, + EnvironmentNameNotFound, + EnvironmentNotWritableError, + maybe_raise, +) +from ..gateways.disk.create import first_writable_envs_dir, write_as_json_to_file +from ..gateways.disk.delete import rm_rf +from ..gateways.disk.test import file_path_is_writable +from ..models.enums import PackageType +from ..models.match_spec import MatchSpec +from ..models.prefix_graph import PrefixGraph +from ..models.records import PackageRecord, PrefixRecord + +if TYPE_CHECKING: + from collections.abc import Iterable + from typing import Any, Self, TypeVar + + from ..auxlib import _Null + from ..common.path import PathType + + T = TypeVar("T") + +log = getLogger(__name__) + + +class PrefixDataType(type): + """Basic caching of PrefixData instance objects.""" + + @deprecated.argument( + "25.9", "26.3", "pip_interop_enabled", rename="interoperability" + ) + def __call__( + cls, + prefix_path: PathType, + interoperability: bool | None = None, + ) -> PrefixData: + if isinstance(prefix_path, PrefixData): + return prefix_path + prefix_path = Path(prefix_path) + interoperability = ( + interoperability + if interoperability is not None + else context.prefix_data_interoperability + ) + cache_key = prefix_path, interoperability + if cache_key in PrefixData._cache_: + return PrefixData._cache_[cache_key] + else: + prefix_data_instance = super().__call__(prefix_path, interoperability) + PrefixData._cache_[cache_key] = prefix_data_instance + return prefix_data_instance + + +class PrefixRecordDict(UserDict): + """Lazily convert dict entries to PrefixRecord.""" + + def __getitem__(self, package_name: str) -> PrefixRecord: + record = self.data[package_name] + if not isinstance(record, PrefixRecord): + self.data[package_name] = record = PrefixRecord(**record) + return record + + +class PrefixData(metaclass=PrefixDataType): + """ + The PrefixData class aims to be the representation of the state + of a conda environment on disk. The directory where the environment + lives is called prefix. + + This class supports different types of tasks: + + - Reading and querying `conda-meta/*.json` files as `PrefixRecord` objects + - Reading and writing environment-specific configuration (env vars, state file, + nonadmin markers, etc) + - Existence checks and validations of name, path, and magic files / markers + - Exposing non-conda packages installed in prefix as `PrefixRecord`, via the plugin system + """ + + _cache_: dict[tuple[Path, bool | None], PrefixData] = {} + + @deprecated.argument( + "25.9", "26.3", "pip_interop_enabled", rename="interoperability" + ) + def __init__( + self, + prefix_path: PathType, + interoperability: bool | None = None, + ): + # pip_interop_enabled is a temporary parameter; DO NOT USE + # TODO: when removing pip_interop_enabled, also remove from meta class + self.prefix_path: Path = Path(prefix_path) + self._magic_file: Path = self.prefix_path / PREFIX_MAGIC_FILE + self._frozen_file: Path = self.prefix_path / PREFIX_FROZEN_FILE + self.__prefix_records: dict[str, PrefixRecord] | None = None + self.__is_writable: bool | None | _Null = NULL + self.interoperability: bool = ( + interoperability + if interoperability is not None + else context.prefix_data_interoperability + ) + + @classmethod + def from_name(cls, name: str, **kwargs) -> PrefixData: + """ + Creates a PrefixData instance from an environment name. + + The name will be validated with `PrefixData.validate_name()` if it does not exist. + + :param name: The name of the environment. Must not contain path separators (/, \\). + :raises CondaValueError: If `name` contains a path separator. + """ + if "/" in name or "\\" in name: + raise CondaValueError("Environment names cannot contain path separators") + try: + return cls(locate_prefix_by_name(name)) + except EnvironmentNameNotFound: + cls(name).validate_name() + return cls(Path(first_writable_envs_dir(), name), **kwargs) + + @classmethod + def from_context(cls, validate: bool = False, **kwargs) -> PrefixData: + """ + Creates a PrefixData instance from the path specified by `context.target_prefix`. + + The path and name will be validated with `PrefixData.validate_path()` and + `PrefixData.validate_name()`, respectively, if `validate` is `True`. + + :param validate: Whether the path and name should be validated. Useful for environments + about to be created. + :param kwargs: Additional keyword arguments to pass to the constructor. + """ + inst = cls(context.target_prefix, **kwargs) + if validate: + inst.validate_path() + inst.validate_name() + return inst + + @property + def name(self) -> str: + """ + Returns the name of the environment, if available. + + If the environment doesn't live in one the configured `envs_dirs`, an empty + string is returned. The construct `prefix_data.name or prefix_data.prefix_path` can + be helpful in those cases. + """ + if self == PrefixData(context.root_prefix): + return ROOT_ENV_NAME + for envs_dir in context.envs_dirs: + if paths_equal(envs_dir, self.prefix_path.parent): + return self.prefix_path.name + return "" + + # region Checks + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, PrefixData): + return False + if self.prefix_path.exists(): + if other.prefix_path.exists(): + return self.prefix_path.samefile(other.prefix_path) + return False # only one prefix exists, cannot be the same + elif other.prefix_path.exists(): + return False # only one prefix exists, cannot be the same + else: + # neither prefix exists, raw comparison + return self.prefix_path.resolve() == other.prefix_path.resolve() + + def exists(self) -> bool: + """ + Check whether the PrefixData path exists and is a directory. + """ + try: + return self.prefix_path.is_dir() + except OSError: + return False + + def is_environment(self) -> bool: + """ + Check whether the PrefixData path is a valid conda environment. + + This is assessed by checking if `conda-meta/history` marker file exists. + """ + try: + return self._magic_file.is_file() + except OSError: + return False + + def is_frozen(self) -> bool: + """ + Check whether the environment is marked as frozen, as per CEP 22. + + This is assessed by checking if `conda-meta/frozen` marker file exists. + """ + try: + return self._frozen_file.is_file() + except OSError: + return False + + def is_base(self) -> bool: + """ + Check whether the configured path refers to the `base` environment. + """ + return paths_equal(str(self.prefix_path), context.root_prefix) + + @property + def is_writable(self) -> bool | None | _Null: + """ + Check whether the configured path is writable. This is assessed by checking + whether `conda-meta/history` is writable. It if is, it is assumed that the rest + of the directory tree is writable too. + + Note: The value is cached in the instance. Use `.assert_writable()` for a non- + cached check. + """ + if self.__is_writable == NULL: + if not self.is_environment(): + is_writable = None + else: + is_writable = file_path_is_writable(self._magic_file) + self.__is_writable = is_writable + return self.__is_writable + + def assert_exists(self) -> None: + """ + Check whether the environment path exists. + + :raises EnvironmentLocationNotFound: If the check returns False. + """ + if not self.exists(): + raise EnvironmentLocationNotFound(self.prefix_path) + + def assert_environment(self) -> None: + """ + Check whether the environment path exists and is a valid conda environment. + + :raises DirectoryNotACondaEnvironmentError: If the check returns False. + """ + self.assert_exists() + if not self.is_environment(): + raise DirectoryNotACondaEnvironmentError(self.prefix_path) + + def assert_writable(self) -> None: + """ + Check whether the environment path is a valid conda environment and is writable. + + :raises EnvironmentNotWritableError: If the check returns False. + """ + self.assert_environment() + if not file_path_is_writable(self._magic_file): + raise EnvironmentNotWritableError(self.prefix_path) + + def assert_not_frozen(self) -> None: + """ + Check whether the environment path is a valid conda environment and is not marked + as frozen (as per CEP 22). + + :raises EnvironmentIsFrozenError: If the environment is marked as frozen. + """ + self.assert_environment() + if not self.is_frozen(): + return + message = "" + contents = self._frozen_file.read_text() + if contents: + message = json.loads(contents).get("message", "") + raise EnvironmentIsFrozenError(self.prefix_path, message) + + def validate_path(self, expand_path: bool = False) -> None: + """ + Validate the path of the environment. + + It runs the following checks: + + - Make sure the path does not contain `:` or `;` (OS-dependent). + - Disallow immediately nested environments (e.g. `$CONDA_ROOT` and `$CONDA_ROOT/my-env`). + - Warn if there are spaces in the path. + + :param expand_path: Whether to process `~` and environment variables in the string. + The expanded value will replace `.prefix_path`. + :raises CondaValueError: If the environment contains `:`, `;`, or is nested. + """ + prefix_str = str(self.prefix_path) + if expand_path: + prefix_str = expand(prefix_str) + self.prefix_path = Path(prefix_str) + + if os.pathsep in prefix_str: + raise CondaValueError( + f"Environment paths cannot contain '{os.pathsep}'. Prefix: '{prefix_str}'" + ) + + if " " in prefix_str: + log.warning( + "Environment paths should not contain spaces. Prefix: '%s'", + prefix_str, + ) + parent = self.__class__(self.prefix_path.parent) + if parent.is_environment(): + raise CondaValueError( + "Environment paths cannot be immediately nested under another conda environment." + ) + + def validate_name(self, allow_base: bool = False) -> None: + """ + Validate the name of the environment. + + :param allow_base: Whether to allow `base` as a valid name. + :raises CondaValueError: If the name is protected, or if it contains disallowed characters + (`/`, ` `, `:`, `#`). + """ + if not allow_base and self.name in RESERVED_ENV_NAMES: + raise CondaValueError(f"'{self.name}' is a reserved environment name") + + if PREFIX_NAME_DISALLOWED_CHARS.intersection(self.prefix_path.name): + raise CondaValueError( + "Environment names cannot contain any of these characters: " + f"{PREFIX_NAME_DISALLOWED_CHARS}" + ) + + # endregion + # region Metadata + + @property + def created(self) -> datetime | None: + """ + Returns the time when the environment was created, as evidenced by the `conda-meta` + directory creation time (if available). Falls back to `conda-meta/created_at`. + + This may return None in the following cases: + + - If the environment doesn't exist. + - If the creation time cannot be determined. This can happen for existing environments + created with conda versions before 25.11 in Linux systems, where the 'birthtime' metadata + is only available in kernels 4.11+, and not implemented in Python as of Python 3.14. + """ + try: + stat = (self.prefix_path / "conda-meta").stat() + if not S_ISDIR(stat.st_mode): + # check if path is a dir without running stat() again + return None + except FileNotFoundError: + return None + else: + # On Windows, ctime represents creation time. On other platforms, ctime gives + # last metadata change; creation time comes from birthtime. + # Birthtime was introduced for Windows in Py312, hence the fallback below. + # See https://docs.python.org/3/library/os.html#os.stat_result.st_ctime + # On Linux, birthtime is only available in kernel 4.11+ via statx and won't be + # available in Python until 3.15. The fallback to ctime would be wrong + # because in this platform ctime is last metadata change (not creation time!). + # See https://discuss.python.org/t/st-birthtime-not-available/104350/2 + if on_mac or on_win: + creation_time = getattr(stat, "st_birthtime", stat.st_ctime) + else: + try: + creation_time = stat.st_birthtime + except AttributeError: + # Fallback to magic file conda-meta/.creation-timestamp + try: + magicfile = self.prefix_path / PREFIX_CREATION_TIMESTAMP_FILE + creation_time = float(magicfile.read_text().strip()) + except (OSError, ValueError, TypeError): + return None + return datetime.fromtimestamp(creation_time, tz=timezone.utc) + + @property + def last_modified(self) -> datetime | None: + """ + Returns the time when the environment was last modified, as evidenced by the + `conda-meta/history` file modification time. If the environment does not exist, returns + None. + """ + try: + stat = self._magic_file.stat() + except FileNotFoundError: + return None + else: + return datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc) + + def size(self) -> int: + """ + Compute the total size of a conda environment prefix. + + This aggregates the installed size of all packages in the environment, + plus the size of files under conda-meta (history, manifests, markers). + + :returns: Total size in bytes. + """ + total_size = 0 + + # 1. sum up the installed size of each package + for record in self.iter_records(): + total_size += record.package_size(self.prefix_path) + + # 2. add up the size of files under conda-meta (history, manifests, markers) + conda_meta_dir = self.prefix_path / "conda-meta" + if self.exists(): + try: + for meta_file in conda_meta_dir.iterdir(): + try: + total_size += meta_file.stat().st_size + except OSError: + pass + except OSError: + pass + + return total_size + + # endregion + # region Records + + @time_recorder(module_name=__name__) + def load(self) -> None: + self.__prefix_records = PrefixRecordDict() + _conda_meta_dir = self.prefix_path / "conda-meta" + if lexists(_conda_meta_dir): + conda_meta_json_paths = ( + p + for p in (entry.path for entry in os.scandir(_conda_meta_dir)) + if p[-5:] == ".json" + ) + for meta_file in conda_meta_json_paths: + self._load_single_record(meta_file) + if self.interoperability: + for loader in context.plugin_manager.get_prefix_data_loaders(): + loader(self.prefix_path, self.__prefix_records) + + def reload(self) -> Self: + self.load() + return self + + @property + @deprecated("25.9", "26.3", addendum="Use PrefixData.interoperability.") + def _pip_interop_enabled(self): + return self.interoperability + + def _get_json_fn(self, prefix_record: PrefixRecord) -> str: + fn = prefix_record.fn + # Check package extensions (dynamic) or .dist-info (pip-installed) + stripped, ext = strip_pkg_extension(fn) + if not ext and fn.endswith(".dist-info"): + stripped = fn[: -len(".dist-info")] + elif not ext: + raise ValueError( + f"Attempted to make prefix record for unknown package type: {fn}" + ) + return stripped + ".json" + + def insert(self, prefix_record: PrefixRecord, remove_auth: bool = True) -> None: + if prefix_record.name in self._prefix_records: + raise CondaError( + f"Prefix record '{prefix_record.name}' already exists. " + f"Try `conda clean --all` to fix." + ) + + prefix_record_json_path = ( + self.prefix_path / "conda-meta" / self._get_json_fn(prefix_record) + ) + if lexists(prefix_record_json_path): + maybe_raise( + BasicClobberError( + source_path=None, + target_path=prefix_record_json_path, + context=context, + ), + context, + ) + rm_rf(prefix_record_json_path) + if remove_auth: + prefix_record_json = prefix_record.dump() + prefix_record_json["url"] = url_remove_auth( + mask_anaconda_token(prefix_record.url) + ) + else: + prefix_record_json = prefix_record + write_as_json_to_file(prefix_record_json_path, prefix_record_json) + + self._prefix_records[prefix_record.name] = prefix_record + + def remove(self, package_name: str) -> None: + prefix_record = self._prefix_records.get(package_name) + if not prefix_record: + raise ValueError(f"Package {package_name} is not in prefix.") + + prefix_record_json_path = ( + self.prefix_path / "conda-meta" / self._get_json_fn(prefix_record) + ) + if self.is_writable: + rm_rf(prefix_record_json_path) + + del self._prefix_records[package_name] + + def get(self, package_name: str, default: T = NULL) -> PackageRecord | T: + try: + return self._prefix_records[package_name] + except KeyError: + if default is not NULL: + return default + else: + raise + + def iter_records(self) -> Iterable[PrefixRecord]: + return iter(self._prefix_records.values()) + + def iter_records_sorted(self) -> Iterable[PrefixRecord]: + prefix_graph = PrefixGraph(self.iter_records()) + return iter(prefix_graph.graph) + + def map_records(self) -> frozendict[str, PrefixRecord]: + """ + Map the records to a frozendict of name -> record. + + :return: A mapping of name -> record. + """ + return frozendict(self._prefix_records) + + def all_subdir_urls(self) -> set[str]: + subdir_urls = set() + for prefix_record in self.iter_records(): + subdir_url = prefix_record.channel.subdir_url + if subdir_url and subdir_url not in subdir_urls: + log.debug("adding subdir url %s for %s", subdir_url, prefix_record) + subdir_urls.add(subdir_url) + return subdir_urls + + def query( + self, package_ref_or_match_spec: PackageRecord | MatchSpec | str + ) -> Iterable[PrefixRecord]: + # returns a generator + param = package_ref_or_match_spec + if isinstance(param, str): + param = MatchSpec(param) + if isinstance(param, MatchSpec): + if ( + param.name + and param.name != "*" + and (record := self.get(param.name, None)) + ): + if param.match(record): + # Yes, we do want to return the same + # type for all queries + return (r for r in (record,)) + return (_ for _ in ()) # empty generator + return ( + prefix_rec + for prefix_rec in self.iter_records() + if param.match(prefix_rec) + ) + elif not isinstance(param, PackageRecord): + raise TypeError("`package_ref_or_match_spec` is not a valid record.") + return (prefix_rec for prefix_rec in self.iter_records() if prefix_rec == param) + + def get_conda_packages(self) -> list[PrefixRecord]: + """Get conda packages sorted alphabetically by name. + + :return: Sorted conda package records + """ + conda_types = {None, PackageType.NOARCH_GENERIC, PackageType.NOARCH_PYTHON} + conda_packages = [ + record + for record in self.iter_records() + if record.package_type in conda_types + ] + return sorted(conda_packages, key=lambda x: x.name) + + def get_python_packages(self) -> list[PrefixRecord]: + """Get Python packages (installed via pip) sorted alphabetically by name. + + :return: Sorted Python package records + """ + python_types = { + PackageType.VIRTUAL_PYTHON_WHEEL, + PackageType.VIRTUAL_PYTHON_EGG_MANAGEABLE, + PackageType.VIRTUAL_PYTHON_EGG_UNMANAGEABLE, + } + python_packages = [ + record + for record in self.iter_records() + if record.package_type in python_types + ] + return sorted(python_packages, key=lambda x: x.name) + + @property + def _prefix_records(self) -> dict[str, PrefixRecord] | None: + return self.__prefix_records or self.load() or self.__prefix_records + + def _load_single_record(self, prefix_record_json_path: PathType) -> None: + with open(prefix_record_json_path) as fh: + try: + data = json.load(fh) + except (UnicodeDecodeError, json.JSONDecodeError): + # UnicodeDecodeError: catch horribly corrupt files + # json.JSONDecodeError: catch bad json format files + raise CorruptedEnvironmentError( + self.prefix_path, prefix_record_json_path + ) + + # check that prefix record json filename conforms to name-version-build + # apparently implemented as part of #2638 to resolve #2599 + name, version, build = basename(prefix_record_json_path)[:-5].rsplit("-", 2) + if (name, version, build) != (data["name"], data["version"], data["build"]): + log.warning( + "Ignoring malformed prefix record at: %s", prefix_record_json_path + ) + # TODO: consider just deleting here this record file in the future + return + # TODO: consider, at least in memory, storing prefix_record_json_path as part + # of PrefixRecord + self.__prefix_records[name] = data + + # endregion + # region Python records + + @property + @deprecated("25.9", "26.3", addendum="Use PrefixData.get('python').") + def _python_pkg_record(self) -> PrefixRecord | None: + """Return the prefix record for the package python.""" + return next( + ( + prefix_record + for prefix_record in self.__prefix_records.values() + if prefix_record.name == "python" + ), + None, + ) + + @deprecated( + "25.9", + "26.3", + addendum="Use 'conda.plugins.prefix_data_loaders.pypi.load_site_packages' instead.", + ) + def _load_site_packages(self) -> dict[str, PrefixRecord]: + from ..plugins.prefix_data_loaders.pypi import load_site_packages + + return load_site_packages(self.prefix_path, self.__prefix_records) + + # endregion + # region State and environment variables + + def _get_environment_state_file(self) -> dict[str, dict[str, str]]: + env_vars_file = self.prefix_path / PREFIX_STATE_FILE + if lexists(env_vars_file): + with open(env_vars_file) as f: + prefix_state = json.loads(f.read()) + else: + prefix_state = {} + return prefix_state + + def _write_environment_state_file(self, state: dict[str, dict[str, str]]) -> None: + env_vars_file = self.prefix_path / PREFIX_STATE_FILE + env_vars_file.write_text(json.dumps(state, ensure_ascii=False)) + + def _ensure_no_reserved_env_vars(self, env_vars_names: Iterable[str]) -> None: + """ + Ensure that the set of env_var_names does not contain any reserved env vars. + Will raise an OperationNotAllowed if a reserved env var is found. + """ + invalid_vars = [var for var in RESERVED_ENV_VARS if var in env_vars_names] + if invalid_vars: + print_reserved_vars = ", ".join(invalid_vars) + warnings.warn( + f"WARNING: the given environment variable(s) are reserved and " + f"will be ignored: {print_reserved_vars}. " + "Setting these environment variables may produce unexpected results.\n\n" + f"Remove the invalid configuration with `conda env config vars unset " + f"-p {self.prefix_path} {' '.join(invalid_vars)}`.", + ) + + def get_environment_env_vars(self) -> dict[str, str] | dict[bytes, bytes]: + prefix_state = self._get_environment_state_file() + env_vars_all = dict(prefix_state.get("env_vars", {})) + env_vars = { + k: v for k, v in env_vars_all.items() if v != CONDA_ENV_VARS_UNSET_VAR + } + return env_vars + + def set_environment_env_vars( + self, env_vars: dict[str, str] + ) -> dict[str, str] | None: + self._ensure_no_reserved_env_vars(env_vars.keys()) + env_state_file = self._get_environment_state_file() + current_env_vars = env_state_file.get("env_vars") + if current_env_vars: + current_env_vars.update(env_vars) + else: + env_state_file["env_vars"] = env_vars + self._write_environment_state_file(env_state_file) + return env_state_file.get("env_vars") + + def unset_environment_env_vars(self, env_vars: list[str]) -> dict[str, str] | None: + env_state_file = self._get_environment_state_file() + current_env_vars = env_state_file.get("env_vars") + if current_env_vars: + for env_var in env_vars: + if env_var in current_env_vars.keys(): + if env_var in RESERVED_ENV_VARS: + current_env_vars.pop(env_var) + else: + current_env_vars[env_var] = CONDA_ENV_VARS_UNSET_VAR + self._write_environment_state_file(env_state_file) + return env_state_file.get("env_vars") + + def set_creation_time(self) -> None: + """ + Writes a .creation-time file in conda-meta with the current timestamp, meant + to be used by .created property as a fallback. + """ + timestamp = ( + self.created or self.last_modified or datetime.now(timezone.utc).timestamp() + ) + timestamp_file = self.prefix_path / PREFIX_CREATION_TIMESTAMP_FILE + timestamp_file.parent.mkdir(parents=True, exist_ok=True) + timestamp_file.write_text(str(timestamp)) + + def set_nonadmin(self) -> None: + """Creates $PREFIX/.nonadmin if sys.prefix/.nonadmin exists (on Windows).""" + if on_win and Path(context.root_prefix, ".nonadmin").is_file(): + self.prefix_path.mkdir(parents=True, exist_ok=True) + (self.prefix_path / ".nonadmin").touch() + + def get_pinned_specs(self) -> tuple[MatchSpec]: + """Find pinned specs from file and return a tuple of MatchSpec.""" + pin_file = self.prefix_path / PREFIX_PINNED_FILE + if pin_file.exists(): + with pin_file.open() as f: + from_file = ( + i + for i in f.read().strip().splitlines() + if i and not i.strip().startswith("#") + ) + else: + from_file = () + + return tuple(MatchSpec(spec, optional=True) for spec in from_file) + + # endregion + + +def get_conda_anchor_files_and_records( + site_packages_short_path: PathType, python_records: Iterable[PrefixRecord] +) -> dict[PathType, PrefixRecord]: + """Return the anchor files for the conda records of python packages.""" + anchor_file_endings = (".egg-info/PKG-INFO", ".dist-info/RECORD", ".egg-info") + conda_python_packages = {} + + matcher = re.compile( + r"^{}/[^/]+(?:{})$".format( + re.escape(site_packages_short_path), + r"|".join(re.escape(fn) for fn in anchor_file_endings), + ) + ).match + + # We could fix this earlier in the PrefixRecord instantiation, but then + # we would pay for this conversion every time we load any record. + # However we only need this fix for conda list, which is the only one + # that uses PrefixData with pip_interop_enabled=True. This function is + # only called in that code path. + # See https://github.com/conda/conda/pull/14523 for more context. + for prefix_record in python_records: + anchor_paths = [] + for fpath in prefix_record.files: + if on_win: + fpath = fpath.replace("\\", "/") + if matcher(fpath): + anchor_paths.append(fpath) + if len(anchor_paths) > 1: + anchor_path = sorted(anchor_paths, key=len)[0] + log.info( + "Package %s has multiple python anchor files.\n Using %s", + prefix_record.record_id(), + anchor_path, + ) + conda_python_packages[anchor_path] = prefix_record + elif anchor_paths: + conda_python_packages[anchor_paths[0]] = prefix_record + + return conda_python_packages + + +@deprecated("25.9", "26.3", addendum="Use `PrefixData.get('python', None)` instead.") +def python_record_for_prefix(prefix: os.PathLike) -> PrefixRecord | None: + """ + For the given conda prefix, return the PrefixRecord of the Python installed + in that prefix. + """ + python_record_iterator = ( + record + for record in PrefixData(prefix).iter_records() + if record.name == "python" + ) + record = next(python_record_iterator, None) + if record is not None: + next_record = next(python_record_iterator, None) + if next_record is not None: + raise CondaDependencyError( + f"multiple python records found in prefix {prefix}" + ) + return record + + +@deprecated("25.9", "26.3", addendum="Use `PrefixData.get('python').version` instead.") +def get_python_version_for_prefix(prefix: os.PathLike) -> str | None: + """ + For the given conda prefix, return the version of the Python installation + in that prefix. + """ + # returns a string e.g. "2.7", "3.4", "3.5" or None + record = PrefixData(prefix).get("python", None) + if record is not None: + if record.version[3].isdigit(): + return record.version[:4] + else: + return record.version[:3] + return None + + +def delete_prefix_from_linked_data(path: str | os.PathLike | Path) -> bool: + """Here, path may be a complete prefix or a dist inside a prefix""" + path = Path(path) + for prefix, interoperability in sorted( + PrefixData._cache_, reverse=True, key=lambda key: key[0] + ): + try: + path.relative_to(prefix) + del PrefixData._cache_[(prefix, interoperability)] + return True + except ValueError: + # ValueError: path is not relative to prefix + continue + return False diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/solve.py b/miniconda3/lib/python3.13/site-packages/conda/core/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..416bb56c82478e8cfa2dd6aa330fc383e10bf89b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/solve.py @@ -0,0 +1,1466 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""The classic solver implementation.""" + +from __future__ import annotations + +import copy +import sys +from itertools import chain +from logging import DEBUG, getLogger +from textwrap import dedent +from typing import TYPE_CHECKING + +from boltons.setutils import IndexedSet + +from .. import CondaError +from .. import __version__ as CONDA_VERSION +from ..auxlib.decorators import memoizedproperty +from ..auxlib.ish import dals +from ..base.constants import REPODATA_FN, UNKNOWN_CHANNEL, DepsModifier, UpdateModifier +from ..base.context import context +from ..common.constants import NULL, TRACE +from ..common.io import dashlist, time_recorder +from ..common.iterators import groupby_to_dict as groupby +from ..common.path import get_major_minor_version, paths_equal +from ..exceptions import ( + NoChannelsConfiguredError, + PackagesNotFoundError, + SpecsConfigurationConflictError, + UnsatisfiableError, +) +from ..history import History +from ..models.channel import Channel +from ..models.enums import NoarchType +from ..models.match_spec import MatchSpec +from ..models.prefix_graph import PrefixGraph +from ..models.version import VersionOrder +from ..reporters import get_spinner +from ..resolve import Resolve +from .index import Index, ReducedIndex +from .link import PrefixSetup, UnlinkLinkTransaction +from .prefix_data import PrefixData +from .subdir_data import SubdirData + +try: + from frozendict import frozendict +except ImportError: + from ..auxlib.collection import frozendict + +if TYPE_CHECKING: + from collections.abc import Iterable + + from ..models.records import PackageRecord + +log = getLogger(__name__) + + +class Solver: + """ + A high-level API to conda's solving logic. Three public methods are provided to access a + solution in various forms. + + * :meth:`solve_final_state` + * :meth:`solve_for_diff` + * :meth:`solve_for_transaction` + """ + + _index: ReducedIndex | None + _r: Resolve | None + + def __init__( + self, + prefix: str, + channels: Iterable[Channel] | None = None, + subdirs: Iterable[str] = (), + specs_to_add: Iterable[MatchSpec] = (), + specs_to_remove: Iterable[MatchSpec] = (), + repodata_fn: str = REPODATA_FN, + command=NULL, + ): + """ + Args: + prefix (str): + The conda prefix / environment location for which the :class:`Solver` + is being instantiated. + channels (Sequence[:class:`Channel`]): + A prioritized list of channels to use for the solution. + subdirs (Sequence[str]): + A prioritized list of subdirs to use for the solution. + specs_to_add (set[:class:`MatchSpec`]): + The set of package specs to add to the prefix. + specs_to_remove (set[:class:`MatchSpec`]): + The set of package specs to remove from the prefix. + + """ + self.prefix = prefix + self._channels = channels or context.channels + self.channels = IndexedSet(Channel(c) for c in self._channels) + self.subdirs = tuple(s for s in subdirs or context.subdirs) + self.specs_to_add = frozenset(MatchSpec.merge(s for s in specs_to_add)) + self.specs_to_add_names = frozenset(_.name for _ in self.specs_to_add) + self.specs_to_remove = frozenset(MatchSpec.merge(s for s in specs_to_remove)) + self.neutered_specs = () + self._command = command + + if unknown_subdirs := set(self.subdirs) - context.known_subdirs: + raise ValueError(f"Unknown subdir(s):{dashlist(sorted(unknown_subdirs))}") + self._repodata_fn = repodata_fn + self._index = None + self._r = None + self._prepared = False + self._pool_cache = {} + + def solve_for_transaction( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=NULL, + should_retry_solve=False, + ): + """Gives an UnlinkLinkTransaction instance that can be used to execute the solution + on an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + See :meth:`solve_for_diff`. + should_retry_solve (bool): + See :meth:`solve_final_state`. + + Returns: + UnlinkLinkTransaction: + + """ + if self.specs_to_add and (not self.channels or len(self.channels) == 0): + raise NoChannelsConfiguredError( + packages=[spec.name for spec in self.specs_to_add if spec.name], + ) + + if self.prefix == context.root_prefix and context.enable_private_envs: + # This path has the ability to generate a multi-prefix transaction. The basic logic + # is in the commented out get_install_transaction() function below. Exercised at + # the integration level in the PrivateEnvIntegrationTests in test_create.py. + raise NotImplementedError() + + # run pre-solve processes here before solving for a solution + context.plugin_manager.invoke_pre_solves( + self.specs_to_add, + self.specs_to_remove, + ) + + unlink_precs, link_precs = self.solve_for_diff( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + force_reinstall, + should_retry_solve, + ) + # TODO: Only explicitly requested remove and update specs are being included in + # History right now. Do we need to include other categories from the solve? + + # run post-solve processes here before performing the transaction + context.plugin_manager.invoke_post_solves( + self._repodata_fn, + unlink_precs, + link_precs, + ) + + self._notify_conda_outdated(link_precs) + return UnlinkLinkTransaction( + PrefixSetup( + self.prefix, + unlink_precs, + link_precs, + self.specs_to_remove, + self.specs_to_add, + self.neutered_specs, + ) + ) + + def solve_for_diff( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + force_reinstall=NULL, + should_retry_solve=False, + ) -> tuple[tuple[PackageRecord, ...], tuple[PackageRecord, ...]]: + """Gives the package references to remove from an environment, followed by + the package references to add to an environment. + + Args: + deps_modifier (DepsModifier): + See :meth:`solve_final_state`. + prune (bool): + See :meth:`solve_final_state`. + ignore_pinned (bool): + See :meth:`solve_final_state`. + force_remove (bool): + See :meth:`solve_final_state`. + force_reinstall (bool): + For requested specs_to_add that are already satisfied in the environment, + instructs the solver to remove the package and spec from the environment, + and then add it back--possibly with the exact package instance modified, + depending on the spec exactness. + should_retry_solve (bool): + See :meth:`solve_final_state`. + + Returns: + tuple[PackageRef], tuple[PackageRef]: + A two-tuple of PackageRef sequences. The first is the group of packages to + remove from the environment, in sorted dependency order from leaves to roots. + The second is the group of packages to add to the environment, in sorted + dependency order from roots to leaves. + + """ + final_precs = self.solve_final_state( + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + should_retry_solve, + ) + unlink_precs, link_precs = diff_for_unlink_link_precs( + self.prefix, final_precs, self.specs_to_add, force_reinstall + ) + + # assert that all unlink_precs are manageable + unmanageable = groupby(lambda prec: prec.is_unmanageable, unlink_precs).get( + True + ) + if unmanageable: + raise RuntimeError( + f"Cannot unlink unmanageable packages:{dashlist(prec.record_id() for prec in unmanageable)}" + ) + + return unlink_precs, link_precs + + def solve_final_state( + self, + update_modifier=NULL, + deps_modifier=NULL, + prune=NULL, + ignore_pinned=NULL, + force_remove=NULL, + should_retry_solve=False, + ): + """Gives the final, solved state of the environment. + + Args: + update_modifier (UpdateModifier): + An optional flag directing how updates are handled regarding packages already + existing in the environment. + + deps_modifier (DepsModifier): + An optional flag indicating special solver handling for dependencies. The + default solver behavior is to be as conservative as possible with dependency + updates (in the case the dependency already exists in the environment), while + still ensuring all dependencies are satisfied. Options include + * NO_DEPS + * ONLY_DEPS + * UPDATE_DEPS + * UPDATE_DEPS_ONLY_DEPS + * FREEZE_INSTALLED + prune (bool): + If ``True``, the solution will not contain packages that were + previously brought into the environment as dependencies but are no longer + required as dependencies and are not user-requested. + ignore_pinned (bool): + If ``True``, the solution will ignore pinned package configuration + for the prefix. + force_remove (bool): + Forces removal of a package without removing packages that depend on it. + should_retry_solve (bool): + Indicates whether this solve will be retried. This allows us to control + whether to call find_conflicts (slow) in ssc.r.solve + + Returns: + tuple[PackageRef]: + In sorted dependency order from roots to leaves, the package references for + the solved state of the environment. + + """ + + if self.specs_to_add and (not self.channels or len(self.channels) == 0): + raise NoChannelsConfiguredError( + packages=[spec.name for spec in self.specs_to_add if spec.name], + ) + + if prune and update_modifier == UpdateModifier.FREEZE_INSTALLED: + update_modifier = NULL + if update_modifier is NULL: + update_modifier = context.update_modifier + else: + update_modifier = UpdateModifier(str(update_modifier).lower()) + if deps_modifier is NULL: + deps_modifier = context.deps_modifier + else: + deps_modifier = DepsModifier(str(deps_modifier).lower()) + ignore_pinned = ( + context.ignore_pinned if ignore_pinned is NULL else ignore_pinned + ) + force_remove = context.force_remove if force_remove is NULL else force_remove + + log.debug( + "solving prefix %s\n specs_to_remove: %s\n specs_to_add: %s\n prune: %s", + self.prefix, + self.specs_to_remove, + self.specs_to_add, + prune, + ) + + retrying = hasattr(self, "ssc") + + if not retrying: + ssc = SolverStateContainer( + self.prefix, + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + should_retry_solve, + ) + self.ssc = ssc + else: + ssc = self.ssc + ssc.update_modifier = update_modifier + ssc.deps_modifier = deps_modifier + ssc.should_retry_solve = should_retry_solve + + # force_remove is a special case where we return early + if self.specs_to_remove and force_remove: + if self.specs_to_add: + raise NotImplementedError() + solution = tuple( + prec + for prec in ssc.solution_precs + if not any(spec.match(prec) for spec in self.specs_to_remove) + ) + return IndexedSet(PrefixGraph(solution).graph) + + # Check if specs are satisfied by current environment. If they are, exit early. + if ( + update_modifier == UpdateModifier.SPECS_SATISFIED_SKIP_SOLVE + and not self.specs_to_remove + and not prune + ): + for spec in self.specs_to_add: + if not next(ssc.prefix_data.query(spec), None): + break + else: + # All specs match a package in the current environment. + # Return early, with a solution that should just be PrefixData().iter_records() + return IndexedSet(PrefixGraph(ssc.solution_precs).graph) + + if not ssc.r: + with get_spinner(f"Collecting package metadata ({self._repodata_fn})"): + ssc = self._collect_all_metadata(ssc) + + if should_retry_solve and update_modifier == UpdateModifier.FREEZE_INSTALLED: + fail_message = ( + "unsuccessful initial attempt using frozen solve. Retrying" + " with flexible solve.\n" + ) + elif self._repodata_fn != REPODATA_FN: + fail_message = ( + f"unsuccessful attempt using repodata from {self._repodata_fn}, retrying" + " with next repodata source.\n" + ) + else: + fail_message = "failed\n" + + with get_spinner("Solving environment", fail_message=fail_message): + ssc = self._remove_specs(ssc) + ssc = self._add_specs(ssc) + solution_precs = copy.copy(ssc.solution_precs) + + pre_packages = self.get_request_package_in_solution( + ssc.solution_precs, ssc.specs_map + ) + ssc = self._find_inconsistent_packages(ssc) + # this will prune precs that are deps of precs that get removed due to conflicts + ssc = self._run_sat(ssc) + post_packages = self.get_request_package_in_solution( + ssc.solution_precs, ssc.specs_map + ) + + if ssc.update_modifier == UpdateModifier.UPDATE_SPECS: + constrained = self.get_constrained_packages( + pre_packages, post_packages, ssc.index.keys() + ) + if len(constrained) > 0: + for spec in constrained: + self.determine_constricting_specs(spec, ssc.solution_precs) + + # if there were any conflicts, we need to add their orphaned deps back in + if ssc.add_back_map: + orphan_precs = ( + set(solution_precs) + - set(ssc.solution_precs) + - set(ssc.add_back_map) + ) + solution_prec_names = [_.name for _ in ssc.solution_precs] + ssc.solution_precs.extend( + [ + _ + for _ in orphan_precs + if _.name not in ssc.specs_map + and _.name not in solution_prec_names + ] + ) + + ssc = self._post_sat_handling(ssc) + + time_recorder.log_totals() + + ssc.solution_precs = IndexedSet(PrefixGraph(ssc.solution_precs).graph) + log.debug( + "solved prefix %s\n solved_linked_dists:\n %s\n", + self.prefix, + "\n ".join(prec.dist_str() for prec in ssc.solution_precs), + ) + + return ssc.solution_precs + + def determine_constricting_specs(self, spec, solution_precs): + highest_version = [ + VersionOrder(sp.version) for sp in solution_precs if sp.name == spec.name + ][0] + constricting = [] + for prec in solution_precs: + if any(j for j in prec.depends if spec.name in j): + for dep in prec.depends: + m_dep = MatchSpec(dep) + if ( + m_dep.name == spec.name + and m_dep.version is not None + and (m_dep.version.exact_value or "<" in m_dep.version.spec) + ): + if "," in m_dep.version.spec: + constricting.extend( + [ + (prec.name, MatchSpec(f"{m_dep.name} {v}")) + for v in m_dep.version.tup + if "<" in v.spec + ] + ) + else: + constricting.append((prec.name, m_dep)) + + hard_constricting = [ + i for i in constricting if i[1].version.matcher_vo <= highest_version + ] + if len(hard_constricting) == 0: + return None + + print(f"\n\nUpdating {spec.name} is constricted by \n") + for const in hard_constricting: + print(f"{const[0]} -> requires {const[1]}") + print( + "\nIf you are sure you want an update of your package either try " + "`conda update --all` or install a specific version of the " + "package you want using `conda install =`\n" + ) + return hard_constricting + + def get_request_package_in_solution(self, solution_precs, specs_map): + requested_packages = {} + for pkg in self.specs_to_add: + update_pkg_request = pkg.name + + requested_packages[update_pkg_request] = [ + (i.name, str(i.version)) + for i in solution_precs + if i.name == update_pkg_request and i.version is not None + ] + requested_packages[update_pkg_request].extend( + [ + (v.name, str(v.version)) + for k, v in specs_map.items() + if k == update_pkg_request and v.version is not None + ] + ) + + return requested_packages + + def get_constrained_packages(self, pre_packages, post_packages, index_keys): + update_constrained = set() + + def empty_package_list(pkg): + for k, v in pkg.items(): + if len(v) == 0: + return True + return False + + if empty_package_list(pre_packages) or empty_package_list(post_packages): + return update_constrained + + for pkg in self.specs_to_add: + if pkg.name.startswith("__"): # ignore virtual packages + continue + current_version = max(i[1] for i in pre_packages[pkg.name]) + if current_version == max( + i.version for i in index_keys if i.name == pkg.name + ): + continue + else: + if post_packages == pre_packages: + update_constrained = update_constrained | {pkg} + return update_constrained + + @time_recorder(module_name=__name__) + def _collect_all_metadata(self, ssc): + if ssc.prune: + # When pruning DO NOT consider history of already installed packages when solving. + prepared_specs = {*self.specs_to_remove, *self.specs_to_add} + else: + # add in historically-requested specs + ssc.specs_map.update(ssc.specs_from_history_map) + + # these are things that we want to keep even if they're not explicitly specified. This + # is to compensate for older installers not recording these appropriately for them + # to be preserved. + for pkg_name in ( + "anaconda", + "conda", + "conda-build", + "python.app", + "console_shortcut", + "powershell_shortcut", + ): + if pkg_name not in ssc.specs_map and ssc.prefix_data.get( + pkg_name, None + ): + ssc.specs_map[pkg_name] = MatchSpec(pkg_name) + + # Add virtual packages so they are taken into account by the solver + virtual_pkg_index = Index().system_packages + virtual_pkgs = [p.name for p in virtual_pkg_index.keys()] + for virtual_pkgs_name in virtual_pkgs: + if virtual_pkgs_name not in ssc.specs_map: + ssc.specs_map[virtual_pkgs_name] = MatchSpec(virtual_pkgs_name) + + for prec in ssc.prefix_data.iter_records(): + # first check: add everything if we have no history to work with. + # This happens with "update --all", for example. + # + # second check: add in aggressively updated packages + # + # third check: add in foreign stuff (e.g. from pip) into the specs + # map. We add it so that it can be left alone more. This is a + # declaration that it is manually installed, much like the + # history map. It may still be replaced if it is in conflict, + # but it is not just an indirect dep that can be pruned. + if ( + not ssc.specs_from_history_map + or MatchSpec(prec.name) in context.aggressive_update_packages + or prec.subdir == "pypi" + ): + ssc.specs_map.update({prec.name: MatchSpec(prec.name)}) + + prepared_specs = { + *self.specs_to_remove, + *self.specs_to_add, + *ssc.specs_from_history_map.values(), + } + + index, r = self._prepare(prepared_specs) + ssc.set_repository_metadata(index, r) + return ssc + + def _remove_specs(self, ssc): + if self.specs_to_remove: + # In a previous implementation, we invoked SAT here via `r.remove()` to help with + # spec removal, and then later invoking SAT again via `r.solve()`. Rather than invoking + # SAT for spec removal determination, we can use the PrefixGraph and simple tree + # traversal if we're careful about how we handle features. We still invoke sat via + # `r.solve()` later. + _track_fts_specs = ( + spec for spec in self.specs_to_remove if "track_features" in spec + ) + feature_names = set( + chain.from_iterable( + spec.get_raw_value("track_features") for spec in _track_fts_specs + ) + ) + graph = PrefixGraph(ssc.solution_precs, ssc.specs_map.values()) + + all_removed_records = [] + no_removed_records_specs = [] + for spec in self.specs_to_remove: + # If the spec was a track_features spec, then we need to also remove every + # package with a feature that matches the track_feature. The + # `graph.remove_spec()` method handles that for us. + log.log(TRACE, "using PrefixGraph to remove records for %s", spec) + removed_records = graph.remove_spec(spec) + if removed_records: + all_removed_records.extend(removed_records) + else: + no_removed_records_specs.append(spec) + + # ensure that each spec in specs_to_remove is actually associated with removed records + unmatched_specs_to_remove = tuple( + spec + for spec in no_removed_records_specs + if not any(spec.match(rec) for rec in all_removed_records) + ) + if unmatched_specs_to_remove: + raise PackagesNotFoundError( + tuple(sorted(str(s) for s in unmatched_specs_to_remove)) + ) + + for rec in all_removed_records: + # We keep specs (minus the feature part) for the non provides_features packages + # if they're in the history specs. Otherwise, we pop them from the specs_map. + rec_has_a_feature = set(rec.features or ()) & feature_names + if rec_has_a_feature and rec.name in ssc.specs_from_history_map: + spec = ssc.specs_map.get(rec.name, MatchSpec(rec.name)) + spec._match_components = frozendict( + { + key: value + for key, value in spec._match_components.items() + if key != "features" + } + ) + ssc.specs_map[spec.name] = spec + else: + ssc.specs_map.pop(rec.name, None) + + ssc.solution_precs = tuple(graph.graph) + return ssc + + @time_recorder(module_name=__name__) + def _find_inconsistent_packages(self, ssc): + # We handle as best as possible environments in inconsistent states. To do this, + # we remove now from consideration the set of packages causing inconsistencies, + # and then we add them back in following the main SAT call. + _, inconsistent_precs = ssc.r.bad_installed(ssc.solution_precs, ()) + if inconsistent_precs: + # It is possible that the package metadata is incorrect, for example when + # un-patched metadata from the Miniconda or Anaconda installer is present, see: + # https://github.com/conda/conda/issues/8076 + # Update the metadata with information from the index and see if that makes the + # environment consistent. + ssc.solution_precs = tuple(ssc.index.get(k, k) for k in ssc.solution_precs) + _, inconsistent_precs = ssc.r.bad_installed(ssc.solution_precs, ()) + if log.isEnabledFor(DEBUG): + log.debug( + "inconsistent precs: %s", + dashlist(inconsistent_precs) if inconsistent_precs else "None", + ) + if inconsistent_precs: + print( + dedent( + """ + The environment is inconsistent, please check the package plan carefully + The following packages are causing the inconsistency:""" + ), + file=sys.stderr, + ) + print(dashlist(inconsistent_precs), file=sys.stderr) + for prec in inconsistent_precs: + # pop and save matching spec in specs_map + spec = ssc.specs_map.pop(prec.name, None) + ssc.add_back_map[prec.name] = (prec, spec) + # let the package float. This is essential to keep the package's dependencies + # in the solution + ssc.specs_map[prec.name] = MatchSpec(prec.name, target=prec.dist_str()) + # inconsistent environments should maintain the python version + # unless explicitly requested by the user. This along with the logic in + # _add_specs maintains the major.minor version + if prec.name == "python" and spec: + ssc.specs_map["python"] = spec + ssc.solution_precs = tuple( + prec for prec in ssc.solution_precs if prec not in inconsistent_precs + ) + return ssc + + def _package_has_updates(self, ssc, spec, installed_pool): + installed_prec = installed_pool.get(spec.name) + has_update = False + + if installed_prec: + installed_prec = installed_prec[0] + for prec in ssc.r.groups.get(spec.name, []): + if prec.version > installed_prec.version: + has_update = True + break + elif ( + prec.version == installed_prec.version + and prec.build_number > installed_prec.build_number + ): + has_update = True + break + # let conda determine the latest version by just adding a name spec + return ( + MatchSpec(spec.name, version=prec.version, build_number=prec.build_number) + if has_update + else spec + ) + + def _should_freeze( + self, ssc, target_prec, conflict_specs, explicit_pool, installed_pool + ): + # never, ever freeze anything if we have no history. + if not ssc.specs_from_history_map: + return False + # never freeze if not in FREEZE_INSTALLED mode + if ssc.update_modifier != UpdateModifier.FREEZE_INSTALLED: + return False + + # if all package specs have overlapping package choices (satisfiable in at least one way) + pkg_name = target_prec.name + no_conflict = pkg_name not in conflict_specs and ( + pkg_name not in explicit_pool or target_prec in explicit_pool[pkg_name] + ) + + return no_conflict + + def _add_specs(self, ssc): + # For the remaining specs in specs_map, add target to each spec. `target` is a reference + # to the package currently existing in the environment. Setting target instructs the + # solver to not disturb that package if it's not necessary. + # If the spec.name is being modified by inclusion in specs_to_add, we don't set `target`, + # since we *want* the solver to modify/update that package. + # + # TLDR: when working with MatchSpec objects, + # - to minimize the version change, set MatchSpec(name=name, target=prec.dist_str()) + # - to freeze the package, set all the components of MatchSpec individually + + installed_pool = groupby(lambda x: x.name, ssc.prefix_data.iter_records()) + + # the only things we should consider freezing are things that don't conflict with the new + # specs being added. + explicit_pool = ssc.r._get_package_pool(self.specs_to_add) + if ssc.prune: + # Ignore installed specs on prune. + installed_specs = () + else: + installed_specs = [ + record.to_match_spec() for record in ssc.prefix_data.iter_records() + ] + + conflict_specs = ( + ssc.r.get_conflicting_specs(installed_specs, self.specs_to_add) or tuple() + ) + conflict_specs = {spec.name for spec in conflict_specs} + + for pkg_name, spec in ssc.specs_map.items(): + matches_for_spec = tuple( + prec for prec in ssc.solution_precs if spec.match(prec) + ) + if matches_for_spec: + if len(matches_for_spec) != 1: + raise CondaError( + dals( + """ + Conda encountered an error with your environment. Please report an issue + at https://github.com/conda/conda/issues. In your report, please include + the output of 'conda info' and 'conda list' for the active environment, along + with the command you invoked that resulted in this error. + pkg_name: %s + spec: %s + matches_for_spec: %s + """ + ) + % ( + pkg_name, + spec, + dashlist((str(s) for s in matches_for_spec), indent=4), + ) + ) + target_prec = matches_for_spec[0] + if target_prec.is_unmanageable: + ssc.specs_map[pkg_name] = target_prec.to_match_spec() + elif MatchSpec(pkg_name) in context.aggressive_update_packages: + ssc.specs_map[pkg_name] = MatchSpec(pkg_name) + elif self._should_freeze( + ssc, target_prec, conflict_specs, explicit_pool, installed_pool + ): + ssc.specs_map[pkg_name] = target_prec.to_match_spec() + elif pkg_name in ssc.specs_from_history_map: + ssc.specs_map[pkg_name] = MatchSpec( + ssc.specs_from_history_map[pkg_name], + target=target_prec.dist_str(), + ) + else: + ssc.specs_map[pkg_name] = MatchSpec( + pkg_name, target=target_prec.dist_str() + ) + + pin_overrides = set() + for s in ssc.pinned_specs: + if s.name in explicit_pool: + if s.name not in self.specs_to_add_names and not ssc.ignore_pinned: + ssc.specs_map[s.name] = MatchSpec(s, optional=False) + elif explicit_pool[s.name] & ssc.r._get_package_pool([s]).get( + s.name, set() + ): + ssc.specs_map[s.name] = MatchSpec(s, optional=False) + pin_overrides.add(s.name) + else: + log.warning( + "pinned spec %s conflicts with explicit specs. " + "Overriding pinned spec.", + s, + ) + + # we want to freeze any packages in the env that are not conflicts, so that the + # solve goes faster. This is kind of like an iterative solve, except rather + # than just providing a starting place, we are preventing some solutions. + # A true iterative solve would probably be better in terms of reaching the + # optimal output all the time. It would probably also get rid of the need + # to retry with an unfrozen (UPDATE_SPECS) solve. + if ssc.update_modifier == UpdateModifier.FREEZE_INSTALLED: + precs = [ + _ for _ in ssc.prefix_data.iter_records() if _.name not in ssc.specs_map + ] + for prec in precs: + if prec.name not in conflict_specs: + ssc.specs_map[prec.name] = prec.to_match_spec() + else: + ssc.specs_map[prec.name] = MatchSpec( + prec.name, target=prec.to_match_spec(), optional=True + ) + log.debug("specs_map with targets: %s", ssc.specs_map) + + # If we're in UPDATE_ALL mode, we need to drop all the constraints attached to specs, + # so they can all float and the solver can find the most up-to-date solution. In the case + # of UPDATE_ALL, `specs_map` wasn't initialized with packages from the current environment, + # but *only* historically-requested specs. This lets UPDATE_ALL drop dependencies if + # they're no longer needed, and their presence would otherwise prevent the updated solution + # the user most likely wants. + if ssc.update_modifier == UpdateModifier.UPDATE_ALL: + # history is preferable because it has explicitly installed stuff in it. + # that simplifies our solution. + if ssc.specs_from_history_map: + ssc.specs_map = dict( + (spec, MatchSpec(spec)) + if MatchSpec(spec).name not in (_.name for _ in ssc.pinned_specs) + else (MatchSpec(spec).name, ssc.specs_map[MatchSpec(spec).name]) + for spec in ssc.specs_from_history_map + ) + for prec in ssc.prefix_data.iter_records(): + # treat pip-installed stuff as explicitly installed, too. + if prec.subdir == "pypi": + ssc.specs_map.update({prec.name: MatchSpec(prec.name)}) + else: + ssc.specs_map = { + prec.name: ( + MatchSpec(prec.name) + if prec.name not in (_.name for _ in ssc.pinned_specs) + else ssc.specs_map[prec.name] + ) + for prec in ssc.prefix_data.iter_records() + } + + # ensure that our self.specs_to_add are not being held back by packages in the env. + # This factors in pins and also ignores specs from the history. It is unfreezing only + # for the indirect specs that otherwise conflict with update of the immediate request + elif ssc.update_modifier == UpdateModifier.UPDATE_SPECS: + skip = lambda x: ( + ( + x.name not in pin_overrides + and any(x.name == _.name for _ in ssc.pinned_specs) + and not ssc.ignore_pinned + ) + or x.name in ssc.specs_from_history_map + ) + + specs_to_add = tuple( + self._package_has_updates(ssc, _, installed_pool) + for _ in self.specs_to_add + if not skip(_) + ) + # the index is sorted, so the first record here gives us what we want. + conflicts = ssc.r.get_conflicting_specs( + tuple(MatchSpec(_) for _ in ssc.specs_map.values()), specs_to_add + ) + for conflict in conflicts or (): + # neuter the spec due to a conflict + if ( + conflict.name in ssc.specs_map + and ( + # add optional because any pinned specs will include it + MatchSpec(conflict, optional=True) not in ssc.pinned_specs + or ssc.ignore_pinned + ) + and conflict.name not in ssc.specs_from_history_map + ): + ssc.specs_map[conflict.name] = MatchSpec(conflict.name) + + # As a business rule, we never want to update python beyond the current minor version, + # unless that's requested explicitly by the user (which we actively discourage). + py_in_prefix = any(_.name == "python" for _ in ssc.solution_precs) + py_requested_explicitly = any(s.name == "python" for s in self.specs_to_add) + if py_in_prefix and not py_requested_explicitly: + python_prefix_rec = ssc.prefix_data.get("python") + freeze_installed = ssc.update_modifier == UpdateModifier.FREEZE_INSTALLED + if "python" not in conflict_specs and freeze_installed: + ssc.specs_map["python"] = python_prefix_rec.to_match_spec() + else: + # will our prefix record conflict with any explicit spec? If so, don't add + # anything here - let python float when it hasn't been explicitly specified + python_spec = ssc.specs_map.get("python", MatchSpec("python")) + if not python_spec.get("version"): + pinned_version = ( + get_major_minor_version(python_prefix_rec.version) + ".*" + ) + python_spec = MatchSpec(python_spec, version=pinned_version) + + spec_set = (python_spec,) + tuple(self.specs_to_add) + if ssc.r.get_conflicting_specs(spec_set, self.specs_to_add): + if self._command != "install" or ( + self._repodata_fn == REPODATA_FN + and (not ssc.should_retry_solve or not freeze_installed) + ): + # raises a hopefully helpful error message + ssc.r.find_conflicts(spec_set) + else: + raise UnsatisfiableError({}) + ssc.specs_map["python"] = python_spec + + # For the aggressive_update_packages configuration parameter, we strip any target + # that's been set. + if not context.offline: + for spec in context.aggressive_update_packages: + if spec.name in ssc.specs_map: + ssc.specs_map[spec.name] = spec + + # add in explicitly requested specs from specs_to_add + # this overrides any name-matching spec already in the spec map + ssc.specs_map.update( + (s.name, s) for s in self.specs_to_add if s.name not in pin_overrides + ) + + # As a business rule, we never want to downgrade conda below the current version, + # unless that's requested explicitly by the user (which we actively discourage). + if "conda" in ssc.specs_map and paths_equal(self.prefix, context.conda_prefix): + conda_prefix_rec = ssc.prefix_data.get("conda") + if conda_prefix_rec: + version_req = f">={conda_prefix_rec.version}" + conda_requested_explicitly = any( + s.name == "conda" for s in self.specs_to_add + ) + conda_spec = ssc.specs_map["conda"] + conda_in_specs_to_add_version = ssc.specs_map.get("conda", {}).get( + "version" + ) + if not conda_in_specs_to_add_version: + conda_spec = MatchSpec(conda_spec, version=version_req) + if context.auto_update_conda and not conda_requested_explicitly: + conda_spec = MatchSpec("conda", version=version_req, target=None) + ssc.specs_map["conda"] = conda_spec + + return ssc + + @time_recorder(module_name=__name__) + def _run_sat(self, ssc): + final_environment_specs = IndexedSet( + ( + *ssc.specs_map.values(), + *ssc.track_features_specs, + # pinned specs removed here - added to specs_map in _add_specs instead + ) + ) + + absent_specs = [s for s in ssc.specs_map.values() if not ssc.r.find_matches(s)] + if absent_specs: + raise PackagesNotFoundError(absent_specs) + + # We've previously checked `solution` for consistency (which at that point was the + # pre-solve state of the environment). Now we check our compiled set of + # `final_environment_specs` for the possibility of a solution. If there are conflicts, + # we can often avoid them by neutering specs that have a target (e.g. removing version + # constraint) and also making them optional. The result here will be less cases of + # `UnsatisfiableError` handed to users, at the cost of more packages being modified + # or removed from the environment. + # + # get_conflicting_specs() returns a "minimal unsatisfiable subset" which + # may not be the only unsatisfiable subset. We may have to call get_conflicting_specs() + # several times, each time making modifications to loosen constraints. + + conflicting_specs = set( + ssc.r.get_conflicting_specs( + tuple(final_environment_specs), self.specs_to_add + ) + or [] + ) + while conflicting_specs: + specs_modified = False + if log.isEnabledFor(DEBUG): + log.debug( + "conflicting specs: %s", + dashlist(s.target or s for s in conflicting_specs), + ) + + # Are all conflicting specs in specs_map? If not, that means they're in + # track_features_specs or pinned_specs, which we should raise an error on. + specs_map_set = set(ssc.specs_map.values()) + grouped_specs = groupby(lambda s: s in specs_map_set, conflicting_specs) + # force optional to true. This is what it is originally in + # pinned_specs, but we override that in _add_specs to make it + # non-optional when there's a name match in the explicit package + # pool + conflicting_pinned_specs = groupby( + lambda s: MatchSpec(s, optional=True) in ssc.pinned_specs, + conflicting_specs, + ) + + if conflicting_pinned_specs.get(True): + in_specs_map = grouped_specs.get(True, ()) + pinned_conflicts = conflicting_pinned_specs.get(True, ()) + in_specs_map_or_specs_to_add = ( + set(in_specs_map) | set(self.specs_to_add) + ) - set(pinned_conflicts) + + raise SpecsConfigurationConflictError( + sorted(s.__str__() for s in in_specs_map_or_specs_to_add), + sorted(s.__str__() for s in {s for s in pinned_conflicts}), + self.prefix, + ) + for spec in conflicting_specs: + if spec.target and not spec.optional: + specs_modified = True + final_environment_specs.remove(spec) + if spec.get("version"): + neutered_spec = MatchSpec(spec.name, version=spec.version) + else: + neutered_spec = MatchSpec(spec.name) + final_environment_specs.add(neutered_spec) + ssc.specs_map[spec.name] = neutered_spec + if specs_modified: + conflicting_specs = set( + ssc.r.get_conflicting_specs( + tuple(final_environment_specs), self.specs_to_add + ) + ) + else: + # Let r.solve() use r.find_conflicts() to report conflict chains. + break + + # Finally! We get to call SAT. + if log.isEnabledFor(DEBUG): + log.debug( + "final specs to add: %s", + dashlist(sorted(str(s) for s in final_environment_specs)), + ) + + # this will raise for unsatisfiable stuff. We can + if not conflicting_specs or context.unsatisfiable_hints: + ssc.solution_precs = ssc.r.solve( + tuple(final_environment_specs), + specs_to_add=self.specs_to_add, + history_specs=ssc.specs_from_history_map, + should_retry_solve=ssc.should_retry_solve, + ) + else: + # shortcut to raise an unsat error without needing another solve step when + # unsatisfiable_hints is off + raise UnsatisfiableError({}) + + self.neutered_specs = tuple( + v + for k, v in ssc.specs_map.items() + if k in ssc.specs_from_history_map + and v.strictness < ssc.specs_from_history_map[k].strictness + ) + + # add back inconsistent packages to solution + if ssc.add_back_map: + for name, (prec, spec) in ssc.add_back_map.items(): + # spec here will only be set if the conflicting prec was in the original specs_map + # if it isn't there, then we restore the conflict. If it is there, though, + # we keep the new, consistent solution + if not spec: + # filter out solution precs and reinsert the conflict. Any resolution + # of the conflict should be explicit (i.e. it must be in ssc.specs_map) + ssc.solution_precs = [ + _ for _ in ssc.solution_precs if _.name != name + ] + ssc.solution_precs.append(prec) + final_environment_specs.add(spec) + + ssc.final_environment_specs = final_environment_specs + return ssc + + def _post_sat_handling(self, ssc): + # Special case handling for various DepsModifier flags. + final_environment_specs = ssc.final_environment_specs + if ssc.deps_modifier == DepsModifier.NO_DEPS: + # In the NO_DEPS case, we need to start with the original list of packages in the + # environment, and then only modify packages that match specs_to_add or + # specs_to_remove. + # + # Help information notes that use of NO_DEPS is expected to lead to broken + # environments. + _no_deps_solution = IndexedSet(ssc.prefix_data.iter_records()) + only_remove_these = { + prec + for spec in self.specs_to_remove + for prec in _no_deps_solution + if spec.match(prec) + } + _no_deps_solution -= only_remove_these + + only_add_these = { + prec + for spec in self.specs_to_add + for prec in ssc.solution_precs + if spec.match(prec) + } + remove_before_adding_back = {prec.name for prec in only_add_these} + _no_deps_solution = IndexedSet( + prec + for prec in _no_deps_solution + if prec.name not in remove_before_adding_back + ) + _no_deps_solution |= only_add_these + ssc.solution_precs = _no_deps_solution + + # TODO: check if solution is satisfiable, and emit warning if it's not + + elif ( + ssc.deps_modifier == DepsModifier.ONLY_DEPS + and ssc.update_modifier != UpdateModifier.UPDATE_DEPS + ): + # Using a special instance of PrefixGraph to remove youngest child nodes that match + # the original specs_to_add. It's important to remove only the *youngest* child nodes, + # because a typical use might be `conda install --only-deps python=2 flask`, and in + # that case we'd want to keep python. + # + # What are we supposed to do if flask was already in the environment? + # We can't be removing stuff here that's already in the environment. + # + # What should be recorded for the user-requested specs in this case? Probably all + # direct dependencies of flask. + graph = PrefixGraph(ssc.solution_precs, self.specs_to_add) + removed_nodes = graph.remove_youngest_descendant_nodes_with_specs() + self.specs_to_add = set(self.specs_to_add) + for prec in removed_nodes: + for dep in prec.depends: + dep = MatchSpec(dep) + if dep.name not in ssc.specs_map: + self.specs_to_add.add(dep) + # unfreeze + self.specs_to_add = frozenset(self.specs_to_add) + + # Add back packages that are already in the prefix. + specs_to_remove_names = {spec.name for spec in self.specs_to_remove} + add_back = tuple( + ssc.prefix_data.get(node.name, None) + for node in removed_nodes + if node.name not in specs_to_remove_names + ) + ssc.solution_precs = tuple( + PrefixGraph((*graph.graph, *filter(None, add_back))).graph + ) + + # TODO: check if solution is satisfiable, and emit warning if it's not + + elif ssc.update_modifier == UpdateModifier.UPDATE_DEPS: + # Here we have to SAT solve again :( It's only now that we know the dependency + # chain of specs_to_add. + # + # UPDATE_DEPS is effectively making each spec in the dependency chain a user-requested + # spec. We don't modify pinned_specs, track_features_specs, or specs_to_add. For + # all other specs, we drop all information but name, drop target, and add them to + # the specs_to_add that gets recorded in the history file. + # + # It's like UPDATE_ALL, but only for certain dependency chains. + graph = PrefixGraph(ssc.solution_precs) + update_names = set() + for spec in self.specs_to_add: + node = graph.get_node_by_name(spec.name) + update_names.update( + ancest_rec.name for ancest_rec in graph.all_ancestors(node) + ) + specs_map = {name: MatchSpec(name) for name in update_names} + + # Remove pinned_specs and any python spec (due to major-minor pinning business rule). + # Add in the original specs_to_add on top. + for spec in ssc.pinned_specs: + specs_map.pop(spec.name, None) + if "python" in specs_map: + python_rec = ssc.prefix_data.get("python") + py_ver = ".".join(python_rec.version.split(".")[:2]) + ".*" + specs_map["python"] = MatchSpec(name="python", version=py_ver) + specs_map.update({spec.name: spec for spec in self.specs_to_add}) + new_specs_to_add = tuple(specs_map.values()) + + # It feels wrong/unsafe to modify this instance, but I guess let's go with it for now. + self.specs_to_add = new_specs_to_add + ssc.solution_precs = self.solve_final_state( + update_modifier=UpdateModifier.UPDATE_SPECS, + deps_modifier=ssc.deps_modifier, + prune=ssc.prune, + ignore_pinned=ssc.ignore_pinned, + force_remove=ssc.force_remove, + ) + ssc.prune = False + + if ssc.prune: + graph = PrefixGraph(ssc.solution_precs, final_environment_specs) + graph.prune() + ssc.solution_precs = tuple(graph.graph) + + return ssc + + def _notify_conda_outdated(self, link_precs): + if not context.notify_outdated_conda or context.quiet: + return + current_conda_prefix_rec = PrefixData(context.conda_prefix).get("conda", None) + if current_conda_prefix_rec: + channel_name = current_conda_prefix_rec.channel.canonical_name + if channel_name == UNKNOWN_CHANNEL: + channel_name = "defaults" + + # only look for a newer conda in the channel conda is currently installed from + conda_newer_spec = MatchSpec(f"{channel_name}::conda>{CONDA_VERSION}") + + if paths_equal(self.prefix, context.conda_prefix): + if any(conda_newer_spec.match(prec) for prec in link_precs): + return + + conda_newer_precs = sorted( + SubdirData.query_all( + conda_newer_spec, + self.channels, + self.subdirs, + repodata_fn=self._repodata_fn, + ), + key=lambda x: VersionOrder(x.version), + # VersionOrder is fine here rather than r.version_key because all precs + # should come from the same channel + ) + if conda_newer_precs: + latest_version = conda_newer_precs[-1].version + # If conda comes from defaults, ensure we're giving instructions to users + # that should resolve release timing issues between defaults and conda-forge. + print( + dedent( + f""" + + ==> WARNING: A newer version of conda exists. <== + current version: {CONDA_VERSION} + latest version: {latest_version} + + Please update conda by running + + $ conda update -n base -c {channel_name} conda + + Or to minimize the number of packages updated during conda update use + + conda install conda={latest_version} + + """ + ), + file=sys.stderr, + ) + + def _prepare(self, prepared_specs) -> tuple[ReducedIndex, Resolve]: + # All of this _prepare() method is hidden away down here. Someday we may want to further + # abstract away the use of `index` or the Resolve object. + + if self._prepared and prepared_specs == self._prepared_specs: + return self._index, self._r + + if hasattr(self, "_index") and self._index: + # added in install_actions for conda-build back-compat + self._prepared_specs = prepared_specs + self._r = Resolve(self._index, channels=self.channels) + else: + # add in required channels that aren't explicitly given in the channels list + # For correctness, we should probably add to additional_channels any channel that + # is given by PrefixData(self.prefix).all_subdir_urls(). However that causes + # usability problems with bad / expired tokens. + + additional_channels = set() + for spec in self.specs_to_add: + # TODO: correct handling for subdir isn't yet done + channel = spec.get_exact_value("channel") + if channel: + additional_channels.add(Channel(channel)) + + self.channels.update(additional_channels) + + self._prepared_specs = prepared_specs + self._index = reduced_index = ReducedIndex( + prepared_specs, + channels=self.channels, + prepend=False, + subdirs=self.subdirs, + use_local=False, + use_cache=False, + prefix=self.prefix, + repodata_fn=self._repodata_fn, + use_system=True, + ) + self._r = Resolve(reduced_index, channels=self.channels) + + self._prepared = True + return self._index, self._r + + +class SolverStateContainer: + # A mutable container with defined attributes to help keep method signatures clean + # and also keep track of important state variables. + + def __init__( + self, + prefix, + update_modifier, + deps_modifier, + prune, + ignore_pinned, + force_remove, + should_retry_solve, + ): + # prefix, channels, subdirs, specs_to_add, specs_to_remove + # self.prefix = prefix + # self.channels = channels + # self.subdirs = subdirs + # self.specs_to_add = specs_to_add + # self.specs_to_remove = specs_to_remove + + # Group 1. Behavior flags + self.update_modifier = update_modifier + self.deps_modifier = deps_modifier + self.prune = prune + self.ignore_pinned = ignore_pinned + self.force_remove = force_remove + self.should_retry_solve = should_retry_solve + + # Group 2. System state + self.prefix = prefix + # self.prefix_data = None + # self.specs_from_history_map = None + # self.track_features_specs = None + # self.pinned_specs = None + + # Group 3. Repository metadata + self.index = None + self.r = None + + # Group 4. Mutable working containers + self.specs_map = {} + self.solution_precs = None + self._init_solution_precs() + self.add_back_map = {} # name: (prec, spec) + self.final_environment_specs = None + + @memoizedproperty + def prefix_data(self): + return PrefixData(self.prefix) + + @memoizedproperty + def specs_from_history_map(self): + return History(self.prefix).get_requested_specs_map() + + @memoizedproperty + def track_features_specs(self): + return tuple(MatchSpec(x + "@") for x in context.track_features) + + @memoizedproperty + def pinned_specs(self): + return () if self.ignore_pinned else get_pinned_specs(self.prefix) + + def set_repository_metadata(self, index, r): + self.index, self.r = index, r + + def _init_solution_precs(self): + if self.prune: + # DO NOT add existing prefix data to solution on prune + self.solution_precs = tuple() + else: + self.solution_precs = tuple(self.prefix_data.iter_records()) + + def working_state_reset(self): + self.specs_map = {} + self._init_solution_precs() + self.add_back_map = {} # name: (prec, spec) + self.final_environment_specs = None + + +def get_pinned_specs(prefix: str) -> tuple[MatchSpec]: + """Find pinned specs from file and return a tuple of MatchSpec.""" + context_pinned_packages = tuple( + MatchSpec(spec, optional=True) for spec in context.pinned_packages + ) + prefix_data = PrefixData(prefix_path=prefix) + return context_pinned_packages + prefix_data.get_pinned_specs() + + +def diff_for_unlink_link_precs( + prefix, + final_precs, + specs_to_add=(), + force_reinstall=NULL, +) -> tuple[tuple[PackageRecord, ...], tuple[PackageRecord, ...]]: + # Ensure final_precs supports the IndexedSet interface + if not isinstance(final_precs, IndexedSet): + if not hasattr(final_precs, "__getitem__"): + raise TypeError("final_precs must support list indexing") + if not hasattr(final_precs, "__sub__"): + raise TypeError("final_precs must support set difference") + + previous_records = IndexedSet(PrefixGraph(PrefixData(prefix).iter_records()).graph) + force_reinstall = ( + context.force_reinstall if force_reinstall is NULL else force_reinstall + ) + + unlink_precs = previous_records - final_precs + link_precs = final_precs - previous_records + + def _add_to_unlink_and_link(rec): + link_precs.add(rec) + if prec in previous_records: + unlink_precs.add(rec) + + # If force_reinstall is enabled, make sure any package in specs_to_add is unlinked then + # re-linked + if force_reinstall: + for spec in specs_to_add: + prec = next((rec for rec in final_precs if spec.match(rec)), None) + if not prec: + raise RuntimeError(f"Could not find record for spec {spec}") + _add_to_unlink_and_link(prec) + + # add back 'noarch: python' packages to unlink and link if python version changes + python_spec = MatchSpec("python") + prev_python = next( + (rec for rec in previous_records if python_spec.match(rec)), None + ) + curr_python = next((rec for rec in final_precs if python_spec.match(rec)), None) + gmm = get_major_minor_version + if ( + prev_python + and curr_python + and gmm(prev_python.version) != gmm(curr_python.version) + ): + noarch_python_precs = (p for p in final_precs if p.noarch == NoarchType.python) + for prec in noarch_python_precs: + _add_to_unlink_and_link(prec) + + unlink_precs = IndexedSet( + reversed(sorted(unlink_precs, key=lambda x: previous_records.index(x))) + ) + link_precs = IndexedSet(sorted(link_precs, key=lambda x: final_precs.index(x))) + return tuple(unlink_precs), tuple(link_precs) diff --git a/miniconda3/lib/python3.13/site-packages/conda/core/subdir_data.py b/miniconda3/lib/python3.13/site-packages/conda/core/subdir_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3e95a97dc8911fdfe1c593db122645f6f3437c77 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/core/subdir_data.py @@ -0,0 +1,744 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools for managing a subdir's repodata.json.""" + +from __future__ import annotations + +import pickle +from collections import UserList, defaultdict +from functools import partial +from itertools import chain +from logging import getLogger +from os.path import exists, getmtime, isfile, join, splitext +from pathlib import Path +from time import time +from typing import TYPE_CHECKING + +from boltons.setutils import IndexedSet + +from ..auxlib.ish import dals +from ..base.constants import CONDA_PACKAGE_EXTENSION_V1, REPODATA_FN +from ..base.context import context +from ..common.io import DummyExecutor, ThreadLimitedThreadPoolExecutor, dashlist +from ..common.iterators import groupby_to_dict as groupby +from ..common.path import url_to_path +from ..common.serialize import json +from ..common.url import join_url +from ..exceptions import ChannelError, CondaUpgradeError, UnavailableInvalidChannel +from ..gateways.disk.delete import rm_rf +from ..gateways.repodata import ( + CACHE_STATE_SUFFIX, + CondaRepoInterface, + RepodataFetch, + RepodataState, + cache_fn_url, + create_cache_dir, + get_repo_interface, +) +from ..models.channel import Channel, all_channel_urls +from ..models.match_spec import MatchSpec +from ..models.records import PackageRecord + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from typing import Any, Self + + from ..gateways.repodata import RepodataCache, RepoInterface + +log = getLogger(__name__) + +REPODATA_PICKLE_VERSION = 30 +MAX_REPODATA_VERSION = 2 +REPODATA_HEADER_RE = b'"(_etag|_mod|_cache_control)":[ ]?"(.*?[^\\\\])"[,}\\s]' + + +class SubdirDataType(type): + def __call__(cls, channel: Channel, repodata_fn: str = REPODATA_FN) -> SubdirData: + if not channel.subdir: + raise ValueError("SubdirData requires a subdir-aware Channel.") + if channel.package_filename: + raise ValueError("Channel object cannot define `package_filename`") + if type(channel) is not Channel: + raise TypeError("`channel` must be a Channel object.") + now = time() + repodata_fn = repodata_fn or REPODATA_FN + cache_key = channel.url(with_credentials=True), repodata_fn + if cache_key in SubdirData._cache_: + cache_entry = SubdirData._cache_[cache_key] + if cache_key[0] and cache_key[0].startswith("file://"): + channel_url = channel.url() + if channel_url: + file_path = url_to_path(channel_url + "/" + repodata_fn) + if exists(file_path) and cache_entry._mtime >= getmtime(file_path): + return cache_entry + else: + return cache_entry + subdir_data_instance = super().__call__( + channel, repodata_fn, RepoInterface=get_repo_interface() + ) + subdir_data_instance._mtime = now + SubdirData._cache_[cache_key] = subdir_data_instance + return subdir_data_instance + + +class PackageRecordList(UserList): + """ + Lazily convert dicts to PackageRecord. + + This class inherits from the built-in UserList class and provides a way to lazily convert + dictionaries to PackageRecord objects. It overrides the __getitem__ method to check if the + item at the given index is a PackageRecord object. If not, it converts the dictionary to a + PackageRecord object and stores it in the data list. + + :param data: The list of items + """ + + def __getitem__(self, i: int) -> PackageRecord: + """ + Returns the PackageRecord at index i. If i is a slice, returns a new instance of + PackageRecordList containing the PackageRecords at the indices in i. If the PackageRecord + at index i is not already an instance of PackageRecord, it is converted to one and stored + back in the data list. + + :param i: An integer or slice object indicating the index or indices of the + PackageRecord(s) to be returned. + :return: If i is a slice, returns a new instance of PackageRecordList containing the + PackageRecords at the indices in i. If i is an integer, returns the PackageRecord + at index i. + """ + if isinstance(i, slice): + return self.__class__(self.data[i]) + else: + record = self.data[i] + if not isinstance(record, PackageRecord): + record = PackageRecord(**record) + self.data[i] = record + return record + + +class SubdirData(metaclass=SubdirDataType): + """ + A class representing the SubdirData. + + This class provides functionality for managing and caching SubdirData instances. + + :param channel: The channel object + :param repodata_fn: The name of the repodata file. Defaults to REPODATA_FN + :return: A SubdirData instance. + """ + + _cache_: dict[tuple[str, str], PackageRecordList | SubdirData] = {} + + @classmethod + def clear_cached_local_channel_data(cls, exclude_file: bool = True) -> None: + """ + Clear the cached local channel data. + + This method is used to clear the cached local channel data. It is primarily used during + unit tests to handle changes in the CONDA_USE_ONLY_TAR_BZ2 environment variable during the + process lifetime. + + :param exclude_file: A flag indicating whether to exclude file:// URLs from the cache. + """ + # This should only ever be needed during unit tests, when + # CONDA_USE_ONLY_TAR_BZ2 may change during process lifetime. + if exclude_file: + cls._cache_ = { + k: v for k, v in cls._cache_.items() if not k[0].startswith("file://") + } + else: + cls._cache_.clear() + + @staticmethod + def query_all( + package_ref_or_match_spec: MatchSpec | str, + channels: Iterable[Channel | str] | None = None, + subdirs: Iterable[str] | None = None, + repodata_fn: str = REPODATA_FN, + ) -> tuple[PackageRecord, ...]: + """ + Execute a query against all repodata instances in the channel/subdir + matrix. + + :param package_ref_or_match_spec: A `MatchSpec` query object. A `str` + will be turned into a `MatchSpec` automatically. + :param channels: An iterable of urls for channels or `Channel` objects. + If None, will fall back to `context.channels`. + :param subdirs: If None, will fall back to context.subdirs. + :param repodata_fn: The filename of the repodata. + :return: A tuple of `PackageRecord` objects. + """ + # ensure that this is not called by threaded code + create_cache_dir() + if channels is None: + channels = context.channels + channel_urls = all_channel_urls(channels, subdirs=subdirs) + if context.offline: + grouped_urls = groupby(lambda url: url.startswith("file://"), channel_urls) + ignored_urls = grouped_urls.get(False, ()) + if ignored_urls: + log.info( + "Ignoring the following channel urls because mode is offline.%s", + dashlist(ignored_urls), + ) + channel_urls = IndexedSet(grouped_urls.get(True, ())) + + def subdir_query(url: str) -> tuple[PackageRecord, ...]: + """ + Queries the SubdirData for a given URL and returns a tuple of PackageRecord objects. + + :param url: The URL of the SubdirData to query. + :return: A tuple of PackageRecord objects representing the query results. + """ + return tuple( + SubdirData(Channel(url), repodata_fn=repodata_fn).query( + package_ref_or_match_spec + ) + ) + + # TODO test timing with ProcessPoolExecutor + Executor = ( + DummyExecutor + if context.debug or context.repodata_threads == 1 + else partial( + ThreadLimitedThreadPoolExecutor, max_workers=context.repodata_threads + ) + ) + with Executor() as executor: + result = tuple( + chain.from_iterable(executor.map(subdir_query, channel_urls)) + ) + return result + + def query( + self, package_ref_or_match_spec: str | MatchSpec + ) -> Iterator[PackageRecord]: + """ + A function that queries for a specific package reference or MatchSpec object. + + :param package_ref_or_match_spec: The package reference or MatchSpec object to query. + :yields: PackageRecord objects. + """ + if not self._loaded: + self.load() + param = package_ref_or_match_spec + if isinstance(param, str): + param = MatchSpec(param) # type: ignore + if isinstance(param, MatchSpec): + if param.get_exact_value("name"): + package_name = param.get_exact_value("name") + for prec in self._iter_records_by_name(package_name): + if param.match(prec): + yield prec + else: + for prec in self.iter_records(): + if param.match(prec): + yield prec + else: + if not isinstance(param, PackageRecord): + raise TypeError("Query did not result in a record.") + for prec in self._iter_records_by_name(param.name): + if prec == param: + yield prec + + def __init__( + self, + channel: Channel, + repodata_fn: str = REPODATA_FN, + RepoInterface: type[RepoInterface] = CondaRepoInterface, + ): + """ + Initializes a new instance of the SubdirData class. + + :param channel: The channel object. + :param repodata_fn: The repodata filename. + :param RepoInterface: The RepoInterface class. + """ + if not channel.subdir: + raise ValueError("SubdirData requires a subdir-aware Channel.") + # metaclass __init__ asserts no package_filename + if channel.package_filename: # pragma: no cover + parts = channel.dump() + del parts["package_filename"] + channel = Channel(**parts) + self.channel = channel + # disallow None (typing) + self.url_w_subdir = self.channel.url(with_credentials=False) or "" + self.url_w_credentials = self.channel.url(with_credentials=True) or "" + # these can be overriden by repodata.json v2 + self._base_url = self.url_w_subdir + self._base_url_w_credentials = self.url_w_credentials + # whether or not to try using the new, trimmed-down repodata + self.repodata_fn = repodata_fn + self.RepoInterface = RepoInterface + self._loaded = False + self._key_mgr = None + + @property + def _repo(self) -> RepoInterface: + """ + Changes as we mutate self.repodata_fn. + """ + return self.repo_fetch._repo + + @property + def repo_cache(self) -> RepodataCache: + """ + Returns the `RepodataCache` object associated with the current instance of `SubdirData`. + """ + return self.repo_fetch.repo_cache + + @property + def repo_fetch(self) -> RepodataFetch: + """ + Object to get repodata. Not cached since self.repodata_fn is mutable. + + Replaces self._repo & self.repo_cache. + """ + return RepodataFetch( + Path(self.cache_path_base), + self.channel, + self.repodata_fn, + repo_interface_cls=self.RepoInterface, + ) + + def reload(self) -> Self: + """ + Update the instance with new information. + """ + self._loaded = False + self.load() + return self + + @property + def cache_path_base(self) -> str: + """ + Get the base path for caching the repodata.json file. + + This method returns the base path for caching the repodata.json file. It is used to + construct the full path for caching the file. + """ + return join( + create_cache_dir(), + splitext(cache_fn_url(self.url_w_credentials, self.repodata_fn))[0], + ) + + @property + def url_w_repodata_fn(self) -> str: + """ + Get the URL with the repodata filename. + + This method returns the URL with the repodata filename. + """ + return self.url_w_subdir + "/" + self.repodata_fn + + @property + def cache_path_json(self) -> Path: + """ + Get the path to the cache file. + + This method returns the path to the cache file. + """ + return Path( + self.cache_path_base + ("1" if context.use_only_tar_bz2 else "") + ".json" + ) + + @property + def cache_path_state(self) -> Path: + """ + Out-of-band etag and other state needed by the RepoInterface. + + Get the path to the cache state file. + + This method returns the path to the cache state file. + """ + return Path( + self.cache_path_base + + ("1" if context.use_only_tar_bz2 else "") + + CACHE_STATE_SUFFIX + ) + + @property + def cache_path_pickle(self) -> str: + """ + Get the path to the cache pickle file. + + This method returns the path to the cache pickle file. + """ + return self.cache_path_base + ("1" if context.use_only_tar_bz2 else "") + ".q" + + def load(self) -> Self: + """ + Load the internal state of the SubdirData instance. + + This method loads the internal state of the SubdirData instance. + """ + _internal_state = self._load() + if _internal_state.get("repodata_version", 0) > MAX_REPODATA_VERSION: + raise CondaUpgradeError( + dals( + """ + The current version of conda is too old to read repodata from + + %s + + (This version only supports repodata_version 1 and 2.) + Please update conda to use this channel. + """ + ) + % self.url_w_repodata_fn + ) + self._base_url = _internal_state.get("base_url", self.url_w_subdir) + self._base_url_w_credentials = _internal_state.get( + "base_url_w_credentials", self.url_w_credentials + ) + self._internal_state = _internal_state + self._package_records = _internal_state["_package_records"] + self._names_index = _internal_state["_names_index"] + # Unused since early 2023: + self._track_features_index = _internal_state["_track_features_index"] + self._loaded = True + return self + + def iter_records(self) -> Iterator[PackageRecord]: + """ + A function that iterates over package records. + + This function checks if the package records are loaded. If not loaded, it loads them. It + returns an iterator over the package records. The package_records attribute could + potentially be replaced with fully-converted UserList data after going through the entire + list. + """ + if not self._loaded: + self.load() + return iter(self._package_records) + # could replace self._package_records with fully-converted UserList.data + # after going through entire list + + def _iter_records_by_name(self, name: str) -> Iterator[PackageRecord]: + """ + A function that iterates over package records by name. + + This function iterates over package records and yields those whose name matches the given + name. If include_self is True, it also yields the record with the given name. + """ + for i in self._names_index[name]: + yield self._package_records[i] + + def _load(self) -> dict[str, Any]: + """ + Try to load repodata. If e.g. we are downloading + `current_repodata.json`, fall back to `repodata.json` when the former is + unavailable. + """ + try: + fetcher = self.repo_fetch + repodata, state = fetcher.fetch_latest_parsed() + return self._process_raw_repodata(repodata, state) + except UnavailableInvalidChannel: + if self.repodata_fn != REPODATA_FN: + self.repodata_fn = REPODATA_FN + return self._load() + else: + raise + + def _pickle_me(self) -> None: + """ + Pickle the object to the specified file. + """ + try: + log.debug( + "Saving pickled state for %s at %s", + self.url_w_repodata_fn, + self.cache_path_pickle, + ) + with open(self.cache_path_pickle, "wb") as fh: + pickle.dump(self._internal_state, fh, pickle.HIGHEST_PROTOCOL) + except Exception: + log.debug("Failed to dump pickled repodata.", exc_info=True) + + def _read_local_repodata(self, state: RepodataState) -> dict[str, Any]: + """ + Read local repodata from the cache and process it. + """ + # first try reading pickled data + _pickled_state = self._read_pickled(state) + if _pickled_state: + return _pickled_state + + raw_repodata_str, state = self.repo_fetch.read_cache() + _internal_state = self._process_raw_repodata_str(raw_repodata_str, state) + # taken care of by _process_raw_repodata(): + if self._internal_state is not _internal_state: + raise RuntimeError("Internal state out of sync.") + self._pickle_me() + return _internal_state + + def _pickle_valid_checks( + self, pickled_state: dict[str, Any], mod: str, etag: str + ) -> Iterator[tuple[str, Any, Any]]: + """ + Throw away the pickle if these don't all match. + + :param pickled_state: The pickled state to compare against. + :param mod: The modification information to check. + :param etag: The etag to compare against. + :yields: Tuples of the form (check_name, pickled_value, current_value). + """ + yield "_url", pickled_state.get("_url"), self.url_w_credentials + yield "_schannel", pickled_state.get("_schannel"), self.channel.canonical_name + yield ( + "_add_pip", + pickled_state.get("_add_pip"), + context.add_pip_as_python_dependency, + ) + yield "_mod", pickled_state.get("_mod"), mod + yield "_etag", pickled_state.get("_etag"), etag + yield ( + "_pickle_version", + pickled_state.get("_pickle_version"), + REPODATA_PICKLE_VERSION, + ) + yield "fn", pickled_state.get("fn"), self.repodata_fn + + def _read_pickled(self, state: RepodataState) -> dict[str, Any] | None: + """ + Read pickled repodata from the cache and process it. + + :param state: The repodata state. + :return: A dictionary containing the processed pickled repodata, or None if the repodata is + not pickled. + """ + if not isinstance(state, RepodataState): + state = RepodataState( + self.cache_path_json, + self.cache_path_state, + self.repodata_fn, + dict=state, + ) + + if not isfile(self.cache_path_pickle) or not isfile(self.cache_path_json): + # Don't trust pickled data if there is no accompanying json data + return None + + try: + if isfile(self.cache_path_pickle): + log.debug("found pickle file %s", self.cache_path_pickle) + with open(self.cache_path_pickle, "rb") as fh: + _pickled_state = pickle.load(fh) + except Exception: + log.debug("Failed to load pickled repodata.", exc_info=True) + rm_rf(self.cache_path_pickle) + return None + + def checks() -> Iterator[tuple[str, str | None, str]]: + """ + Generate a list of checks to verify the validity of a pickled state. + + :return: A list of tuples, where each tuple contains a check name, the value from the + pickled state, and the current value. + """ + return self._pickle_valid_checks(_pickled_state, state.mod, state.etag) + + def _check_pickled_valid() -> Iterator[bool]: + """ + Generate a generator that yields the results of checking the validity of a pickled + state. + + :yields: True if the pickled state is valid, False otherwise. + """ + for _, left, right in checks(): + yield left == right + + if not all(_check_pickled_valid()): + log.debug( + "Pickle load validation failed for %s at %s. %r", + self.url_w_repodata_fn, + self.cache_path_json, + tuple(checks()), + ) + return None + + return _pickled_state + + def _process_raw_repodata_str( + self, + raw_repodata_str: str, + state: RepodataState | None = None, + ) -> dict[str, Any]: + """State contains information that was previously in-band in raw_repodata_str. + + Process the raw repodata string and return the processed repodata. + + :param raw_repodata_str: The raw repodata string. + :return: A dictionary containing the processed repodata. + """ + json_obj = json.loads(raw_repodata_str or "{}") + return self._process_raw_repodata(json_obj, state=state) + + def _process_raw_repodata( + self, repodata: dict[str, Any], state: RepodataState | None = None + ) -> dict[str, Any]: + """ + Process the raw repodata dictionary and return the processed repodata. + + :param repodata: The raw repodata dictionary. + :param state: The repodata state. Defaults to None. + :return: A dictionary containing the processed repodata. + """ + if not isinstance(state, RepodataState): + state = RepodataState( + self.cache_path_json, + self.cache_path_state, + self.repodata_fn, + dict=state, + ) + + subdir = repodata.get("info", {}).get("subdir") or self.channel.subdir + if subdir != self.channel.subdir: + raise ValueError( + f"Repodata subdir ({subdir}) does not match channel ({self.channel.subdir})" + ) + add_pip = context.add_pip_as_python_dependency + schannel = self.channel.canonical_name + + self._package_records = _package_records = PackageRecordList() + self._names_index = _names_index = defaultdict(list) + self._track_features_index = _track_features_index = defaultdict(list) + base_url = self._get_base_url(repodata, with_credentials=False) + base_url_w_credentials = self._get_base_url(repodata, with_credentials=True) + + _internal_state = { + "channel": self.channel, + "url_w_subdir": self.url_w_subdir, + "url_w_credentials": self.url_w_credentials, + "base_url": base_url, + "base_url_w_credentials": base_url_w_credentials, + "cache_path_base": self.cache_path_base, + "fn": self.repodata_fn, + "_package_records": _package_records, + "_names_index": _names_index, + "_track_features_index": _track_features_index, + "_etag": state.get("_etag"), + "_mod": state.get("_mod"), + "_cache_control": state.get("_cache_control"), + "_url": state.get("_url"), + "_add_pip": add_pip, + "_pickle_version": REPODATA_PICKLE_VERSION, + "_schannel": schannel, + "repodata_version": state.get("repodata_version", 0), + } + if _internal_state["repodata_version"] > MAX_REPODATA_VERSION: + raise CondaUpgradeError( + dals( + """ + The current version of conda is too old to read repodata from + + %s + + (This version only supports repodata_version 1 and 2.) + Please update conda to use this channel. + """ + ) + % self.url_w_subdir + ) + + meta_in_common = { # just need to make this once, then apply with .update() + "arch": repodata.get("info", {}).get("arch"), + "channel": self.channel, + "platform": repodata.get("info", {}).get("platform"), + "schannel": schannel, + "subdir": subdir, + } + + legacy_packages = repodata.get("packages", {}) + conda_packages = ( + {} if context.use_only_tar_bz2 else repodata.get("packages.conda", {}) + ) + + _tar_bz2 = CONDA_PACKAGE_EXTENSION_V1 + use_these_legacy_keys = set(legacy_packages.keys()) - { + k[:-6] + _tar_bz2 for k in conda_packages.keys() + } + + for group, copy_legacy_md5 in ( + (conda_packages.items(), True), + (((k, legacy_packages[k]) for k in use_these_legacy_keys), False), + ): + for fn, info in group: + if copy_legacy_md5: + counterpart = f"{fn[: -len('.conda')]}.tar.bz2" + if counterpart in legacy_packages: + info["legacy_bz2_md5"] = legacy_packages[counterpart].get("md5") + info["legacy_bz2_size"] = legacy_packages[counterpart].get( + "size" + ) + if ( + add_pip + and info["name"] == "python" + and info["version"].startswith(("2.", "3.")) + ): + info["depends"].append("pip") + info.update(meta_in_common) + if info.get("record_version", 0) > 1: + log.debug( + "Ignoring record_version %d from %s", + info["record_version"], + info["url"], + ) + continue + + # lazy + # package_record = PackageRecord(**info) + info["fn"] = fn + info["url"] = join_url(base_url_w_credentials, fn) + _package_records.append(info) + record_index = len(_package_records) - 1 + _names_index[info["name"]].append(record_index) + + self._internal_state = _internal_state + return _internal_state + + def _get_base_url(self, repodata: dict, with_credentials: bool = True) -> str: + """ + In repodata_version=1, .tar.bz2 and .conda artifacts are assumed to + be colocated next to repodata.json, in the same server and directory. + + In repodata_version=2, repodata.json files can define a 'base_url' field + to override that default assumption. See CEP-15 for more details. + + This method deals with both cases and returns the appropriate value. + + Get the base URL for the given endpoint. + + :param endpoint: The endpoint for which the base URL is needed. + :return: The base URL corresponding to the provided endpoint. + """ + maybe_base_url = repodata.get("info", {}).get("base_url") + if maybe_base_url: # repodata defines base_url field + try: + base_url_parts = Channel(maybe_base_url).dump() + except ValueError as exc: + raise ChannelError( + f"Subdir for {self.channel.canonical_name} at url '{self.url_w_subdir}' " + "has invalid 'base_url'" + ) from exc + if with_credentials and self.url_w_credentials != self.url_w_subdir: + # We don't check for .token or .auth because those are not well defined + # in multichannel objects. It's safer to compare the resulting URLs. + # Note that base_url is assumed to have the same authentication as the repodata + channel_parts = self.channel.dump() + for key in ("auth", "token"): + if base_url_parts.get(key): + raise ChannelError( + f"'{self.url_w_subdir}' has 'base_url' with credentials. " + "This is not supported." + ) + channel_creds = channel_parts.get(key) + if channel_creds: + base_url_parts[key] = channel_creds + return Channel(**base_url_parts).url(with_credentials=True) + return maybe_base_url + if with_credentials: + return self.url_w_credentials + return self.url_w_subdir diff --git a/miniconda3/lib/python3.13/site-packages/conda/deprecations.py b/miniconda3/lib/python3.13/site-packages/conda/deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..837fab51fdf4304102eb041ea35f28c769c2cc48 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/deprecations.py @@ -0,0 +1,481 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools to aid in deprecating code.""" + +from __future__ import annotations + +import sys +import warnings +from argparse import SUPPRESS, Action +from dataclasses import dataclass, field +from functools import wraps +from types import ModuleType +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace + from collections.abc import Callable + from typing import Any, ParamSpec, Self, TypeVar + + from packaging.version import Version + + T = TypeVar("T") + P = ParamSpec("P") + + ActionType = TypeVar("ActionType", bound=type[Action]) + +from . import __version__ + + +class DeprecatedError(RuntimeError): + pass + + +# inspired by deprecation (https://deprecation.readthedocs.io/en/latest/) and +# CPython's warnings._deprecated +class DeprecationHandler: + _version: str | None + _version_tuple: tuple[int, ...] | None + _version_object: Version | None + + def __init__(self: Self, version: str) -> None: + """Factory to create a deprecation handle for the specified version. + + :param version: The version to compare against when checking deprecation statuses. + """ + self._version = version + # Try to parse the version string as a simple tuple[int, ...] to avoid + # packaging.version import and costlier version comparisons. + self._version_tuple = self._get_version_tuple(version) + self._version_object = None + + @staticmethod + def _get_version_tuple(version: str) -> tuple[int, ...] | None: + """Return version as non-empty tuple of ints if possible, else None. + + :param version: Version string to parse. + """ + try: + return tuple(int(part) for part in version.strip().split(".")) or None + except (AttributeError, ValueError): + return None + + def _version_less_than(self: Self, version: str) -> bool: + """Test whether own version is less than the given version. + + :param version: Version string to compare against. + """ + if self._version_tuple and (version_tuple := self._get_version_tuple(version)): + return self._version_tuple < version_tuple + + # If self._version or version could not be represented by a simple + # tuple[int, ...], do a more elaborate version parsing and comparison. + # Avoid this import otherwise to reduce import time for conda activate. + from packaging.version import parse + + if self._version_object is None: + try: + self._version_object = parse(self._version) # type: ignore[arg-type] + except TypeError: + # TypeError: self._version could not be parsed + self._version_object = parse("0.0.0.dev0+placeholder") + return self._version_object < parse(version) + + def __call__( + self: Self, + deprecate_in: str, + remove_in: str, + *, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> Callable[[Callable[P, T]], Callable[P, T]]: + """Deprecation decorator for functions, methods, & classes. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + + def deprecated_decorator(obj: Callable[P, T]) -> Callable[P, T]: + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=f"{obj.__module__}.{obj.__qualname__}", + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # if obj is a class, wrap the __init__ + isclass = False + func: Callable[P, T] + if isinstance(obj, type): + try: + func = obj.__init__ # type: ignore[misc] + except AttributeError: + # AttributeError: obj has no __init__ + func = obj + else: + isclass = True + else: + func = obj + + # alert user that it's time to remove something + @wraps(func) # type: ignore[reportArgumentType] + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + warnings.warn(message, category, stacklevel=2 + stack) + + return func(*args, **kwargs) + + if isclass: + obj.__init__ = inner # type: ignore[misc] + return obj + else: + return inner + + return deprecated_decorator + + def argument( + self: Self, + deprecate_in: str, + remove_in: str, + argument: str, + *, + rename: str | None = None, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> Callable[[Callable[P, T]], Callable[P, T]]: + """Deprecation decorator for keyword arguments. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param argument: The argument to deprecate. + :param rename: Optional new argument name. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + + def deprecated_decorator(func: Callable[P, T]) -> Callable[P, T]: + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=f"{func.__module__}.{func.__qualname__}({argument})", + # provide a default addendum if renaming and no addendum is provided + addendum=( + f"Use '{rename}' instead." if rename and not addendum else addendum + ), + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # alert user that it's time to remove something + @wraps(func) + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + # only warn about argument deprecations if the argument is used + if argument in kwargs: + warnings.warn(message, category, stacklevel=2 + stack) + + # rename argument deprecations as needed + value = kwargs.pop(argument, None) + if rename: + kwargs.setdefault(rename, value) + + return func(*args, **kwargs) + + return inner + + return deprecated_decorator + + def action( + self: Self, + deprecate_in: str, + remove_in: str, + action: ActionType, + *, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = FutureWarning, + ) -> ActionType: + """Wraps any argparse.Action to issue a deprecation warning.""" + + class DeprecationMixin(Action): + category: type[Warning] + help: str # override argparse.Action's help type annotation + + def __init__(inner_self: Self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=( + # option_string are ordered shortest to longest, + # use the longest as it's the most descriptive + f"`{inner_self.option_strings[-1]}`" + if inner_self.option_strings + # if not a flag/switch, use the destination itself + else f"`{inner_self.dest}`" + ), + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + inner_self.category = category + inner_self.deprecation = message + if inner_self.help is not SUPPRESS: + inner_self.help = message + + def __call__( + inner_self: Self, + parser: ArgumentParser, + namespace: Namespace, + values: Any, + option_string: str | None = None, + ) -> None: + # alert user that it's time to remove something + from conda.common.constants import NULL + + if values is not NULL: + warnings.warn( + inner_self.deprecation, + inner_self.category, + stacklevel=7 + stack, + ) + + super().__call__(parser, namespace, values, option_string) + + return type(action.__name__, (DeprecationMixin, action), {}) # type: ignore[return-value] + + def module( + self: Self, + deprecate_in: str, + remove_in: str, + *, + addendum: str | None = None, + stack: int = 0, + ) -> None: + """Deprecation function for modules. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + self.topic( + deprecate_in=deprecate_in, + remove_in=remove_in, + topic=self._get_module(stack)[1], + addendum=addendum, + stack=2 + stack, + ) + + def constant( + self: Self, + deprecate_in: str, + remove_in: str, + constant: str, + value: Any, + *, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> None: + """Deprecation function for module constant/global. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param constant: + :param value: + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + # detect calling module + module, fullname = self._get_module(stack) + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=f"{fullname}.{constant}", + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # patch module level __getattr__ to alert user that it's time to remove something + if isinstance( + fallback := getattr(module, "__getattr__", None), + _ConstantDeprecationRegistry, + ): + deprecations = fallback + else: + deprecations = _ConstantDeprecationRegistry(fullname, fallback) + module.__getattr__ = deprecations # type: ignore[method-assign] + + deprecations.register(constant, message, category, stack, value) + + def topic( + self: Self, + deprecate_in: str, + remove_in: str, + *, + topic: str, + addendum: str | None = None, + stack: int = 0, + deprecation_type: type[Warning] = DeprecationWarning, + ) -> None: + """Deprecation function for a topic. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param topic: The topic being deprecated. + :param addendum: Optional additional messaging. Useful to indicate what to do instead. + :param stack: Optional stacklevel increment. + """ + # detect function name and generate message + category, message = self._generate_message( + deprecate_in=deprecate_in, + remove_in=remove_in, + prefix=topic, + addendum=addendum, + deprecation_type=deprecation_type, + ) + + # alert developer that it's time to remove something + if not category: + raise DeprecatedError(message) + + # alert user that it's time to remove something + warnings.warn(message, category, stacklevel=2 + stack) + + def _get_module(self: Self, stack: int) -> tuple[ModuleType, str]: + """Detect the module from which we are being called. + + :param stack: The stacklevel increment. + :return: The module and module name. + """ + try: + frame = sys._getframe(2 + stack) + except IndexError: + # IndexError: 2 + stack is out of range + pass + else: + # Shortcut finding the module by manually inspecting loaded modules. + try: + filename = frame.f_code.co_filename + except AttributeError: + # AttributeError: frame.f_code.co_filename is undefined + pass + else: + # use a copy of sys.modules to avoid RuntimeError during iteration + # see https://github.com/conda/conda/issues/13754 + for loaded in tuple(sys.modules.values()): + if not isinstance(loaded, ModuleType): + continue + if not hasattr(loaded, "__file__"): + continue + if loaded.__file__ == filename: + return (loaded, loaded.__name__) + + # If above failed, do an expensive import and costly getmodule call. + import inspect + + module = inspect.getmodule(frame) + if module is not None: + return (module, module.__name__) + + raise DeprecatedError("unable to determine the calling module") + + def _generate_message( + self: Self, + deprecate_in: str, + remove_in: str, + prefix: str, + addendum: str | None, + *, + deprecation_type: type[Warning], + ) -> tuple[type[Warning] | None, str]: + """Generate the standardized deprecation message and determine whether the + deprecation is pending, active, or past. + + :param deprecate_in: Version in which code will be marked as deprecated. + :param remove_in: Version in which code is expected to be removed. + :param prefix: The message prefix, usually the function name. + :param addendum: Additional messaging. Useful to indicate what to do instead. + :param deprecation_type: The warning type to use for active deprecations. + :return: The warning category (if applicable) and the message. + """ + category: type[Warning] | None + if self._version_less_than(deprecate_in): + category = PendingDeprecationWarning + warning = f"is pending deprecation and will be removed in {remove_in}." + elif self._version_less_than(remove_in): + category = deprecation_type + warning = f"is deprecated and will be removed in {remove_in}." + else: + category = None + warning = f"was slated for removal in {remove_in}." + + return ( + category, + " ".join(filter(None, [prefix, warning, addendum])), # message + ) + + +@dataclass +class _ConstantDeprecationRegistry: + """Registry of deprecated module constants. + + Serves as a module's __getattr__, issuing deprecation warnings + when registered constants are accessed. + """ + + deprecations: dict[str, tuple[str, type[Warning], int, Any]] = field( + default_factory=dict, + init=False, + repr=False, + ) + fullname: str + fallback: Callable[[str], Any] | None + + def __call__(self, name: str) -> Any: + if name in self.deprecations: + message, category, stacklevel, value = self.deprecations[name] + warnings.warn(message, category, stacklevel=stacklevel) + return value + + if self.fallback: + return self.fallback(name) + + raise AttributeError(f"module '{self.fullname}' has no attribute '{name}'") + + def register( + self, + constant: str, + message: str, + category: type[Warning], + stack: int, + value: Any, + ) -> None: + # stacklevel=2 points from __call__ to user code accessing the constant + self.deprecations[constant] = (message, category, 2 + stack, value) + + +deprecated = DeprecationHandler(__version__) diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/env.py b/miniconda3/lib/python3.13/site-packages/conda/env/env.py new file mode 100644 index 0000000000000000000000000000000000000000..ce37fc36eeb29980be7297556f7d917409e24c35 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/env.py @@ -0,0 +1,483 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Environment object describing the conda environment.yaml file.""" + +from __future__ import annotations + +import os +import re +from itertools import chain +from typing import TYPE_CHECKING + +from ..base.context import context +from ..cli import common +from ..common.io import dashlist +from ..common.iterators import unique +from ..common.path import expand +from ..common.serialize import json, yaml +from ..core.prefix_data import PrefixData +from ..deprecations import deprecated +from ..exceptions import ( + CondaMultiError, + EnvironmentFileEmpty, + EnvironmentFileInvalid, + EnvironmentFileNotFound, + InvalidMatchSpec, +) +from ..gateways.connection.download import download_text +from ..gateways.connection.session import CONDA_SESSION_SCHEMES +from ..history import History +from ..models.environment import Environment as EnvironmentModel +from ..models.environment import EnvironmentConfig +from ..models.match_spec import MatchSpec + +if TYPE_CHECKING: + from typing import Any + +REQUIRED_KEYS = frozenset(("dependencies",)) +OPTIONAL_KEYS = frozenset( + ( + "name", + "prefix", + "channels", + "variables", + ) +) +VALID_KEYS = frozenset((*REQUIRED_KEYS, *OPTIONAL_KEYS)) + + +def field_type_validation(field_name: str, value: Any, value_type: Any) -> None: + """Validates the type of a value""" + if not isinstance(value, value_type): + raise EnvironmentFileInvalid( + f"Invalid type for '{field_name}', expected a {value_type.__name__}" + ) + + +def prefix_validation(prefix: str): + """Validate the contents of the prefix field. + + Will ensure: + * prefix is a string + """ + field_type_validation("prefix", prefix, str) + + +def name_validation(name: str): + """Validate the contents of the name field. + + Will ensure: + * name is a string + """ + field_type_validation("name", name, str) + + +def dependencies_validation(dependencies: list): + """Validate the contents of the dependencies field. + + Will ensure: + * dependencies are a list + * all string dependencies are MatchSpec compatible + * the only other type allowed is a dict + """ + field_type_validation("dependencies", dependencies, list) + + errors = [] + for dependency in dependencies: + if isinstance(dependency, str): + # If the dependency is a string type, it must be + # MatchSpec compatible. + try: + MatchSpec(dependency) + except InvalidMatchSpec as err: + errors.append(EnvironmentFileInvalid(str(err))) + elif isinstance(dependency, dict): + # dict types are also allowed. There are no requirements + # for the form of this entry + pass + else: + # All other types are invalid + errors.append( + EnvironmentFileInvalid( + f"'{dependency}' is an invalid type for a 'dependency'" + ) + ) + + if errors: + raise CondaMultiError(errors) + + +def channels_validation(channels: list): + """Validate the contents of the channels field. + + Will ensure: + * channels is a list + * all entries are strings + """ + field_type_validation("channels", channels, list) + + for channel in channels: + if not isinstance(channel, str): + raise EnvironmentFileInvalid( + "`channels` key must only contain strings. Found '{channel}'" + ) + + +def variables_validation(variables: dict[str, str]): + """Validate the contents of the variables field. + + Will ensure: + * variables is a dict + * all entries are strings + """ + field_type_validation("variables", variables, dict) + + +SCHEMA_VALIDATORS = { + "name": name_validation, + "prefix": prefix_validation, + "dependencies": dependencies_validation, + "channels": channels_validation, + "variables": variables_validation, +} + + +def get_schema_errors(data: dict) -> list[EnvironmentFileInvalid]: + """Parses environment.yaml data to build a list of schema errors + + Will produce errors to ensure: + * all required fields are present + * all fields contain valid data + + :param dict data: The contents of the environment.yaml + :returns errors: A list of EnvironmentFileInvalid exceptions that occurred during validation + """ + errors = [] + # Ensure all required keys are present + for field in REQUIRED_KEYS.difference(data): + errors.append(EnvironmentFileInvalid(f"Missing required field '{field}'")) + + # Run validations on all the relevant fields, extra keys are ignored + for key, validator in SCHEMA_VALIDATORS.items(): + try: + validator(data[key]) + except KeyError: + pass + except EnvironmentFileInvalid as err: + errors.append(err) + + return errors + + +def validate_keys(data, kwargs): + """Check for unknown keys, remove them and print a warning""" + invalid_keys = [] + new_data = data.copy() if data else {} + for key in data.keys(): + if key not in VALID_KEYS: + invalid_keys.append(key) + new_data.pop(key) + + if invalid_keys: + filename = kwargs.get("filename") + verb = "are" if len(invalid_keys) != 1 else "is" + plural = "s" if len(invalid_keys) != 1 else "" + print( + f"\nEnvironmentSectionNotValid: The following section{plural} on " + f"'{filename}' {verb} invalid and will be ignored:" + ) + for key in invalid_keys: + print(f" - {key}") + print() + + deps = data.get("dependencies") or [] + depsplit = re.compile(r"[<>~\s=]") + is_pip = lambda dep: "pip" in depsplit.split(dep)[0].split("::") + lists_pip = any(is_pip(dep) for dep in deps if not isinstance(dep, dict)) + for dep in deps: + if isinstance(dep, dict) and "pip" in dep and not lists_pip: + print( + "Warning: you have pip-installed dependencies in your environment file, " + "but you do not list pip itself as one of your conda dependencies. Conda " + "may not use the correct pip to install your packages, and they may end up " + "in the wrong place. Please add an explicit pip dependency. I'm adding one" + " for you, but still nagging you." + ) + new_data["dependencies"].insert(0, "pip") + break + return new_data + + +def from_environment( + name, prefix, no_builds=False, ignore_channels=False, from_history=False +): + """ + Get ``EnvironmentYaml`` object from prefix + Args: + name: The name of environment + prefix: The path of prefix + no_builds: Whether has build requirement + ignore_channels: whether ignore_channels + from_history: Whether environment file should be based on explicit specs in history + + Returns: EnvironmentYaml object + """ + pd = PrefixData(prefix, interoperability=True) + variables = pd.get_environment_env_vars() + + if from_history: + history = History(prefix).get_requested_specs_map() + deps = [str(package) for package in history.values()] + return EnvironmentYaml( + name=name, + dependencies=deps, + channels=list(context.channels), + prefix=prefix, + variables=variables, + ) + + conda_precs = pd.get_conda_packages() + python_precs = pd.get_python_packages() + + dependencies = [ + conda_prec.spec_no_build if no_builds else conda_prec.spec + for conda_prec in conda_precs + ] + if python_precs: + dependencies.append( + { + "pip": [ + f"{python_prec.name}=={python_prec.version}" + for python_prec in python_precs + ] + } + ) + + channels = list(context.channels) + if not ignore_channels: + for conda_prec in conda_precs: + canonical_name = conda_prec.channel.canonical_name + if canonical_name not in channels: + channels.insert(0, canonical_name) + + return EnvironmentYaml( + name=name, + dependencies=dependencies, + channels=channels, + prefix=prefix, + variables=variables, + ) + + +def from_yaml(yamlstr: str, **kwargs) -> EnvironmentYaml: + """Load and return a ``EnvironmentYaml`` from a given ``yaml`` string + + :param yamlstr: The contents of the environment.yaml + :param raise_validation_errors: Indicates if an error should be raised if the yamlstr + is found to be invalid + :returns EnvironmentYaml: A representation of the environment file + """ + data = yaml.loads(yamlstr) + filename = kwargs.get("filename") + if data is None: + raise EnvironmentFileEmpty(filename) + + # Perform schema validation. This will output a warning for any invalid schema. + errors = get_schema_errors(data) + if errors: + # Warn for all the schema errors in the environment + deprecated.topic( + "26.3", + "26.9", + topic="The environment file is not fully CEP 24 compliant", + addendum=( + "In the future, this configuration will be rejected. Please fix the following " + "errors in order to make the configuration valid: " + f"{dashlist(errors)}" + ), + deprecation_type=FutureWarning, + ) + + data = validate_keys(data, kwargs) + + if kwargs is not None: + for key, value in kwargs.items(): + data[key] = value + _expand_channels(data) + return EnvironmentYaml(**data) + + +def _expand_channels(data): + """Expands ``EnvironmentYaml`` variables for the channels found in the ``yaml`` data""" + data["channels"] = [ + os.path.expandvars(channel) for channel in data.get("channels", []) + ] + + +def load_file(filename): + """Load and return an yaml string from a given file""" + url_scheme = filename.split("://", 1)[0] + if url_scheme in CONDA_SESSION_SCHEMES: + yamlstr = download_text(filename) + elif not os.path.exists(filename): + raise EnvironmentFileNotFound(filename) + else: + with open(filename, "rb") as fp: + yamlb = fp.read() + try: + yamlstr = yamlb.decode("utf-8") + except UnicodeDecodeError: + yamlstr = yamlb.decode("utf-16") + return yamlstr + + +def from_file(filename): + """Load and return an ``EnvironmentYaml`` from a given file""" + yamlstr = load_file(filename) + return from_yaml(yamlstr, filename=filename) + + +class Dependencies(dict): + """A ``dict`` subclass that parses the raw dependencies into a conda and pip list""" + + def __init__(self, raw, *args, **kwargs): + super().__init__(*args, **kwargs) + self.raw = raw + self.parse() + + def parse(self): + """Parse the raw dependencies into a conda and pip list""" + if not self.raw: + return + + self.update({"conda": []}) + + for line in self.raw: + if isinstance(line, dict): + self.update(line) + else: + self["conda"].append(str(MatchSpec(line))) + + if "pip" in self: + if not self["pip"]: + del self["pip"] + if not any(MatchSpec(s).name == "pip" for s in self["conda"]): + self["conda"].append("pip") + + # TODO only append when it's not already present + def add(self, package_name): + """Add a package to the ``EnvironmentYaml``""" + self.raw.append(package_name) + self.parse() + + +class EnvironmentYaml: + """A class representing an ``environment.yaml`` file""" + + def __init__( + self, + name=None, + filename=None, + channels=None, + dependencies=None, + prefix=None, + variables=None, + ): + self.name = name + self.filename = filename + self.prefix = prefix + self.dependencies = Dependencies(dependencies) + self.variables = variables + + if channels is None: + channels = [] + self.channels = channels + + def add_channels(self, channels): + """Add channels to the ``EnvironmentYaml``""" + self.channels = list(unique(chain.from_iterable((channels, self.channels)))) + + def remove_channels(self): + """Remove all channels from the ``EnvironmentYaml``""" + self.channels = [] + + def to_dict(self, stream=None): + """Convert information related to the ``EnvironmentYaml`` into a dictionary""" + d = {"name": self.name} + if self.channels: + d["channels"] = self.channels + if self.dependencies: + d["dependencies"] = self.dependencies.raw + if self.variables: + d["variables"] = self.variables + if self.prefix: + d["prefix"] = self.prefix + if stream is None: + return d + stream.write(json.dumps(d)) + + def to_yaml(self, stream=None): + """Convert information related to the ``EnvironmentYaml`` into a ``yaml`` string""" + d = self.to_dict() + return yaml.write(d, fp=stream) + + def save(self): + """Save the ``EnvironmentYaml`` data to a ``yaml`` file""" + with open(self.filename, "wb") as fp: + self.to_yaml(stream=fp) + + def to_environment_model(self) -> EnvironmentModel: + """Convert the ``Environment`` into a ``model.Environment`` object""" + config = EnvironmentConfig(channels=tuple(self.channels)) + + external_packages = {} + if pip_dependencies := self.dependencies.get("pip"): + external_packages["pip"] = pip_dependencies + + requested_packages = [ + MatchSpec(spec) for spec in self.dependencies.get("conda", []) + ] + + return EnvironmentModel( + prefix=self.prefix or context.target_prefix, + platform=context.subdir, + name=self.name, + config=config, + variables=self.variables, + external_packages=external_packages, + requested_packages=requested_packages, + ) + + +@deprecated("26.3", "26.9", addendum="Use `conda.env.env.EnvironmentYaml` instead.") +class Environment(EnvironmentYaml): + """A class representing an ``environment.yaml`` file""" + + +@deprecated("25.9", "26.3") +def get_filename(filename): + """Expand filename if local path or return the ``url``""" + url_scheme = filename.split("://", 1)[0] + if url_scheme in CONDA_SESSION_SCHEMES: + return filename + else: + return expand(filename) + + +def print_result(args, prefix, result): + """Print the result of an install operation""" + if context.json: + if result["conda"] is None and result["pip"] is None: + common.stdout_json_success( + message="All requested packages already installed." + ) + else: + if result["conda"] is not None: + actions = result["conda"] + else: + actions = {} + if result["pip"] is not None: + actions["PIP"] = result["pip"] + common.stdout_json_success(prefix=prefix, actions=actions) + else: + common.print_activate(args.name or prefix) diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/installers/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/env/installers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/installers/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/installers/base.py b/miniconda3/lib/python3.13/site-packages/conda/env/installers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..461e74ffb67bfd7b7d7d6d0e58811bcb01497718 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/installers/base.py @@ -0,0 +1,19 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Dynamic installer loading.""" + +import importlib + +from ...exceptions import InvalidInstaller + + +def get_installer(name): + """ + Gets the installer for the given environment. + + Raises: InvalidInstaller if unable to load installer + """ + try: + return importlib.import_module(f"conda.env.installers.{name}") + except ImportError: + raise InvalidInstaller(name) diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/installers/conda.py b/miniconda3/lib/python3.13/site-packages/conda/env/installers/conda.py new file mode 100644 index 0000000000000000000000000000000000000000..e6fca47d2e750263a43f5b9ec5742baa952a61e6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/installers/conda.py @@ -0,0 +1,133 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda-flavored installer.""" + +from __future__ import annotations + +import tempfile +from os.path import basename +from typing import TYPE_CHECKING + +from boltons.setutils import IndexedSet + +from ...base.constants import UpdateModifier +from ...base.context import context +from ...common.constants import NULL +from ...env.env import EnvironmentYaml +from ...exceptions import CondaValueError, UnsatisfiableError +from ...models.channel import Channel, prioritize_channels + +if TYPE_CHECKING: + from argparse import Namespace + + from ...core.solve import Solver + from ...models.environment import Environment + + +def _solve( + prefix: str, specs: list[str], args: Namespace, env: Environment, *_, **kwargs +) -> Solver: + """Solve the environment. + + :param prefix: Installation target directory + :param specs: Package specifications to install + :param args: Command-line arguments + :param env: Environment object + :return: Solver object + """ + # TODO: support all various ways this happens + # Including 'nodefaults' in the channels list disables the defaults + channel_urls = [chan for chan in env.config.channels if chan != "nodefaults"] + + if "nodefaults" not in env.config.channels: + channel_urls.extend(context.channels) + _channel_priority_map = prioritize_channels(channel_urls) + + channels = IndexedSet(Channel(url) for url in _channel_priority_map) + subdirs = IndexedSet(basename(url) for url in _channel_priority_map) + + solver_backend = context.plugin_manager.get_cached_solver_backend() + if solver_backend is None: + raise CondaValueError("No solver backend found") + solver = solver_backend(prefix, channels, subdirs, specs_to_add=specs) + return solver + + +def dry_run( + specs: list[str], args: Namespace, env: Environment, *_, **kwargs +) -> EnvironmentYaml: + """Do a dry run of the environment solve. + + :param specs: Package specifications to install + :param args: Command-line arguments + :param env: Environment object + :return: Solved environment object + :rtype: EnvironmentYaml + """ + solver = _solve(tempfile.mkdtemp(), specs, args, env, *_, **kwargs) + pkgs = solver.solve_final_state() + return EnvironmentYaml( + name=env.name, dependencies=[str(p) for p in pkgs], channels=env.config.channels + ) + + +def install( + prefix: str, specs: list[str], args: Namespace, env: Environment, *_, **kwargs +) -> dict | None: + """Install packages into a conda environment. + + This function handles two main paths: + 1. For environments with explicit_specs (from @EXPLICIT files): Bypasses the solver + and directly installs packages using conda.misc.explicit() as required by CEP-23. + 2. For regular Environment instances: Uses the solver to determine the optimal + package set before installation. + + :param prefix: The target installation path for the environment + :param specs: Package specifications to install + :param args: Command-line arguments from the conda command + :param env: Environment object containing dependencies and channels + :return: Installation result information + + .. note:: + This implementation follows CEP-23, which states: "When an explicit input file is + processed, the conda client SHOULD NOT invoke a solver." + """ + # Handle explicit environments separately per CEP-23 requirements + if env.explicit_packages: + from ...misc import install_explicit_packages + + # For explicit environments, we consider any provided specs as user-requested + # All packages in the explicit file are installed, but only user-provided specs + # are recorded in history as explicitly requested + requested_specs = specs if specs else () + + # Install explicit packages - bypassing the solver completely + return install_explicit_packages( + package_cache_records=env.explicit_packages, + prefix=prefix, + requested_specs=requested_specs, + ) + + # For regular environments, proceed with the normal solve-based installation + solver = _solve(prefix, specs, args, env, *_, **kwargs) + + try: + unlink_link_transaction = solver.solve_for_transaction( + prune=getattr(args, "prune", False), + update_modifier=UpdateModifier.FREEZE_INSTALLED, + ) + except (UnsatisfiableError, SystemExit) as exc: + # See this comment for 'allow_retry' details + # https://github.com/conda/conda/blob/b4592e9eb0/conda/cli/install.py#L417-L429 + if not getattr(exc, "allow_retry", True): + raise + unlink_link_transaction = solver.solve_for_transaction( + prune=getattr(args, "prune", False), update_modifier=NULL + ) + # Execute the transaction and return success + if unlink_link_transaction.nothing_to_do: + return None + + unlink_link_transaction.download_and_extract() + unlink_link_transaction.execute() + return unlink_link_transaction._make_legacy_action_groups()[0] diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/installers/pip.py b/miniconda3/lib/python3.13/site-packages/conda/env/installers/pip.py new file mode 100644 index 0000000000000000000000000000000000000000..85ff3c35d81fb91cbb52ad3f5c72e1ae4d392ae8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/installers/pip.py @@ -0,0 +1,72 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Pip-flavored installer.""" + +import os +import os.path as op +from logging import getLogger + +from ...auxlib.compat import Utf8NamedTemporaryFile +from ...env.pip_util import get_pip_installed_packages, pip_subprocess +from ...gateways.connection.session import CONDA_SESSION_SCHEMES +from ...reporters import get_spinner + +log = getLogger(__name__) + + +def _pip_install_via_requirements(prefix, specs, args, *_, **kwargs): + """ + Installs the pip dependencies in specs using a temporary pip requirements file. + + Args + ---- + prefix: string + The path to the python and pip executables. + + specs: iterable of strings + Each element should be a valid pip dependency. + See: https://pip.pypa.io/en/stable/user_guide/#requirements-files + https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format + """ + url_scheme = args.file.split("://", 1)[0] + if url_scheme in CONDA_SESSION_SCHEMES: + pip_workdir = None + else: + try: + pip_workdir = op.dirname(op.abspath(args.file)) + if not os.access(pip_workdir, os.W_OK): + pip_workdir = None + except AttributeError: + pip_workdir = None + requirements = None + try: + # Generate the temporary requirements file + requirements = Utf8NamedTemporaryFile( + mode="w", + prefix="condaenv.", + suffix=".requirements.txt", + dir=pip_workdir, + delete=False, + ) + requirements.write("\n".join(specs)) + requirements.close() + # pip command line... + # see https://pip.pypa.io/en/stable/cli/pip/#exists-action-option + pip_cmd = ["install", "-U", "-r", requirements.name, "--exists-action=b"] + stdout, stderr = pip_subprocess(pip_cmd, prefix, cwd=pip_workdir) + finally: + # Win/Appveyor does not like it if we use context manager + delete=True. + # So we delete the temporary file in a finally block. + if requirements is not None and op.isfile(requirements.name): + if "CONDA_TEST_SAVE_TEMPS" not in os.environ: + os.remove(requirements.name) + else: + log.warning( + f"CONDA_TEST_SAVE_TEMPS :: retaining pip requirements.txt {requirements.name}" + ) + return get_pip_installed_packages(stdout) + + +def install(*args, **kwargs): + with get_spinner("Installing pip dependencies"): + return _pip_install_via_requirements(*args, **kwargs) diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/pip_util.py b/miniconda3/lib/python3.13/site-packages/conda/env/pip_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef5ed2ac03215747daee3c3765c5c658a533753 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/pip_util.py @@ -0,0 +1,49 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Functions related to core conda functionality that relates to pip + +NOTE: This modules used to in conda, as conda/pip.py +""" + +import os +import re +import sys +from logging import getLogger + +from ..base.context import context +from ..common.compat import on_win +from ..exceptions import CondaEnvException +from ..gateways.subprocess import any_subprocess + +log = getLogger(__name__) + + +def pip_subprocess(args, prefix, cwd): + """Run pip in a subprocess""" + if on_win: + python_path = os.path.join(prefix, "python.exe") + else: + python_path = os.path.join(prefix, "bin", "python") + run_args = [python_path, "-m", "pip"] + args + stdout, stderr, rc = any_subprocess(run_args, prefix, cwd=cwd) + if not context.quiet and not context.json: + print("Ran pip subprocess with arguments:") + print(run_args) + print("Pip subprocess output:") + print(stdout) + if rc != 0: + print("Pip subprocess error:", file=sys.stderr) + print(stderr, file=sys.stderr) + raise CondaEnvException("Pip failed") + + return stdout, stderr + + +def get_pip_installed_packages(stdout): + """Return the list of pip packages installed based on the command output""" + m = re.search(r"Successfully installed\ (.*)", stdout) + if m: + return m.group(1).strip().split() + else: + return None diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/specs/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/env/specs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef805e178e5cb72b78ed96f02e0321d5d5bd7a0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/specs/__init__.py @@ -0,0 +1,80 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +from ...base.context import context +from ...deprecations import deprecated +from ...exceptions import ( + EnvironmentFileExtensionNotValid, + EnvironmentFileNotFound, + EnvironmentSpecPluginNotDetected, + SpecNotFound, +) +from ...gateways.connection.session import CONDA_SESSION_SCHEMES + +if TYPE_CHECKING: + from .requirements import RequirementsSpec + from .yaml_file import YamlFileSpec + + FileSpecTypes = type[YamlFileSpec] | type[RequirementsSpec] + SpecTypes = YamlFileSpec | RequirementsSpec + + +@deprecated( + "25.9", + "26.3", + addendum="Use conda.base.context.plugin_manager.detect_environment_specifier.", +) +def get_spec_class_from_file(filename: str) -> FileSpecTypes: + """ + Determine spec class to use from the provided ``filename`` + + :raises EnvironmentFileExtensionNotValid | EnvironmentFileNotFound: + """ + from .requirements import RequirementsSpec + from .yaml_file import YamlFileSpec + + if filename.startswith("file://"): + filename = filename[len("file://") :] + + # Check extensions + all_valid_exts = {*YamlFileSpec.extensions, *RequirementsSpec.extensions} + _, ext = os.path.splitext(filename) + + # First check if file exists and test the known valid extension for specs + file_exists = ( + os.path.isfile(filename) or filename.split("://", 1)[0] in CONDA_SESSION_SCHEMES + ) + if file_exists: + if ext == "" or ext not in all_valid_exts: + raise EnvironmentFileExtensionNotValid(filename) + elif ext in YamlFileSpec.extensions: + return YamlFileSpec + elif ext in RequirementsSpec.extensions: + return RequirementsSpec + raise EnvironmentFileNotFound(filename=filename) + + +@deprecated.argument("25.9", "26.3", "name") +@deprecated.argument( + "25.9", "26.3", "directory", addendum="Specify the full path in filename" +) +def detect( + filename: str | None = None, +) -> SpecTypes: + """ + Return the appropriate spec type to use. + + :raises SpecNotFound: Raised if no suitable spec class could be found given the input + """ + try: + spec_hook = context.plugin_manager.detect_environment_specifier( + source=filename, + ) + except EnvironmentSpecPluginNotDetected as e: + raise SpecNotFound(e.message) + + return spec_hook.environment_spec(filename) diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/specs/binstar.py b/miniconda3/lib/python3.13/site-packages/conda/env/specs/binstar.py new file mode 100644 index 0000000000000000000000000000000000000000..398e00f7df93b20a891f173b0c6b241f12d85399 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/specs/binstar.py @@ -0,0 +1,9 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Define binstar spec.""" + +from ...deprecations import deprecated + +deprecated.module("24.7", "26.3") + +deprecated.constant("24.7", "26.3", "ENVIRONMENT_TYPE", "env") diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/specs/cep_24.py b/miniconda3/lib/python3.13/site-packages/conda/env/specs/cep_24.py new file mode 100644 index 0000000000000000000000000000000000000000..cab0f7199f0a7c4b37c6dc4fa6afe6e55a7e5722 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/specs/cep_24.py @@ -0,0 +1,65 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Define cep-0024 compliant YAML spec.""" + +from __future__ import annotations + +import os +from logging import getLogger +from typing import TYPE_CHECKING + +from ...common.serialize import yaml +from ...exceptions import CondaError +from ...plugins.types import EnvironmentSpecBase +from .. import env + +if TYPE_CHECKING: + from ...models.environment import Environment + + +log = getLogger(__name__) + + +class Cep24YamlFileSpec(EnvironmentSpecBase): + _environment = None + extensions = {".yaml", ".yml"} + + def __init__(self, filename: str | None = None, **kwargs): + self.filename = filename + + def can_handle(self): + """ + Validates loader can process environment definition. + This can handle if: + * the provided file exists + * the provided file ends in the supported file extensions (.yaml or .yml) + * the provided file is compliant with the CEP-0024 + + :return: True or False + """ + if not self.filename: + return False + + # Extract the file extension (e.g., '.txt' or '' if no extension) + _, file_ext = os.path.splitext(self.filename) + + # Check if the file has a supported extension and exists + if file_ext.lower() not in self.extensions: + return False + + try: + yamlstr = env.load_file(self.filename) + data = yaml.loads(yamlstr) + errors = env.get_schema_errors(data) + if errors: + return False + return True + except CondaError: + log.debug("Failed to load %s as a YAML.", self.filename, exc_info=True) + return False + + @property + def env(self) -> Environment: + if not self._environment: + self._environment = env.from_file(self.filename) + return self._environment.to_environment_model() diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/specs/explicit.py b/miniconda3/lib/python3.13/site-packages/conda/env/specs/explicit.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5f4925ddb557535b6c8da5100705bccee99a74 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/specs/explicit.py @@ -0,0 +1,68 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Define explicit spec.""" + +from __future__ import annotations + +from ...base.constants import EXPLICIT_MARKER +from ...base.context import context +from ...exceptions import CondaValueError +from ...gateways.disk.read import yield_lines +from ...misc import get_package_records_from_explicit +from ...models.environment import Environment +from ...plugins.types import EnvironmentSpecBase + + +class ExplicitSpec(EnvironmentSpecBase): + """ + The ExplicitSpec class handles explicit environment files. These are ones + which are marked with the @EXPLICIT marker. + """ + + def __init__(self, filename: str | None = None, **kwargs) -> None: + """Initialize the explicit specification. + + :param filename: Path to the requirements file + :param kwargs: Additional arguments + """ + self.filename = filename + + def can_handle(self) -> bool: + """ + Validates that this spec can process the environment definition. + This checks if: + * a filename was provided + * the file has the "@EXPLICIT" marker + + :return: True if the file can be handled, False otherwise + """ + # Return early if no filename was provided + if self.filename is None: + return False + + # Ensure the file has the "@EXPLICIT" marker + dependencies_list = list(yield_lines(self.filename)) + if EXPLICIT_MARKER in dependencies_list: + return True + else: + return False + + @property + def env(self) -> Environment: + """ + Build an environment from the explicit file. + + :return: An Environment object containing the package specifications + :raises ValueError: If the file cannot be read + """ + if not self.filename: + raise CondaValueError("No filename provided") + + # Convert generator to list since Dependencies needs to access it multiple times + dependencies_list = list(yield_lines(self.filename)) + explicit_packages = get_package_records_from_explicit(dependencies_list) + + return Environment( + platform=context.subdir, + explicit_packages=explicit_packages, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/specs/requirements.py b/miniconda3/lib/python3.13/site-packages/conda/env/specs/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..fd39e94116c226821083605ab6c64e6322ff2ea9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/specs/requirements.py @@ -0,0 +1,148 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Define requirements.txt spec.""" + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import ClassVar + +from ...base.context import context +from ...deprecations import deprecated +from ...exceptions import CondaValueError +from ...gateways.disk.read import yield_lines +from ...models.environment import Environment +from ...models.match_spec import MatchSpec +from ...plugins.types import EnvironmentSpecBase +from ..env import EnvironmentYaml + + +class RequirementsSpec(EnvironmentSpecBase): + """ + Reads dependencies from requirements files (including explicit files) + and returns an Environment object from it. + """ + + msg: str | None = None + extensions: ClassVar[set[str]] = {".txt"} + + @deprecated.argument("24.7", "26.3", "name") + def __init__( + self, filename: str | None = None, name: str | None = None, **kwargs + ) -> None: + """Initialize the requirements specification. + + :param filename: Path to the requirements file + :param name: (Deprecated) Name of the environment + :param kwargs: Additional arguments + """ + self.filename = filename + self._name = name + + @property + @deprecated("25.9", "26.3", addendum="This attribute is not used anymore.") + def name(self): # type: ignore[misc] + return self._name + + @name.setter # type: ignore[misc] + @deprecated("25.9", "26.3", addendum="This attribute is not used anymore.") + def name(self, value): # type: ignore[misc] + self._name = value + + @deprecated("25.9", "26.3", addendum="This method is not used anymore.") + def _valid_file(self) -> bool: + """Check if the file exists. + + :return: True if the file exists, False otherwise + """ + if self.filename and os.path.exists(self.filename): + return True + else: + self.msg = "There is no requirements.txt" + return False + + @deprecated("25.9", "26.3", addendum="This method is not used anymore.") + def _valid_name(self) -> bool: + """Check if the name is valid. + + :return: True if the name is valid, False otherwise + """ + if self.name is None: + self.msg = "The environment does not have a name" + return False + else: + return True + + def can_handle(self) -> bool: + """ + Validates that this spec can process the environment definition. + This checks if: + * a filename was provided + * the file has a supported extension + * the file exists + * the file content is valid for this specifier type + + :return: True if the file can be handled, False otherwise + """ + # Return early if no filename was provided + if self.filename is None: + return False + + # Extract the file extension (e.g., '.txt' or '' if no extension) + _, file_ext = os.path.splitext(self.filename) + + # Check if the file has a supported extension + if not any(spec_ext == file_ext for spec_ext in self.extensions): + self.msg = f"File {self.filename} does not have a supported extension: {', '.join(self.extensions)}" + return False + + # Ensure this is not an explicit file. Requirements.txt and explicit files + # may sometimes share file extension. + dependencies_list = list(yield_lines(self.filename)) + if "@EXPLICIT" in dependencies_list: + return False + return True + + @property + @deprecated("26.3", "26.9", addendum="This method is not used anymore, use 'env'") + def environment(self) -> EnvironmentYaml: + """ + Build an environment from the requirements file. + + This method reads the file as a generator and passes it directly to EnvironmentYaml. + + :return: An Environment object containing the package specifications + :raises ValueError: If the file cannot be read + """ + if not self.filename: + raise CondaValueError("No filename provided") + + # Convert generator to list since Dependencies needs to access it multiple times + dependencies_list = list(yield_lines(self.filename)) + return EnvironmentYaml( + dependencies=dependencies_list, + filename=self.filename, + ) + + @property + def env(self) -> Environment: + """ + Build an environment from the requirements file. + + :return: An Environment object containing the package specifications + :raises ValueError: If the file cannot be read + """ + if not self.filename: + raise ValueError("No filename provided") + + # Convert generator to list since Dependencies needs to access it multiple times + dependencies_list = list(yield_lines(self.filename)) + requested_packages = [MatchSpec(dep) for dep in dependencies_list] + + return Environment( + platform=context.subdir, + requested_packages=requested_packages, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/env/specs/yaml_file.py b/miniconda3/lib/python3.13/site-packages/conda/env/specs/yaml_file.py new file mode 100644 index 0000000000000000000000000000000000000000..befe3ee00e94ebc25152bd65c5dce0ee81b20851 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/env/specs/yaml_file.py @@ -0,0 +1,86 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Define YAML spec.""" + +from __future__ import annotations + +import os +from logging import getLogger +from typing import TYPE_CHECKING + +from ...common.serialize import yaml +from ...deprecations import deprecated +from ...exceptions import CondaValueError +from ...plugins.types import EnvironmentSpecBase +from .. import env + +if TYPE_CHECKING: + from ...models.environment import Environment + from ..env import EnvironmentYaml + + +log = getLogger(__name__) + + +class YamlFileSpec(EnvironmentSpecBase): + # Do not use this plugin for in the environment spec detection process. + # Users must specify using `environment.yaml` with the `--environment-specifier` + # option. + detection_supported = False + + _environment = None + + extensions = {".yaml", ".yml"} + + def __init__(self, filename=None, **kwargs): + self.filename = filename + self.msg = None + + def can_handle(self): + """ + Validates loader can process environment definition. + This can handle if: + * the provided file exists + * the provided file ends in the supported file extensions (.yaml or .yml) + * the yaml file can be loaded and is not empty + + :return: True or False + """ + if not self.filename: + return False + + # Extract the file extension (e.g., '.txt' or '' if no extension) + _, file_ext = os.path.splitext(self.filename) + + # Check if the file has a supported extension and exists + if not any(spec_ext == file_ext for spec_ext in YamlFileSpec.extensions): + return False + + try: + yamlstr = env.load_file(self.filename) + data = yaml.loads(yamlstr) + if data is None: + return False + except Exception: + log.debug("Failed to load %s as a YAML.", self.filename, exc_info=True) + return False + + return True + + @property + @deprecated("26.3", "26.9", addendum="This method is not used anymore, use 'env'") + def environment(self) -> EnvironmentYaml: + if not self._environment: + if not self.can_handle(): + raise CondaValueError(f"Cannot handle environment file: {self.msg}") + self._environment = env.from_file(self.filename) + + if self._environment is None: + raise CondaValueError("Environment could not be loaded") + return self._environment + + @property + def env(self) -> Environment: + if not self._environment: + self._environment = env.from_file(self.filename) + return self._environment.to_environment_model() diff --git a/miniconda3/lib/python3.13/site-packages/conda/exception_handler.py b/miniconda3/lib/python3.13/site-packages/conda/exception_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..a389777d3a9be4c9a71ac4a63d27f1f02adb2507 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/exception_handler.py @@ -0,0 +1,430 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Error handling and error reporting.""" + +from __future__ import annotations + +import os +import sys +from functools import cached_property, partial +from logging import getLogger +from typing import TYPE_CHECKING + +from .common.compat import ensure_text_type, on_win +from .deprecations import deprecated + +if TYPE_CHECKING: + from collections.abc import Callable + from types import TracebackType + from typing import Any, TypeVar + + T = TypeVar("T") + +log = getLogger(__name__) + + +class ExceptionHandler: + # FUTURE: Python 3.10+, use typing.ParamSpec + def __call__(self, func: Callable[..., T], *args, **kwargs) -> T | int: + try: + return func(*args, **kwargs) + except: + _, exc_val, exc_tb = sys.exc_info() + return self.handle_exception(exc_val, exc_tb) + + def write_out(self, *content: str) -> None: + from logging import getLogger + + from .cli.main import init_loggers + + init_loggers() + getLogger("conda.stderr").info("\n".join(content)) + + @property + def http_timeout(self): + from .base.context import context + + return context.remote_connect_timeout_secs, context.remote_read_timeout_secs + + @property + def user_agent(self): + from .base.context import context + + return context.user_agent + + @property + @deprecated( + "26.9", + "27.3", + ) + def error_upload_url(self): + from .base.context import context + + return context.error_upload_url + + def handle_exception(self, exc_val: BaseException, exc_tb: TracebackType) -> int: + from errno import ENOSPC + + from .exceptions import ( + CondaError, + CondaMemoryError, + NoSpaceLeftError, + ) + + if isinstance(exc_val, CondaError): + if exc_val.reportable: + return self.handle_reportable_application_exception(exc_val, exc_tb) + else: + return self.handle_application_exception(exc_val, exc_tb) + if isinstance(exc_val, EnvironmentError): + if getattr(exc_val, "errno", None) == ENOSPC: + return self.handle_application_exception( + NoSpaceLeftError(exc_val), exc_tb + ) + if isinstance(exc_val, MemoryError): + return self.handle_application_exception(CondaMemoryError(exc_val), exc_tb) + if isinstance(exc_val, KeyboardInterrupt): + self._print_conda_exception(CondaError("KeyboardInterrupt"), exc_tb) + return 1 + if isinstance(exc_val, SystemExit): + return exc_val.code + return self.handle_unexpected_exception(exc_val, exc_tb) + + def handle_application_exception( + self, exc_val: BaseException, exc_tb: TracebackType + ) -> int: + self._print_conda_exception(exc_val, exc_tb) + return exc_val.return_code + + def _print_conda_exception( + self, + exc_val: BaseException, + exc_tb: TracebackType, + ) -> None: + from .exceptions import print_conda_exception + + print_conda_exception(exc_val, exc_tb) + + def handle_unexpected_exception( + self, exc_val: BaseException, exc_tb: TracebackType + ) -> int: + error_report = self.get_error_report(exc_val, exc_tb) + self.print_unexpected_error_report(error_report) + rc = getattr(exc_val, "return_code", None) + return rc if rc is not None else 1 + + def handle_reportable_application_exception( + self, exc_val: BaseException, exc_tb: TracebackType + ) -> int: + error_report = self.get_error_report(exc_val, exc_tb) + from .base.context import context + + if context.json: + error_report.update(exc_val.dump_map()) + self.print_expected_error_report(error_report) + return exc_val.return_code + + def get_error_report( + self, + exc_val: BaseException, + exc_tb: TracebackType, + ) -> dict[str, str]: + from .exceptions import CondaError, _format_exc + + command = " ".join(ensure_text_type(s) for s in sys.argv) + info_dict = {} + if " info" not in command: + # get info_dict, but if we get an exception here too, record it without trampling + # the original exception + try: + from .cli.main_info import get_info_dict + + info_dict = get_info_dict() + except Exception as info_e: + info_traceback = _format_exc() + info_dict = { + "error": repr(info_e), + "exception_name": info_e.__class__.__name__, + "exception_type": str(exc_val.__class__), + "traceback": info_traceback, + } + + error_report = { + "error": repr(exc_val), + "exception_name": exc_val.__class__.__name__, + "exception_type": str(exc_val.__class__), + "command": command, + "traceback": _format_exc(exc_val, exc_tb), + "conda_info": info_dict, + } + + if isinstance(exc_val, CondaError): + error_report["conda_error_components"] = exc_val.dump_map() + + return error_report + + def print_unexpected_error_report(self, error_report: dict[str, str]) -> None: + from .base.context import context + + if context.json: + from .cli.common import stdout_json + + stdout_json(error_report) + else: + message_builder = [] + message_builder.append("") + message_builder.append( + "# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<" + ) + message_builder.append("") + message_builder.extend( + " " + line for line in error_report["traceback"].splitlines() + ) + message_builder.append("") + message_builder.append("`$ {}`".format(error_report["command"])) + message_builder.append("") + if error_report["conda_info"]: + from .cli.main_info import get_env_vars_str, get_main_info_str + + try: + # TODO: Sanitize env vars to remove secrets (e.g credentials for PROXY) + message_builder.append(get_env_vars_str(error_report["conda_info"])) + message_builder.append( + get_main_info_str(error_report["conda_info"]) + ) + except Exception as e: + log.warning("%r", e, exc_info=True) + message_builder.append("conda info could not be constructed.") + message_builder.append(f"{e!r}") + message_builder.extend( + [ + "", + "An unexpected error has occurred. Conda has prepared the above report." + "", + "If you suspect this error is being caused by a malfunctioning plugin,", + "consider using the --no-plugins option to turn off plugins.", + "", + "Example: conda --no-plugins install ", + "", + "Alternatively, you can set the CONDA_NO_PLUGINS environment variable on", + "the command line to run the command without plugins enabled.", + "", + "Example: CONDA_NO_PLUGINS=true conda install ", + "", + ] + ) + self.write_out(*message_builder) + + def print_expected_error_report(self, error_report: dict[str, str]) -> None: + from .base.context import context + + if context.json: + from .cli.common import stdout_json + + stdout_json(error_report) + else: + message_builder = [] + message_builder.append("") + message_builder.append( + "# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<" + ) + message_builder.append("") + message_builder.append("`$ {}`".format(error_report["command"])) + message_builder.append("") + if error_report["conda_info"]: + from .cli.main_info import get_env_vars_str, get_main_info_str + + try: + # TODO: Sanitize env vars to remove secrets (e.g credentials for PROXY) + message_builder.append(get_env_vars_str(error_report["conda_info"])) + message_builder.append( + get_main_info_str(error_report["conda_info"]) + ) + except Exception as e: + log.warning("%r", e, exc_info=True) + message_builder.append("conda info could not be constructed.") + message_builder.append(f"{e!r}") + message_builder.append("") + message_builder.append( + "V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V V" + ) + message_builder.append("") + + message_builder.extend(error_report["error"].splitlines()) + message_builder.append("") + + message_builder.append( + "A reportable application error has occurred. Conda has prepared the above report." + ) + message_builder.append("") + self.write_out(*message_builder) + + @cached_property + def _isatty(self) -> bool: + try: + return os.isatty(0) or on_win + except Exception as e: + log.debug("%r", e) + return True + + @deprecated( + "26.9", + "27.3", + ) + def _upload(self, error_report: dict[str, str]) -> None: + """Determine whether or not to upload the error report.""" + from .base.context import context + + post_upload = False + if context.report_errors is False: + # no prompt and no submission + do_upload = False + elif context.report_errors is True or context.always_yes: + # no prompt and submit + do_upload = True + elif context.json or context.quiet or not self._isatty: + # never prompt under these conditions, submit iff always_yes + do_upload = bool(not context.offline and context.always_yes) + else: + # prompt whether to submit + do_upload = self._ask_upload() + post_upload = True + + # the upload state is one of the following: + # - True: upload error report + # - False: do not upload error report + # - None: while prompting a timeout occurred + + if do_upload: + # user wants report to be submitted + self._execute_upload(error_report) + + if post_upload: + # post submission text + self._post_upload(do_upload) + + @deprecated( + "26.9", + "27.3", + ) + def _ask_upload(self) -> bool: + from .auxlib.type_coercion import boolify + from .common.io import timeout + + try: + do_upload = timeout( + 40, + partial( + input, + "If submitted, this report will be used by core maintainers to improve\n" + "future releases of conda.\n" + "Would you like conda to send this report to the core maintainers? " + "[y/N]: ", + ), + ) + return do_upload and boolify(do_upload) + except Exception as e: + log.debug("%r", e) + return False + + @deprecated( + "26.9", + "27.3", + ) + def _execute_upload(self, error_report: dict[str, Any]) -> None: + import getpass + + from .common.serialize import json + + headers = { + "User-Agent": self.user_agent, + } + _timeout = self.http_timeout + username = getpass.getuser() + error_report["is_ascii"] = ( + True if all(ord(c) < 128 for c in username) else False + ) + error_report["has_spaces"] = True if " " in str(username) else False + data = json.dumps(error_report, sort_keys=True) + "\n" + data = data.replace(str(username), "USERNAME_REMOVED") + response = None + try: + # requests does not follow HTTP standards for redirects of non-GET methods + # That is, when following a 301 or 302, it turns a POST into a GET. + # And no way to disable. WTF + import requests + + redirect_counter = 0 + url = self.error_upload_url + response = requests.post( + url, headers=headers, timeout=_timeout, data=data, allow_redirects=False + ) + response.raise_for_status() + while response.status_code in (301, 302) and response.headers.get( + "Location" + ): + url = response.headers["Location"] + response = requests.post( + url, + headers=headers, + timeout=_timeout, + data=data, + allow_redirects=False, + ) + response.raise_for_status() + redirect_counter += 1 + if redirect_counter > 15: + from . import CondaError + + raise CondaError("Redirect limit exceeded") + log.debug("upload response status: %s", response and response.status_code) + except Exception as e: # pragma: no cover + log.info("%r", e) + try: + if response and response.ok: + self.write_out("Upload successful.") + else: + self.write_out("Upload did not complete.") + if response and response.status_code: + self.write_out(f" HTTP {response.status_code}") + except Exception as e: + log.debug(f"{e!r}") + + @deprecated( + "26.9", + "27.3", + ) + def _post_upload(self, do_upload: bool) -> None: + if do_upload is True: + # report was submitted + self.write_out( + "", + "Thank you for helping to improve conda.", + "Opt-in to always sending reports (and not see this message again)", + "by running", + "", + " $ conda config --set report_errors true", + "", + ) + elif do_upload is None: + # timeout was reached while prompting user + self.write_out( + "", + "Timeout reached. No report sent.", + "", + ) + else: + # no report submitted + self.write_out( + "", + "No report sent. To permanently opt-out, use", + "", + " $ conda config --set report_errors false", + "", + ) + + +def conda_exception_handler(func: Callable[..., T], *args, **kwargs) -> T | int: + exception_handler = ExceptionHandler() + return_value = exception_handler(func, *args, **kwargs) + return return_value diff --git a/miniconda3/lib/python3.13/site-packages/conda/exceptions.py b/miniconda3/lib/python3.13/site-packages/conda/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..eb883664e1506219696506a0c6ad46cf150185d7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/exceptions.py @@ -0,0 +1,1505 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda exceptions.""" + +from __future__ import annotations + +import os +import sys +from collections import defaultdict +from datetime import timedelta +from logging import getLogger +from os.path import join +from textwrap import dedent, indent +from traceback import format_exception, format_exception_only +from typing import TYPE_CHECKING + +from . import CondaError, CondaExitZero, CondaMultiError +from .auxlib.ish import dals +from .auxlib.logz import stringify +from .base.constants import ( + COMPATIBLE_SHELLS, + PREFIX_PINNED_FILE, + PathConflict, + SafetyChecks, +) +from .common.compat import on_win +from .common.io import dashlist +from .common.iterators import groupby_to_dict as groupby +from .common.serialize.json import JSONDecodeError +from .common.serialize.json import dumps as json_dumps +from .common.signals import get_signal_name +from .common.url import join_url, maybe_unquote +from .deprecations import DeprecatedError # noqa: F401 +from .exception_handler import ExceptionHandler, conda_exception_handler # noqa: F401 +from .models.channel import Channel + +if TYPE_CHECKING: + from collections.abc import Iterable + from types import TracebackType + from typing import Any + + import requests + + from conda.base.context import Context + from conda.common.path import PathType + from conda.models.match_spec import MatchSpec + from conda.models.records import PackageRecord + from conda.plugins.types import CondaEnvironmentExporter + +log = getLogger(__name__) + + +# TODO: for conda-build compatibility only +# remove in conda 4.4 +class ResolvePackageNotFound(CondaError): + def __init__(self, bad_deps: Iterable[Iterable[MatchSpec]]): + # bad_deps is a list of lists + # bad_deps should really be named 'invalid_chains' + self.bad_deps = tuple(dep for deps in bad_deps for dep in deps if dep) + formatted_chains = tuple( + " -> ".join(map(str, bad_chain)) for bad_chain in bad_deps + ) + self._formatted_chains = formatted_chains + message = "\n" + "\n".join( + (f" - {bad_chain}") for bad_chain in formatted_chains + ) + super().__init__(message) + + +NoPackagesFound = NoPackagesFoundError = ResolvePackageNotFound + + +class LockError(CondaError, OSError): + def __init__(self, message: str): + msg = str(message) + super().__init__(msg) + + +class ArgumentError(CondaError): + return_code = 2 + + def __init__(self, message: str, **kwargs): + super().__init__(message, **kwargs) + + +class Help(CondaError): + pass + + +class ActivateHelp(Help): + def __init__(self): + message = dals( + """ + usage: conda activate [-h] [--[no-]stack] [env_name_or_prefix] + + Activate a conda environment. + + Options: + + positional arguments: + env_name_or_prefix The environment name or prefix to activate. If the + prefix is a relative path, it must start with './' + (or '.\\' on Windows). + + optional arguments: + -h, --help Show this help message and exit. + --stack Stack the environment being activated on top of the + previous active environment, rather replacing the + current active environment with a new one. Currently, + only the PATH environment variable is stacked. This + may be enabled implicitly by the 'auto_stack' + configuration variable. + --no-stack Do not stack the environment. Overrides 'auto_stack' + setting. + """ + ) + super().__init__(message) + + +class DeactivateHelp(Help): + def __init__(self): + message = dals( + """ + usage: conda deactivate [-h] + + Deactivate the current active conda environment. + + Options: + + optional arguments: + -h, --help Show this help message and exit. + """ + ) + super().__init__(message) + + +class GenericHelp(Help): + def __init__(self, command: str): + message = f"help requested for {command}" + super().__init__(message) + + +class CondaSignalInterrupt(CondaError): + def __init__(self, signum: int): + signal_name = get_signal_name(signum) + super().__init__( + "Signal interrupt %(signal_name)s", signal_name=signal_name, signum=signum + ) + + +class TooManyArgumentsError(ArgumentError): + def __init__( + self, + expected: int, + received: int, + offending_arguments: Iterable[str], + optional_message: str = "", + *args, + ): + self.expected = expected + self.received = received + self.offending_arguments = offending_arguments + self.optional_message = optional_message + + suffix = "s" if received - expected > 1 else "" + msg = "{} Got {} argument{} ({}) but expected {}.".format( + optional_message, + received, + suffix, + ", ".join(offending_arguments), + expected, + ) + super().__init__(msg, *args) + + +class ClobberError(CondaError): + def __init__(self, message: str, path_conflict: PathConflict, **kwargs): + self.path_conflict = path_conflict + super().__init__(message, **kwargs) + + def __repr__(self): + clz_name = ( + "ClobberWarning" + if self.path_conflict == PathConflict.warn + else "ClobberError" + ) + return f"{clz_name}: {self}\n" + + +class BasicClobberError(ClobberError): + def __init__(self, source_path: PathType, target_path: PathType, context: Context): + message = dals( + """ + Conda was asked to clobber an existing path. + source path: %(source_path)s + target path: %(target_path)s + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "Conda no longer clobbers existing paths without the use of the " + "--clobber option\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + source_path=source_path, + ) + + +class KnownPackageClobberError(ClobberError): + def __init__( + self, + target_path: PathType, + colliding_dist_being_linked: PackageRecord | str, + colliding_linked_dist: PackageRecord | str, + context: Context, + ): + message = dals( + """ + The package '%(colliding_dist_being_linked)s' cannot be installed due to a + path collision for '%(target_path)s'. + This path already exists in the target prefix, and it won't be removed by + an uninstall action in this transaction. The path appears to be coming from + the package '%(colliding_linked_dist)s', which is already installed in the prefix. + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "If you'd like to proceed anyway, re-run the command with " + "the `--clobber` flag.\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + colliding_dist_being_linked=colliding_dist_being_linked, + colliding_linked_dist=colliding_linked_dist, + ) + + +class UnknownPackageClobberError(ClobberError): + def __init__( + self, + target_path: PathType, + colliding_dist_being_linked: PackageRecord | str, + context: Context, + ): + message = dals( + """ + The package '%(colliding_dist_being_linked)s' cannot be installed due to a + path collision for '%(target_path)s'. + This path already exists in the target prefix, and it won't be removed + by an uninstall action in this transaction. The path is one that conda + doesn't recognize. It may have been created by another package manager. + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "If you'd like to proceed anyway, re-run the command with " + "the `--clobber` flag.\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + colliding_dist_being_linked=colliding_dist_being_linked, + ) + + +class SharedLinkPathClobberError(ClobberError): + def __init__( + self, + target_path: PathType, + incompatible_package_dists: Iterable[PackageRecord | str], + context: Context, + ): + message = dals( + """ + This transaction has incompatible packages due to a shared path. + packages: %(incompatible_packages)s + path: '%(target_path)s' + """ + ) + if context.path_conflict == PathConflict.prevent: + message += ( + "If you'd like to proceed anyway, re-run the command with " + "the `--clobber` flag.\n." + ) + super().__init__( + message, + context.path_conflict, + target_path=target_path, + incompatible_packages=", ".join(str(d) for d in incompatible_package_dists), + ) + + +class CommandNotFoundError(CondaError): + def __init__(self, command: str): + activate_commands = { + "activate", + "deactivate", + "run", + } + conda_commands = { + "clean", + "config", + "create", + "--help", # https://github.com/conda/conda/issues/11585 + "info", + "install", + "list", + "package", + "remove", + "search", + "uninstall", + "update", + "upgrade", + } + build_commands = { + "build", + "convert", + "develop", + "index", + "inspect", + "metapackage", + "render", + "skeleton", + } + from .cli.main import init_loggers + + init_loggers() + if command in activate_commands: + # TODO: Point users to a page at conda-docs, which explains this context in more detail + builder = [ + "Your shell has not been properly configured to use 'conda %(command)s'." + ] + if on_win: + builder.append( + dals( + """ + If using 'conda %(command)s' from a batch script, change your + invocation to 'CALL conda.bat %(command)s'. + """ + ) + ) + builder.append( + dals( + """ + To initialize your shell, run + + $ conda init + + Currently supported shells are:%(supported_shells)s + + See 'conda init --help' for more information and options. + + IMPORTANT: You may need to close and restart your shell after running 'conda init'. + """ + ) + % { + "supported_shells": dashlist(COMPATIBLE_SHELLS), + } + ) + message = "\n".join(builder) + elif command in build_commands: + message = "To use 'conda %(command)s', install conda-build." + else: + from difflib import get_close_matches + + from .cli.find_commands import find_commands + + message = "No command 'conda %(command)s'." + choices = ( + activate_commands + | conda_commands + | build_commands + | set(find_commands()) + ) + close = get_close_matches(command, choices) + if close: + message += f"\nDid you mean 'conda {close[0]}'?" + super().__init__(message, command=command) + + +class PathNotFoundError(CondaError, OSError): + def __init__(self, path: PathType): + message = "%(path)s" + super().__init__(message, path=path) + + +class DirectoryNotFoundError(CondaError): + def __init__(self, path: PathType): + message = "%(path)s" + super().__init__(message, path=path) + + +class EnvironmentLocationNotFound(CondaError): + def __init__(self, location: PathType): + message = "Not a conda environment: %(location)s" + super().__init__(message, location=location) + + +class EnvironmentNameNotFound(CondaError): + def __init__(self, environment_name: str): + message = dals( + """ + Could not find conda environment: %(environment_name)s + You can list all discoverable environments with `conda info --envs`. + """ + ) + super().__init__(message, environment_name=environment_name) + + +class NoBaseEnvironmentError(CondaError): + def __init__(self): + message = dals( + """ + This conda installation has no default base environment. Use + 'conda create' to create new environments and 'conda activate' to + activate environments. + """ + ) + super().__init__(message) + + +class DirectoryNotACondaEnvironmentError(CondaError): + def __init__(self, target_directory: PathType): + message = dals( + """ + The target directory exists, but it is not a conda environment. + Use 'conda create' to convert the directory to a conda environment. + target directory: %(target_directory)s + """ + ) + super().__init__(message, target_directory=target_directory) + + +class CondaEnvironmentError(CondaError, EnvironmentError): + def __init__(self, message: str, *args): + msg = f"{message}" + super().__init__(msg, *args) + + +class DryRunExit(CondaExitZero): + def __init__(self): + msg = "Dry run. Exiting." + super().__init__(msg) + + +class CondaSystemExit(CondaExitZero, SystemExit): + def __init__(self, *args): + msg = " ".join(str(arg) for arg in self.args) + super().__init__(msg) + + +class PaddingError(CondaError): + def __init__(self, dist: str, placeholder: str, placeholder_length: int): + msg = ( + "Placeholder of length '%d' too short in package %s.\n" + "The package must be rebuilt with conda-build > 2.0." + % (placeholder_length, dist) + ) + super().__init__(msg) + + +class LinkError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class CondaOSError(CondaError, OSError): + def __init__(self, message: str, **kwargs): + msg = f"{message}" + super().__init__(msg, **kwargs) + + +class ProxyError(CondaError): + def __init__(self, message: str | None = None): + if message is None: + message = dals( + """ + Conda cannot proceed due to an error in your proxy configuration. + Check for typos and other configuration errors in any '.netrc' file in your home directory, + any environment variables ending in '_PROXY', and any other system-wide proxy + configuration settings. + """ + ) + super().__init__(message) + + +class CondaIOError(CondaError, IOError): + def __init__(self, message: str, *args): + msg = f"{message}" + super().__init__(msg) + + +class CondaFileIOError(CondaIOError): + def __init__(self, filepath: PathType, message: str, *args): + self.filepath = filepath + + msg = f"'{filepath}'. {message}" + super().__init__(msg, *args) + + +class CondaKeyError(CondaError, KeyError): + def __init__(self, key: Any, message: str, *args): + self.key = key + self.msg = f"{key!r}: {message}" + super().__init__(self.msg, *args) + + +class ChannelError(CondaError): + pass + + +class ChannelNotAllowed(ChannelError): + warning = "Channel not included in allowlist" + + def __init__(self, channel: Channel): + channel_name = channel.name + channel_url = maybe_unquote(channel.base_url) + message = dals( + """ + %(warning)s: + channel name: %(channel_name)s + channel url: %(channel_url)s + """ + ) + super().__init__( + message, + channel_url=channel_url, + channel_name=channel_name, + warning=self.warning, + ) + + +class ChannelDenied(ChannelNotAllowed): + warning = "Channel included in denylist" + + +class UnavailableInvalidChannel(ChannelError): + status_code: str | int + + def __init__( + self, + channel: Channel | str, + status_code: str | int, + response: requests.models.Response | None = None, + ): + # parse channel + channel = Channel(channel) + channel_name = channel.name + channel_url = maybe_unquote(channel.base_url) + + # define hardcoded/default reason/message + reason = getattr(response, "reason", None) + message = dals( + """ + The channel is not accessible or is invalid. + + You will need to adjust your conda configuration to proceed. + Use `conda config --show channels` to view your configuration's current state, + and use `conda config --show-sources` to view config file locations. + """ + ) + if channel.scheme == "file": + url = join_url(channel.location, channel.name) + message += dedent( + f""" + As of conda 4.3, a valid channel must contain a + `noarch/repodata.json` even if `noarch/repodata.json` is + empty. Use `conda index {url}`, or create `noarch/repodata.json` + """ + ) + + # if response includes a valid json body we prefer the reason/message defined there + try: + body = response.json() + except (AttributeError, JSONDecodeError): + body = {} + else: + reason = body.get("reason") or reason + message = body.get("message") or message + # if RFC 9457 'detail' is present, it is preferred over 'message' + # See https://datatracker.ietf.org/doc/html/rfc9457 + message = body.get("detail") or message + + # standardize arguments + status_code = status_code or "000" + reason = reason or "UNAVAILABLE OR INVALID" + + self.status_code = status_code + + super().__init__( + f"HTTP {status_code} {reason} for channel {channel_name} <{channel_url}>\n\n{message}", + channel_name=channel_name, + channel_url=channel_url, + status_code=status_code, + reason=reason, + response_details=stringify(response, content_max_len=1024) or "", + json=body, + ) + + +class OperationNotAllowed(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class CondaImportError(CondaError, ImportError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class ParseError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CouldntParseError(ParseError): + def __init__(self, reason: str): + self.reason = reason + super().__init__(self.args[0]) + + +class ChecksumMismatchError(CondaError): + def __init__( + self, + url: str, + target_full_path: PathType, + checksum_type: str, + expected_checksum: str, + actual_checksum: str, + partial_download: bool = False, + ): + message = dals( + """ + Conda detected a mismatch between the expected content and downloaded content + for url '%(url)s'. + download saved to: %(target_full_path)s + expected %(checksum_type)s: %(expected_checksum)s + actual %(checksum_type)s: %(actual_checksum)s + """ + ) + url = maybe_unquote(url) + super().__init__( + message, + url=url, + target_full_path=target_full_path, + checksum_type=checksum_type, + expected_checksum=expected_checksum, + actual_checksum=actual_checksum, + partial_download=partial_download, + ) + + +class PackageNotInstalledError(CondaError): + def __init__(self, prefix: PathType, package_name: str): + message = dals( + """ + Package is not installed in prefix. + prefix: %(prefix)s + package name: %(package_name)s + """ + ) + super().__init__(message, prefix=prefix, package_name=package_name) + + +class CondaHTTPError(CondaError): + def __init__( + self, + message: str, + url: str, + status_code: int | str, + reason: str, + elapsed_time: timedelta | str, + response: requests.Response | None = None, + caused_by: Any = None, + ): + # if response includes a valid json body we prefer the reason/message defined there + try: + body = response.json() + except (AttributeError, JSONDecodeError): + body = {} + else: + reason = body.get("reason") or reason + message = body.get("message") or message + # if RFC 9457 'detail' is present, it is preferred over 'message' + # See https://datatracker.ietf.org/doc/html/rfc9457 + message = body.get("detail") or message + + # standardize arguments + url = maybe_unquote(url) + status_code = status_code or "000" + reason = reason or "CONNECTION FAILED" + elapsed_time = elapsed_time or "-" + if isinstance(elapsed_time, timedelta): + elapsed_time = str(elapsed_time).split(":", 1)[-1] + + # extract CF-RAY + try: + cf_ray = response.headers["CF-RAY"] + except (AttributeError, KeyError): + cf_ray = "" + else: + cf_ray = f"CF-RAY: {cf_ray}\n" + + super().__init__( + dals( + f""" + HTTP {status_code} {reason} for url <{url}> + Elapsed: {elapsed_time} + {cf_ray} + """ + ) + # since message may include newlines don't include in f-string/dals above + + message, + url=url, + status_code=status_code, + reason=reason, + elapsed_time=elapsed_time, + response_details=stringify(response, content_max_len=1024) or "", + json=body, + caused_by=caused_by, + ) + + +class CondaSSLError(CondaError): + pass + + +class AuthenticationError(CondaError): + pass + + +class PackagesNotFoundError(CondaError): + def __init__( + self, + packages: Iterable[MatchSpec | PackageRecord | str], + channel_urls: Iterable[str] = (), + ): + if channel_urls: + message = dals( + """ + The following packages are not available from current channels: + %(packages_formatted)s + + Current channels: + %(channels_formatted)s + + To search for alternate channels that may provide the conda package you're + looking for, navigate to + + https://anaconda.org + + and use the search bar at the top of the page. + """ + ) + from .base.context import context + + if context.use_only_tar_bz2: + message += dals( + """ + Note: 'use_only_tar_bz2' is enabled. This might be omitting some + packages from the index. Set this option to 'false' and retry. + """ + ) + packages_formatted = dashlist(packages) + channels_formatted = dashlist(channel_urls) + else: + message = dals( + """ + The following packages are missing from the target environment: + %(packages_formatted)s + """ + ) + packages_formatted = dashlist(packages) + channels_formatted = "" + + super().__init__( + message, + packages=packages, + packages_formatted=packages_formatted, + channel_urls=list(channel_urls), + channels_formatted=channels_formatted, + ) + + +class NoChannelsConfiguredError(CondaError): + def __init__(self, packages: Iterable[str] = ()): + packages_str = ", ".join(packages) if packages else "the requested packages" + + message = dals( + """ + No channels are configured. Conda requires at least one channel to search for packages. + + You have attempted to install: %(packages_str)s + + To fix this issue, you may do one of the following: + + 1. Add a channel for this command: + conda install -c %(packages_str)s + + 2. Configure channels permanently: + conda config --append channels + + 3. Create or modify your .condarc file to include channels. + + For more information, visit: https://docs.conda.io/projects/conda/en/stable/user-guide/configuration/use-condarc.html#channel-locations-channels + and https://docs.conda.io/projects/conda/en/stable/user-guide/concepts/channels.html#specifying-channels-when-installing-packages + """ + ) + + super().__init__( + message, + packages=list(packages), + packages_str=packages_str, + ) + + +class UnsatisfiableError(CondaError): + """An exception to report unsatisfiable dependencies. + + Args: + bad_deps: a list of tuples of objects (likely MatchSpecs). + chains: (optional) if True, the tuples are interpreted as chains + of dependencies, from top level to bottom. If False, the tuples + are interpreted as simple lists of conflicting specs. + + Returns: + Raises an exception with a formatted message detailing the + unsatisfiable specifications. + """ + + def _format_chain_str(self, bad_deps: Iterable[Iterable[MatchSpec]]): + chains = {} + for dep in sorted(bad_deps, key=len, reverse=True): + dep1 = [s.partition(" ") for s in dep[1:]] + key = (dep[0],) + tuple(v[0] for v in dep1) + vals = ("",) + tuple(v[2] for v in dep1) + found = False + for key2, csets in chains.items(): + if key2[: len(key)] == key: + for cset, val in zip(csets, vals): + cset.add(val) + found = True + if not found: + chains[key] = [{val} for val in vals] + for key, csets in chains.items(): + deps = [] + for name, cset in zip(key, csets): + if "" not in cset: + pass + elif len(cset) == 1: + cset.clear() + else: + cset.remove("") + cset.add("*") + if name[0] == "@": + name = "feature:" + name[1:] + deps.append( + "{} {}".format(name, "|".join(sorted(cset))) if cset else name + ) + chains[key] = " -> ".join(deps) + return [chains[key] for key in sorted(chains.keys())] + + def __init__( + self, + bad_deps: Iterable[Iterable[MatchSpec]], + chains: bool = True, + strict: bool = False, + ): + from .models.match_spec import MatchSpec + + messages = { + "python": dals( + """ + +The following specifications were found +to be incompatible with the existing python installation in your environment: + +Specifications:\n{specs} + +Your python: {ref} + +If python is on the left-most side of the chain, that's the version you've asked for. +When python appears to the right, that indicates that the thing on the left is somehow +not available for the python version you are constrained to. Note that conda will not +change your python version to a different minor version unless you explicitly specify +that. + + """ + ), + "request_conflict_with_history": dals( + """ + +The following specifications were found to be incompatible with a past +explicit spec that is not an explicit spec in this operation ({ref}):\n{specs} + + """ + ), + "direct": dals( + """ + +The following specifications were found to be incompatible with each other: + """ + ), + "virtual_package": dals( + """ + +The following specifications were found to be incompatible with your system:\n{specs} + +Your installed version is: {ref} +""" + ), + } + + msg = "" + self.unsatisfiable = [] + if len(bad_deps) == 0: + msg += """ +Did not find conflicting dependencies. If you would like to know which +packages conflict ensure that you have enabled unsatisfiable hints. + +conda config --set unsatisfiable_hints True + """ + else: + for class_name, dep_class in bad_deps.items(): + if dep_class: + _chains = [] + if class_name == "direct": + msg += messages["direct"] + last_dep_entry = {d[0][-1].name for d in dep_class} + dep_constraint_map = {} + for dep in dep_class: + if dep[0][-1].name in last_dep_entry: + if not dep_constraint_map.get(dep[0][-1].name): + dep_constraint_map[dep[0][-1].name] = [] + dep_constraint_map[dep[0][-1].name].append(dep[0]) + msg += "\nOutput in format: Requested package -> Available versions" + for dep, chain in dep_constraint_map.items(): + if len(chain) > 1: + msg += f"\n\nPackage {dep} conflicts for:\n" + msg += "\n".join( + [" -> ".join([str(i) for i in c]) for c in chain] + ) + self.unsatisfiable += [ + tuple(entries) for entries in chain + ] + else: + for dep_chain, installed_blocker in dep_class: + # Remove any target values from the MatchSpecs, convert to strings + dep_chain = [ + str(MatchSpec(dep, target=None)) for dep in dep_chain + ] + _chains.append(dep_chain) + + if _chains: + _chains = self._format_chain_str(_chains) + else: + _chains = [", ".join(c) for c in _chains] + msg += messages[class_name].format( + specs=dashlist(_chains), ref=installed_blocker + ) + if strict: + msg += ( + "\nNote that strict channel priority may have removed " + "packages required for satisfiability." + ) + + super().__init__(msg) + + +class RemoveError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class DisallowedPackageError(CondaError): + def __init__(self, package_ref: PackageRecord, **kwargs): + from .models.records import PackageRecord + + package_ref = PackageRecord.from_objects(package_ref) + message = ( + "The package '%(dist_str)s' is disallowed by configuration.\n" + "See 'conda config --show disallowed_packages'." + ) + super().__init__( + message, package_ref=package_ref, dist_str=package_ref.dist_str(), **kwargs + ) + + +class SpecsConfigurationConflictError(CondaError): + def __init__( + self, + requested_specs: Iterable[MatchSpec], + pinned_specs: Iterable[MatchSpec], + prefix: PathType, + ): + message = dals( + """ + Requested specs conflict with configured specs. + requested specs: {requested_specs_formatted} + pinned specs: {pinned_specs_formatted} + Use 'conda config --show-sources' to look for 'pinned_specs' and 'track_features' + configuration parameters. Pinned specs may also be defined in the file + {pinned_specs_path}. + """ + ).format( + requested_specs_formatted=dashlist(requested_specs, 4), + pinned_specs_formatted=dashlist(pinned_specs, 4), + pinned_specs_path=join(prefix, PREFIX_PINNED_FILE), + ) + super().__init__( + message, + requested_specs=requested_specs, + pinned_specs=pinned_specs, + prefix=prefix, + ) + + +class CondaIndexError(CondaError, IndexError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CondaValueError(CondaError, ValueError): + def __init__(self, message: str, *args, **kwargs): + super().__init__(message, *args, **kwargs) + + +class CyclicalDependencyError(CondaError, ValueError): + def __init__(self, packages_with_cycles: Iterable[PackageRecord], **kwargs): + from .models.records import PackageRecord + + packages_with_cycles = tuple( + PackageRecord.from_objects(p) for p in packages_with_cycles + ) + message = f"Cyclic dependencies exist among these items: {dashlist(p.dist_str() for p in packages_with_cycles)}" + super().__init__(message, packages_with_cycles=packages_with_cycles, **kwargs) + + +class CorruptedEnvironmentError(CondaError): + def __init__( + self, + environment_location: PathType, + corrupted_file: PathType, + **kwargs, + ): + message = dals( + """ + The target environment has been corrupted. Corrupted environments most commonly + occur when the conda process is force-terminated while in an unlink-link + transaction. + environment location: %(environment_location)s + corrupted file: %(corrupted_file)s + """ + ) + super().__init__( + message, + environment_location=environment_location, + corrupted_file=corrupted_file, + **kwargs, + ) + + +class CondaHistoryError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CondaUpgradeError(CondaError): + def __init__(self, message: str): + msg = f"{message}" + super().__init__(msg) + + +class CondaVerificationError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class SafetyError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class CondaMemoryError(CondaError, MemoryError): + def __init__(self, caused_by: Any, **kwargs): + message = "The conda process ran out of memory. Increase system memory and/or try again." + super().__init__(message, caused_by=caused_by, **kwargs) + + +class NotWritableError(CondaError, OSError): + def __init__(self, path: PathType, errno: int, **kwargs): + kwargs.update( + { + "path": path, + "errno": errno, + } + ) + if on_win: + message = dals( + """ + The current user does not have write permissions to a required path. + path: %(path)s + """ + ) + else: + message = dals( + """ + The current user does not have write permissions to a required path. + path: %(path)s + uid: %(uid)s + gid: %(gid)s + + If you feel that permissions on this path are set incorrectly, you can manually + change them by executing + + $ sudo chown %(uid)s:%(gid)s %(path)s + + In general, it's not advisable to use 'sudo conda'. + """ + ) + kwargs.update( + { + "uid": os.geteuid(), + "gid": os.getegid(), + } + ) + super().__init__(message, **kwargs) + self.errno = errno + + +class NoWritableEnvsDirError(CondaError): + def __init__(self, envs_dirs: Iterable[PathType], **kwargs): + message = f"No writeable envs directories configured.{dashlist(envs_dirs)}" + super().__init__(message, envs_dirs=envs_dirs, **kwargs) + + +class NoWritablePkgsDirError(CondaError): + def __init__(self, pkgs_dirs: Iterable[PathType], **kwargs): + message = f"No writeable pkgs directories configured.{dashlist(pkgs_dirs)}" + super().__init__(message, pkgs_dirs=pkgs_dirs, **kwargs) + + +class EnvironmentIsFrozenError(CondaError): + def __init__(self, prefix: PathType, message: str = "", **kwargs): + error = f"Cannot modify '{prefix}'. The environment is marked as frozen. " + if message: + error += "Reason:\n\n" + error += indent(message, " ") + error += "\n\n" + error += ( + "You can bypass these protections with the `--override-frozen` flag," + " at your own risk." + ) + super().__init__(error, **kwargs) + + +class EnvironmentNotWritableError(CondaError): + def __init__(self, environment_location: PathType, **kwargs): + kwargs.update( + { + "environment_location": environment_location, + } + ) + if on_win: + message = dals( + """ + The current user does not have write permissions to the target environment. + environment location: %(environment_location)s + """ + ) + else: + message = dals( + """ + The current user does not have write permissions to the target environment. + environment location: %(environment_location)s + uid: %(uid)s + gid: %(gid)s + """ + ) + kwargs.update( + { + "uid": os.geteuid(), + "gid": os.getegid(), + } + ) + super().__init__(message, **kwargs) + + +class CondaDependencyError(CondaError): + def __init__(self, message: str): + super().__init__(message) + + +class BinaryPrefixReplacementError(CondaError): + def __init__( + self, + path: PathType, + placeholder: str, + new_prefix: PathType, + original_data_length: int, + new_data_length: int, + ): + message = dals( + """ + Refusing to replace mismatched data length in binary file. + path: %(path)s + placeholder: %(placeholder)s + new prefix: %(new_prefix)s + original data Length: %(original_data_length)d + new data length: %(new_data_length)d + """ + ) + kwargs = { + "path": path, + "placeholder": placeholder, + "new_prefix": new_prefix, + "original_data_length": original_data_length, + "new_data_length": new_data_length, + } + super().__init__(message, **kwargs) + + +class InvalidSpec(CondaError, ValueError): + def __init__(self, message: str, **kwargs): + super().__init__(message, **kwargs) + + +class InvalidVersionSpec(InvalidSpec): + def __init__(self, invalid_spec: str | MatchSpec, details: str): + message = "Invalid version '%(invalid_spec)s': %(details)s" + super().__init__(message, invalid_spec=invalid_spec, details=details) + + +class InvalidMatchSpec(InvalidSpec): + def __init__(self, invalid_spec: str | MatchSpec, details: str): + message = "Invalid spec '%(invalid_spec)s': %(details)s" + super().__init__(message, invalid_spec=invalid_spec, details=details) + + +class EncodingError(CondaError): + def __init__(self, caused_by: Any, **kwargs): + message = ( + dals( + """ + A unicode encoding or decoding error has occurred. + Python 2 is the interpreter under which conda is running in your base environment. + Replacing your base environment with one having Python 3 may help resolve this issue. + If you still have a need for Python 2 environments, consider using 'conda create' + and 'conda activate'. For example: + + $ conda create -n py2 python=2 + $ conda activate py2 + + Error details: %r + + """ + ) + % caused_by + ) + super().__init__(message, caused_by=caused_by, **kwargs) + + +class NoSpaceLeftError(CondaError): + def __init__(self, caused_by: Any, **kwargs): + message = "No space left on devices." + super().__init__(message, caused_by=caused_by, **kwargs) + + +class CondaEnvException(CondaError): + def __init__(self, message: str, *args, **kwargs): + msg = f"{message}" + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileInvalid(CondaEnvException): + def __init__(self, msg: str, *args, **kwargs): + msg = f"Provided environment.yaml is invalid: {msg}" + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileNotFound(CondaEnvException): + def __init__(self, filename: PathType, *args, **kwargs): + msg = f"'{filename}' file not found" + self.filename = filename + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileExtensionNotValid(CondaEnvException): + def __init__(self, filename: PathType, *args, **kwargs): + msg = f"'{filename}' file extension must be one of '.txt', '.yaml' or '.yml'" + self.filename = filename + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileTypeMismatchError(CondaError): + def __init__(self, file_types: dict[str, str], *args, **kwargs): + type_groups = defaultdict(list) + for file, file_type in file_types.items(): + type_groups[file_type].append(file) + + lines = ["Cannot mix environment file formats.\n"] + + for file_type, files in type_groups.items(): + lines.extend(f"'{file}' is a {file_type} format file" for file in files) + + super().__init__("\n".join(lines), *args, **kwargs) + + +class EnvironmentFileEmpty(CondaEnvException): + def __init__(self, filename: PathType, *args, **kwargs): + self.filename = filename + msg = f"Environment file '{filename}' is empty." + super().__init__(msg, *args, **kwargs) + + +class EnvironmentFileNotDownloaded(CondaError): + def __init__(self, username: str, packagename: str, *args, **kwargs): + msg = f"{username}/{packagename} file not downloaded" + self.username = username + self.packagename = packagename + super().__init__(msg, *args, **kwargs) + + +class PluginError(CondaError): + pass + + +class SpecNotFound(CondaError): + def __init__(self, msg: str, *args, **kwargs): + super().__init__(msg, *args, **kwargs) + + +class EnvironmentSpecPluginNotDetected(SpecNotFound): + def __init__( + self, + name: str, + plugin_names: Iterable[str], + autodetect_disabled_plugins: Iterable[str] = (), + *args, + **kwargs, + ): + self.name = name + msg = dals( + f""" + Environment at {name} is not able to be detected by any installed environment specifier plugins. + + Available plugins: {dashlist(plugin_names, 16)} + + """ + ) + if autodetect_disabled_plugins: + msg += dals( + """ + Found compatible plugins but they must be explicitly selected. + Request conda to use these plugins by providing + the cli argument `--environment-spec PLUGIN_NAME`: + """ + ) + dashlist(autodetect_disabled_plugins, 4) + super().__init__(msg, *args, **kwargs) + + +class EnvironmentExporterNotDetected(CondaError): + def __init__( + self, + filename: str, + exporters: Iterable[CondaEnvironmentExporter], + *args, + **kwargs, + ): + self.filename = filename + supported_filenames: list[str] = [] + available_formats: list[str] = [] + for exporter in exporters: + supported_filenames.extend( + f"{filename:<20} (format: {exporter.name})" + for filename in exporter.default_filenames + ) + available_formats.append( + f"{exporter.name:<20} (aliases: {', '.join(exporter.aliases)})" + if exporter.aliases + else exporter.name + ) + msg = ( + f"No environment exporter plugin found for filename '{filename}'.\n" + f"\n" + f"Supported filenames:{dashlist(supported_filenames)}\n" + f"\n" + f"Available formats:{dashlist(available_formats)}\n" + f"\n" + f"Use conda export --format=FORMAT to specify the export format explicitly, " + f"or rename your file to match a supported filename pattern." + ) + super().__init__(msg, *args, **kwargs) + + +class SpecNotFoundInPackageCache(CondaError): + def __init__(self, msg: str, *args, **kwargs): + super().__init__(msg, *args, **kwargs) + + +def maybe_raise(error: BaseException, context: Context): + if isinstance(error, CondaMultiError): + groups = groupby(lambda e: isinstance(e, ClobberError), error.errors) + clobber_errors = groups.get(True, ()) + groups = groupby(lambda e: isinstance(e, SafetyError), groups.get(False, ())) + safety_errors = groups.get(True, ()) + other_errors = groups.get(False, ()) + + if ( + (safety_errors and context.safety_checks == SafetyChecks.enabled) + or ( + clobber_errors + and context.path_conflict == PathConflict.prevent + and not context.clobber + ) + or other_errors + ): + raise error + elif (safety_errors and context.safety_checks == SafetyChecks.warn) or ( + clobber_errors + and context.path_conflict == PathConflict.warn + and not context.clobber + ): + print_conda_exception(error) + + elif isinstance(error, ClobberError): + if context.path_conflict == PathConflict.prevent and not context.clobber: + raise error + elif context.path_conflict == PathConflict.warn and not context.clobber: + print_conda_exception(error) + + elif isinstance(error, SafetyError): + if context.safety_checks == SafetyChecks.enabled: + raise error + elif context.safety_checks == SafetyChecks.warn: + print_conda_exception(error) + + else: + raise error + + +def print_conda_exception(exc_val: CondaError, exc_tb: TracebackType | None = None): + from .base.context import context + + rc = getattr(exc_val, "return_code", None) + if context.debug or (not isinstance(exc_val, DryRunExit) and context.info): + print(_format_exc(exc_val, exc_tb), file=sys.stderr) + elif context.json: + if isinstance(exc_val, DryRunExit): + return + logger = getLogger("conda.stdout" if rc else "conda.stderr") + exc_json = json_dumps(exc_val.dump_map(), sort_keys=True) + logger.info(f"{exc_json}\n") + else: + stderrlog = getLogger("conda.stderr") + stderrlog.error("\n%r\n", exc_val) + # An alternative which would allow us not to reload sys with newly setdefaultencoding() + # is to not use `%r`, e.g.: + # Still, not being able to use `%r` seems too great a price to pay. + # stderrlog.error("\n" + exc_val.__repr__() + \n") + + +def _format_exc( + exc_val: BaseException | None = None, exc_tb: TracebackType | None = None +): + if exc_val is None: + exc_type, exc_val, exc_tb = sys.exc_info() + else: + exc_type = type(exc_val) + if exc_tb: + formatted_exception = format_exception(exc_type, exc_val, exc_tb) + else: + formatted_exception = format_exception_only(exc_type, exc_val) + return "".join(formatted_exception) + + +class InvalidInstaller(Exception): + def __init__(self, name: str): + msg = f"Unable to load installer for {name}" + super().__init__(msg) + + +class OfflineError(CondaError, RuntimeError): + pass + + +class CondaUpdatePackageError(CondaError): + def __init__(self, spec: str | list[str]): + spec_format = dashlist(spec, 4) if isinstance(spec, list) else spec + msg = ( + f"`conda update` only supports name-only spec, but received: {spec_format}\n" + f"Use `conda install` to install a specific version of a package." + ) + super().__init__(msg) diff --git a/miniconda3/lib/python3.13/site-packages/conda/exports.py b/miniconda3/lib/python3.13/site-packages/conda/exports.py new file mode 100644 index 0000000000000000000000000000000000000000..db7d8fb88b934edd1a9c8300d1dccba0bdb42213 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/exports.py @@ -0,0 +1,395 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Backported exports for conda-build.""" + +from __future__ import annotations + +from builtins import input # noqa: UP029 +from io import StringIO +from typing import TYPE_CHECKING + +from . import CondaError +from .base.constants import ( + DEFAULT_CHANNELS, + DEFAULT_CHANNELS_UNIX, + DEFAULT_CHANNELS_WIN, + PREFIX_PLACEHOLDER, +) +from .base.context import ( # noqa: F401 + context, + non_x86_machines, + reset_context, + sys_rc_path, +) +from .cli.common import spec_from_line, specs_from_args, specs_from_url # noqa: F401 +from .cli.conda_argparse import ArgumentParser # noqa: F401 +from .cli.helpers import ( # noqa: F401 + add_parser_channels, + add_parser_prefix, +) +from .common import compat # noqa: F401 +from .common.serialize.json import CondaJSONEncoder +from .common.toposort import _toposort # noqa: F401 +from .core.index import ( + Index, + dist_str_in_index, # noqa: F401 +) +from .core.package_cache_data import ProgressiveFetchExtract # noqa: F401 +from .core.prefix_data import delete_prefix_from_linked_data +from .core.solve import Solver # noqa: F401 +from .core.subdir_data import cache_fn_url # noqa: F401 +from .deprecations import deprecated +from .exceptions import ( + CondaHTTPError, + CondaOSError, + LinkError, + LockError, + PaddingError, + PathNotFoundError, + UnsatisfiableError, +) +from .gateways.connection.download import TmpDownload # noqa: F401 +from .gateways.connection.download import download as _download +from .gateways.connection.session import CondaSession # noqa: F401 +from .gateways.disk.create import TemporaryDirectory # noqa: F401 +from .gateways.disk.delete import delete_trash # noqa: F401 +from .gateways.disk.link import lchmod # noqa: F401 +from .gateways.subprocess import ACTIVE_SUBPROCESSES, subprocess_call # noqa: F401 +from .misc import untracked, walk_prefix # noqa: F401 +from .models.channel import Channel, get_conda_build_local_url # noqa: F401 +from .models.dist import Dist +from .models.enums import FileMode, PathEnum # noqa: F401 +from .models.version import VersionOrder, normalized_version # noqa: F401 +from .resolve import ( # noqa: F401 + MatchSpec, + Resolve, + ResolvePackageNotFound, + Unsatisfiable, +) +from .utils import human_bytes, url_path # noqa: F401 + +if TYPE_CHECKING: + from typing import Any + +reset_context() # initialize context when conda.exports is imported + + +NoPackagesFound = NoPackagesFoundError = ResolvePackageNotFound +non_x86_linux_machines = non_x86_machines +arch_name = context.arch_name +binstar_upload = context.anaconda_upload +bits = context.bits +default_prefix = context.default_prefix +default_python = context.default_python +envs_dirs = context.envs_dirs +pkgs_dirs = context.pkgs_dirs +platform = context.platform +root_dir = context.root_prefix +root_writable = context.root_writable +subdir = context.subdir +conda_build = context.conda_build +get_rc_urls = lambda: list(context.channels) +get_local_urls = lambda: list(get_conda_build_local_url()) or [] +load_condarc = lambda fn: reset_context([fn]) +PaddingError = PaddingError +LinkError = LinkError +CondaOSError = CondaOSError +# Replacements for six exports for compatibility + + +# FUTURE: conda 26.3+ remove this +def __getattr__(name: str) -> Any: + # lazy load the deprecated module + if name == "plan": + from . import plan + + return plan + + raise AttributeError(f"module '{__name__}' has no attribute '{name}'") + + +deprecated.constant( + "26.3", + "26.9", + "EntityEncoder", + CondaJSONEncoder, + addendum="Use `conda.common.serialize.json.CondaJSONEncoder` instead.", +) +del CondaJSONEncoder + +deprecated.constant( + "26.9", + "27.3", + "input", + input, + addendum="Use `builtins.input` instead.", +) +del input + +deprecated.constant( + "26.9", + "27.3", + "StringIO", + StringIO, + addendum="Use `io.StringIO` instead.", +) +del StringIO + +deprecated.constant( + "26.9", + "27.3", + "PY3", + True, + addendum="Python 2 is no longer supported.", +) + +deprecated.constant( + "26.9", + "27.3", + "string_types", + str, + addendum="Use `str` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "text_type", + str, + addendum="Use `str` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "DEFAULT_CHANNELS", + DEFAULT_CHANNELS, + addendum="Use `conda.base.constants.DEFAULT_CHANNELS` instead.", +) +del DEFAULT_CHANNELS + +deprecated.constant( + "26.9", + "27.3", + "DEFAULT_CHANNELS_UNIX", + DEFAULT_CHANNELS_UNIX, + addendum="Use `conda.base.constants.DEFAULT_CHANNELS_UNIX` instead.", +) +del DEFAULT_CHANNELS_UNIX + +deprecated.constant( + "26.9", + "27.3", + "DEFAULT_CHANNELS_WIN", + DEFAULT_CHANNELS_WIN, + addendum="Use `conda.base.constants.DEFAULT_CHANNELS_WIN` instead.", +) +del DEFAULT_CHANNELS_WIN + +deprecated.constant( + "26.9", + "27.3", + "PREFIX_PLACEHOLDER", + PREFIX_PLACEHOLDER, + addendum="Use `conda.base.constants.PREFIX_PLACEHOLDER` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "_PREFIX_PLACEHOLDER", + PREFIX_PLACEHOLDER, + addendum="Use `conda.base.constants.PREFIX_PLACEHOLDER` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "prefix_placeholder", + PREFIX_PLACEHOLDER, + addendum="Use `conda.base.constants.PREFIX_PLACEHOLDER` instead.", +) +del PREFIX_PLACEHOLDER + +deprecated.constant( + "26.9", + "27.3", + "CondaError", + CondaError, + addendum="Use `conda.CondaError` instead.", +) +del CondaError + +deprecated.constant( + "26.9", + "27.3", + "CondaHTTPError", + CondaHTTPError, + addendum="Use `conda.exceptions.CondaHTTPError` instead.", +) +del CondaHTTPError + +deprecated.constant( + "26.9", + "27.3", + "CondaOSError", + CondaOSError, + addendum="Use `conda.exceptions.CondaOSError` instead.", +) +del CondaOSError + +deprecated.constant( + "26.9", + "27.3", + "LinkError", + LinkError, + addendum="Use `conda.exceptions.LinkError` instead.", +) +del LinkError + +deprecated.constant( + "26.9", + "27.3", + "LockError", + LockError, + addendum="Use `conda.exceptions.LockError` instead.", +) +del LockError + +deprecated.constant( + "26.9", + "27.3", + "PaddingError", + PaddingError, + addendum="Use `conda.exceptions.PaddingError` instead.", +) +del PaddingError + +deprecated.constant( + "26.9", + "27.3", + "PathNotFoundError", + PathNotFoundError, + addendum="Use `conda.exceptions.PathNotFoundError` instead.", +) + +deprecated.constant( + "26.9", + "27.3", + "CondaFileNotFoundError", + PathNotFoundError, + addendum="Use `conda.exceptions.PathNotFoundError` instead.", +) +del PathNotFoundError + +deprecated.constant( + "26.9", + "27.3", + "UnsatisfiableError", + UnsatisfiableError, + addendum="Use `conda.exceptions.UnsatisfiableError` instead.", +) +del UnsatisfiableError + + +def get_default_urls(): + from .base.constants import DEFAULT_CHANNELS + + return DEFAULT_CHANNELS + + +def rm_rf(path, max_retries=5, trash=True): + from .gateways.disk.delete import rm_rf + + rm_rf(path) + delete_prefix_from_linked_data(path) + + +def get_index( + channel_urls=(), + prepend=True, + platform=None, + use_local=False, + use_cache=False, + unknown=None, + prefix=None, +): + index = Index( + channel_urls, prepend, platform, use_local, use_cache, unknown, prefix + ) + return {Dist(prec): prec for prec in index.values()} + + +def package_cache(): + from .core.package_cache_data import PackageCacheData + + class package_cache: + def __contains__(self, dist): + return bool( + PackageCacheData.first_writable().get(Dist(dist).to_package_ref(), None) + ) + + def keys(self): + return (Dist(v) for v in PackageCacheData.first_writable().values()) + + def __delitem__(self, dist): + PackageCacheData.first_writable().remove(Dist(dist).to_package_ref()) + + return package_cache() + + +def linked_data(prefix, ignore_channels=False): + """Return a dictionary of the linked packages in prefix.""" + from .core.prefix_data import PrefixData + from .models.dist import Dist + + pd = PrefixData(prefix) + return { + Dist(prefix_record): prefix_record + for prefix_record in pd._prefix_records.values() + } + + +def linked(prefix, ignore_channels=False): + """Return the Dists of linked packages in prefix.""" + from .models.enums import PackageType + + conda_package_types = PackageType.conda_package_types() + ld = linked_data(prefix, ignore_channels=ignore_channels).items() + return { + dist + for dist, prefix_rec in ld + if prefix_rec.package_type in conda_package_types + } + + +# exports +def is_linked(prefix, dist): + """ + Return the install metadata for a linked package in a prefix, or None + if the package is not linked in the prefix. + """ + # FIXME Functions that begin with `is_` should return True/False + from .core.prefix_data import PrefixData + + pd = PrefixData(prefix) + prefix_record = pd.get(dist.name, None) + if prefix_record is None: + return None + elif MatchSpec(dist).match(prefix_record): + return prefix_record + else: + return None + + +def download( + url, + dst_path, + session=None, + md5sum=None, + urlstxt=False, + retries=3, + sha256=None, + size=None, +): + return _download(url, dst_path, md5=md5sum, sha256=sha256, size=size) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f7052773f52043727fe66b1bf54c918f7aaeb1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/__init__.py @@ -0,0 +1,27 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Gateways isolate interaction of conda code with the outside world. Disk manipulation, +database interaction, and remote requests should all be through various gateways. Functions +and methods in ``conda.gateways`` must use ``conda.models`` for arguments and return values. + +Conda modules importable from ``conda.gateways`` are + +- ``conda.common`` +- ``conda.models`` +- ``conda.gateways`` + +Conda modules off limits for import within ``conda.gateways`` are + +- ``conda.api`` +- ``conda.cli`` +- ``conda.client`` +- ``conda.core`` + +Conda modules strictly prohibited from importing ``conda.gateways`` are + +- ``conda.api`` +- ``conda.cli`` +- ``conda.client`` + +""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/anaconda_client.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/anaconda_client.py new file mode 100644 index 0000000000000000000000000000000000000000..75a16f782a77bf19ed7dd38ce9d631799c78a302 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/anaconda_client.py @@ -0,0 +1,68 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Anaconda-client (binstar) token management for CondaSession.""" + +import os +import re +from logging import getLogger +from os.path import isdir, isfile, join +from stat import S_IREAD, S_IWRITE + +from platformdirs import user_config_dir + +from ..common.url import quote_plus, unquote_plus +from .disk.delete import rm_rf + +log = getLogger(__name__) + + +def replace_first_api_with_conda(url): + # replace first occurrence of 'api' with 'conda' in url + return re.sub(r"([./])api([./]|$)", r"\1conda\2", url, count=1) + + +def _get_binstar_token_directory(): + if "BINSTAR_CONFIG_DIR" in os.environ: + return os.path.join(os.environ["BINSTAR_CONFIG_DIR"], "data") + else: + return user_config_dir(appname="binstar", appauthor="ContinuumIO") + + +def read_binstar_tokens(): + tokens = {} + token_dir = _get_binstar_token_directory() + if not isdir(token_dir): + return tokens + + for tkn_entry in os.scandir(token_dir): + if tkn_entry.name[-6:] != ".token": + continue + url = re.sub(r"\.token$", "", unquote_plus(tkn_entry.name)) + with open(tkn_entry.path) as f: + token = f.read() + tokens[url] = tokens[replace_first_api_with_conda(url)] = token + return tokens + + +def set_binstar_token(url, token): + token_dir = _get_binstar_token_directory() + if not isdir(token_dir): + os.makedirs(token_dir) + + tokenfile = join(token_dir, f"{quote_plus(url)}.token") + + if isfile(tokenfile): + os.unlink(tokenfile) + with open(tokenfile, "w") as fd: + fd.write(token) + os.chmod(tokenfile, S_IWRITE | S_IREAD) + + +def remove_binstar_token(url): + token_dir = _get_binstar_token_directory() + tokenfile = join(token_dir, f"{quote_plus(url)}.token") + rm_rf(tokenfile) + + +if __name__ == "__main__": + print(read_binstar_tokens()) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21beee6400fb947266f0112b7c83fba2b2fb9e01 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/__init__.py @@ -0,0 +1,18 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from requests import ConnectionError, HTTPError, Session # noqa: F401 +from requests.adapters import DEFAULT_POOLBLOCK, BaseAdapter, HTTPAdapter # noqa: F401 +from requests.auth import AuthBase, _basic_auth_str # noqa: F401 +from requests.cookies import extract_cookies_to_jar # noqa: F401 +from requests.exceptions import ( # noqa: F401 + ChunkedEncodingError, + InvalidSchema, + SSLError, +) +from requests.exceptions import ProxyError as RequestsProxyError # noqa: F401 +from requests.hooks import dispatch_hook # noqa: F401 +from requests.models import PreparedRequest, Response # noqa: F401 +from requests.packages.urllib3.exceptions import InsecureRequestWarning # noqa: F401 +from requests.packages.urllib3.util.retry import Retry # noqa: F401 +from requests.structures import CaseInsensitiveDict # noqa: F401 +from requests.utils import get_auth_from_url, get_netrc_auth # noqa: F401 diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/ftp.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/ftp.py new file mode 100644 index 0000000000000000000000000000000000000000..05faa09862f2a700f217f15370ab46df8e82cb14 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/ftp.py @@ -0,0 +1,278 @@ +# Copyright (C) 2012 Cory Benfield +# SPDX-License-Identifier: Apache-2.0 +"""Defines FTP transport adapter for CondaSession (requests.Session). + +Taken from requests-ftp (https://github.com/Lukasa/requests-ftp/blob/master/requests_ftp/ftp.py). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import ftplib +from base64 import b64decode +from io import BytesIO, StringIO +from logging import getLogger + +from ....common.url import urlparse +from ....exceptions import AuthenticationError +from .. import BaseAdapter, Response, dispatch_hook + +log = getLogger(__name__) + + +# After: https://stackoverflow.com/a/44073062/3257826 +# And: https://stackoverflow.com/a/35368154/3257826 +_old_makepasv = ftplib.FTP.makepasv + + +def _new_makepasv(self): + host, port = _old_makepasv(self) + host = self.sock.getpeername()[0] + return host, port + + +ftplib.FTP.makepasv = _new_makepasv + + +class FTPAdapter(BaseAdapter): + """A Requests Transport Adapter that handles FTP urls.""" + + def __init__(self): + super().__init__() + + # Build a dictionary keyed off the methods we support in upper case. + # The values of this dictionary should be the functions we use to + # send the specific queries. + self.func_table = { + "LIST": self.list, + "RETR": self.retr, + "NLST": self.nlst, + "GET": self.retr, + } + + def send(self, request, **kwargs): + """Sends a PreparedRequest object over FTP. Returns a response object.""" + # Get the authentication from the prepared request, if any. + auth = self.get_username_password_from_header(request) + + # Next, get the host and the path. + host, port, path = self.get_host_and_path_from_url(request) + + # Sort out the timeout. + timeout = kwargs.get("timeout", None) + if not isinstance(timeout, int): + # https://github.com/conda/conda/pull/3392 + timeout = 10 + + # Establish the connection and login if needed. + self.conn = ftplib.FTP() + self.conn.connect(host, port, timeout) + + if auth is not None: + self.conn.login(auth[0], auth[1]) + else: + self.conn.login() + + # Get the method and attempt to find the function to call. + resp = self.func_table[request.method](path, request) + + # Return the response. + return resp + + def close(self): + """Dispose of any internal state.""" + # Currently this is a no-op. + pass + + def list(self, path, request): + """Executes the FTP LIST command on the given path.""" + data = StringIO() + + # To ensure the StringIO gets cleaned up, we need to alias its close + # method to the release_conn() method. This is a dirty hack, but there + # you go. + data.release_conn = data.close + + self.conn.cwd(path) + code = self.conn.retrbinary("LIST", data_callback_factory(data)) + + # When that call has finished executing, we'll have all our data. + response = build_text_response(request, data, code) + + # Close the connection. + self.conn.close() + + return response + + def retr(self, path, request): + """Executes the FTP RETR command on the given path.""" + data = BytesIO() + + # To ensure the BytesIO gets cleaned up, we need to alias its close + # method. See self.list(). + data.release_conn = data.close + + code = self.conn.retrbinary("RETR " + path, data_callback_factory(data)) + + response = build_binary_response(request, data, code) + + # Close the connection. + self.conn.close() + + return response + + def nlst(self, path, request): + """Executes the FTP NLST command on the given path.""" + data = StringIO() + + # Alias the close method. + data.release_conn = data.close + + self.conn.cwd(path) + code = self.conn.retrbinary("NLST", data_callback_factory(data)) + + # When that call has finished executing, we'll have all our data. + response = build_text_response(request, data, code) + + # Close the connection. + self.conn.close() + + return response + + def get_username_password_from_header(self, request): + """Given a PreparedRequest object, reverse the process of adding HTTP + Basic auth to obtain the username and password. Allows the FTP adapter + to piggyback on the basic auth notation without changing the control + flow. + """ + auth_header = request.headers.get("Authorization") + + if auth_header: + # The basic auth header is of the form 'Basic xyz'. We want the + # second part. Check that we have the right kind of auth though. + encoded_components = auth_header.split()[:2] + if encoded_components[0] != "Basic": + raise AuthenticationError("Invalid form of Authentication used.") + else: + encoded = encoded_components[1] + + # Decode the base64 encoded string. + decoded = b64decode(encoded) + + # The string is of the form 'username:password'. Split on the + # colon. + components = decoded.split(":") + username = components[0] + password = components[1] + return (username, password) + else: + # No auth header. Return None. + return None + + def get_host_and_path_from_url(self, request): + """Given a PreparedRequest object, split the URL in such a manner as to + determine the host and the path. This is a separate method to wrap some + of urlparse's craziness. + """ + url = request.url + parsed = urlparse(url) + path = parsed.path + + # If there is a slash on the front of the path, chuck it. + if path[0] == "/": + path = path[1:] + + host = parsed.hostname + port = parsed.port or 0 + + return (host, port, path) + + +def data_callback_factory(variable): + """Returns a callback suitable for use by the FTP library. This callback + will repeatedly save data into the variable provided to this function. This + variable should be a file-like structure. + """ + + def callback(data): + variable.write(data) + + return callback + + +def build_text_response(request, data, code): + """Build a response for textual data.""" + return build_response(request, data, code, "ascii") + + +def build_binary_response(request, data, code): + """Build a response for data whose encoding is unknown.""" + return build_response(request, data, code, None) + + +def build_response(request, data, code, encoding): + """Builds a response object from the data returned by ftplib, using the + specified encoding. + """ + response = Response() + + response.encoding = encoding + + # Fill in some useful fields. + response.raw = data + response.url = request.url + response.request = request + response.status_code = get_status_code_from_code_response(code) + + # Make sure to seek the file-like raw object back to the start. + response.raw.seek(0) + + # Run the response hook. + response = dispatch_hook("response", request.hooks, response) + return response + + +def get_status_code_from_code_response(code): + r"""Handle complicated code response, even multi-lines. + + We get the status code in two ways: + - extracting the code from the last valid line in the response + - getting it from the 3 first digits in the code + After a comparison between the two values, + we can safely set the code or raise a warning. + Examples: + - get_status_code_from_code_response('200 Welcome') == 200 + - multi_line_code = '226-File successfully transferred\n226 0.000 seconds' + get_status_code_from_code_response(multi_line_code) == 226 + - multi_line_with_code_conflicts = '200-File successfully transferred\n226 0.000 seconds' + get_status_code_from_code_response(multi_line_with_code_conflicts) == 226 + For more detail see RFC 959, page 36, on multi-line responses: + https://www.ietf.org/rfc/rfc959.txt + "Thus the format for multi-line replies is that the first line + will begin with the exact required reply code, followed + immediately by a Hyphen, "-" (also known as Minus), followed by + text. The last line will begin with the same code, followed + immediately by Space , optionally some text, and the Telnet + end-of-line code." + """ + last_valid_line_from_code = [line for line in code.split("\n") if line][-1] + status_code_from_last_line = int(last_valid_line_from_code.split()[0]) + status_code_from_first_digits = int(code[:3]) + if status_code_from_last_line != status_code_from_first_digits: + log.warning( + "FTP response status code seems to be inconsistent.\n" + "Code received: %s, extracted: %s and %s", + code, + status_code_from_last_line, + status_code_from_first_digits, + ) + return status_code_from_last_line diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/http.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/http.py new file mode 100644 index 0000000000000000000000000000000000000000..524d2b29de288b2cefda22232c1789c5f9ab9a14 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/http.py @@ -0,0 +1,82 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2008-2023 The pip developers +# SPDX-License-Identifier: MIT +# +"""Defines HTTP transport adapter for CondaSession (requests.Session). + +Closely derived from pip: + +https://github.com/pypa/pip/blob/8c24fd2a80bad21aa29aec02fb48bd89a1e8f5e1/src/pip/_internal/network/session.py#L254 + +Under the MIT license: + +Copyright (c) 2008-2023 The pip developers (see AUTHORS.txt file on the pip repository) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" + +from typing import TYPE_CHECKING, Any, Optional + +from .. import DEFAULT_POOLBLOCK +from .. import HTTPAdapter as BaseHTTPAdapter + +if TYPE_CHECKING: + from ssl import SSLContext + + from urllib3 import PoolManager + + +class _SSLContextAdapterMixin: + """Mixin to add the ``ssl_context`` constructor argument to HTTP adapters. + + The additional argument is forwarded directly to the pool manager. This allows us + to dynamically decide what SSL store to use at runtime, which is used to implement + the optional ``truststore`` backend. + """ + + def __init__( + self, + *, + ssl_context: Optional["SSLContext"] = None, + **kwargs: Any, + ) -> None: + self._ssl_context = ssl_context + super().__init__(**kwargs) + + def init_poolmanager( + self, + connections: int, + maxsize: int, + block: bool = DEFAULT_POOLBLOCK, + **pool_kwargs: Any, + ) -> "PoolManager": + if self._ssl_context is not None: + pool_kwargs.setdefault("ssl_context", self._ssl_context) + return super().init_poolmanager( # type: ignore[misc] + connections=connections, + maxsize=maxsize, + block=block, + **pool_kwargs, + ) + + +class HTTPAdapter(_SSLContextAdapterMixin, BaseHTTPAdapter): + pass diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/localfs.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/localfs.py new file mode 100644 index 0000000000000000000000000000000000000000..18496e8fa9a4561bb688536352aa136e20f78954 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/localfs.py @@ -0,0 +1,59 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Defines local filesystem transport adapter for CondaSession (requests.Session).""" + +from email.utils import formatdate +from logging import getLogger +from mimetypes import guess_type +from os import stat +from tempfile import SpooledTemporaryFile + +from ....common.compat import ensure_binary +from ....common.path import url_to_path +from ....common.serialize import json +from .. import BaseAdapter, CaseInsensitiveDict, Response + +log = getLogger(__name__) + + +class LocalFSAdapter(BaseAdapter): + def send( + self, request, stream=None, timeout=None, verify=None, cert=None, proxies=None + ): + pathname = url_to_path(request.url) + + resp = Response() + resp.status_code = 200 + resp.url = request.url + + try: + stats = stat(pathname) + except OSError as exc: + resp.status_code = 404 + message = { + "error": "file does not exist", + "path": pathname, + "exception": repr(exc), + } + fh = SpooledTemporaryFile() + fh.write(ensure_binary(json.dumps(message))) + fh.seek(0) + resp.raw = fh + resp.close = resp.raw.close + else: + modified = formatdate(stats.st_mtime, usegmt=True) + content_type = guess_type(pathname)[0] or "text/plain" + resp.headers = CaseInsensitiveDict( + { + "Content-Type": content_type, + "Content-Length": stats.st_size, + "Last-Modified": modified, + } + ) + + resp.raw = open(pathname, "rb") + resp.close = resp.raw.close + return resp + + def close(self): + pass # pragma: no cover diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/s3.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/s3.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0caaae8dcd3254b0f08faa9428025eeb3a749e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/adapters/s3.py @@ -0,0 +1,98 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Defines S3 transport adapter for CondaSession (requests.Session).""" + +from __future__ import annotations + +from logging import LoggerAdapter, getLogger +from tempfile import SpooledTemporaryFile +from typing import TYPE_CHECKING + +from ....common.compat import ensure_binary +from ....common.serialize import json +from ....common.url import url_to_s3_info +from .. import BaseAdapter, CaseInsensitiveDict, Response + +if TYPE_CHECKING: + from .. import PreparedRequest + +log = getLogger(__name__) +stderrlog = LoggerAdapter(getLogger("conda.stderrlog"), extra=dict(terminator="\n")) + + +class S3Adapter(BaseAdapter): + def send( + self, + request: PreparedRequest, + stream: bool = False, + timeout: None | float | tuple[float, float] | tuple[float, None] = None, + verify: bool | str = True, + cert: None | bytes | str | tuple[bytes | str, bytes | str] = None, + proxies: dict[str, str] | None = None, + ) -> Response: + resp = Response() + resp.status_code = 200 + resp.url = request.url + + try: + return self._send_boto3(resp, request) + except ImportError: + stderrlog.info( + "\nError: boto3 is required for S3 channels. " + "Please install with `conda install boto3`\n" + "Make sure to run `conda deactivate` if you " + "are in a conda environment.\n" + ) + resp.status_code = 404 + return resp + + def close(self): + pass + + def _send_boto3(self, resp: Response, request: PreparedRequest) -> Response: + from boto3.session import Session + from botocore.exceptions import BotoCoreError, ClientError + + bucket_name, key_string = url_to_s3_info(request.url) + # https://github.com/conda/conda/issues/8993 + # creating a separate boto3 session to make this thread safe + session = Session() + # create a resource client using this thread's session object + s3 = session.resource("s3") + # finally get the S3 object + key = s3.Object(bucket_name, key_string[1:]) + + try: + response = key.get() + except (BotoCoreError, ClientError) as e: + resp.status_code = 404 + message = { + "error": "error downloading file from s3", + "path": request.url, + "exception": repr(e), + } + resp.raw = self._write_tempfile( + lambda x: x.write(ensure_binary(json.dumps(message))) + ) + resp.close = resp.raw.close + return resp + + key_headers = response["ResponseMetadata"]["HTTPHeaders"] + resp.headers = CaseInsensitiveDict( + { + "Content-Type": key_headers.get("content-type", "text/plain"), + "Content-Length": key_headers["content-length"], + "Last-Modified": key_headers["last-modified"], + } + ) + + resp.raw = self._write_tempfile(key.download_fileobj) + resp.close = resp.raw.close + + return resp + + def _write_tempfile(self, writer_callable): + fh = SpooledTemporaryFile() + writer_callable(fh) + fh.seek(0) + return fh diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/download.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/download.py new file mode 100644 index 0000000000000000000000000000000000000000..ada6bc729c13703340a48aceae42d2fe1a792015 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/download.py @@ -0,0 +1,461 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Download logic for conda indices and packages.""" + +from __future__ import annotations + +import hashlib +import os +import tempfile +import warnings +from contextlib import contextmanager +from logging import DEBUG, getLogger +from os.path import basename, exists, join +from pathlib import Path + +from ... import CondaError +from ...auxlib.ish import dals +from ...auxlib.logz import stringify +from ...base.constants import CONDA_HOMEPAGE_URL, PARTIAL_EXTENSION +from ...base.context import context +from ...common.io import time_recorder +from ...common.url import join_url +from ...exceptions import ( + BasicClobberError, + ChecksumMismatchError, + CondaDependencyError, + CondaHTTPError, + CondaSSLError, + CondaValueError, + ProxyError, + maybe_raise, +) +from ...models.channel import Channel +from ..disk.delete import rm_rf +from ..disk.lock import lock +from . import ( + ConnectionError, + HTTPError, + InsecureRequestWarning, + InvalidSchema, + RequestsProxyError, + SSLError, +) +from .session import get_session + +log = getLogger(__name__) + + +CHUNK_SIZE = 1 << 14 + + +def disable_ssl_verify_warning(): + warnings.simplefilter("ignore", InsecureRequestWarning) + + +@time_recorder("download") +def download( + url, + target_full_path, + md5=None, + sha256=None, + size=None, + progress_update_callback=None, +): + if exists(target_full_path): + maybe_raise(BasicClobberError(target_full_path, url, context), context) + if not context.ssl_verify: + disable_ssl_verify_warning() + + with download_http_errors(url): + try: + download_inner( + url, target_full_path, md5, sha256, size, progress_update_callback + ) + except ChecksumMismatchError as e: + if not e._kwargs["partial_download"]: + raise + + log.warning("Retry failed partial download %s", target_full_path) + download_inner( + url, target_full_path, md5, sha256, size, progress_update_callback + ) + + +def download_inner(url, target_full_path, md5, sha256, size, progress_update_callback): + timeout = context.remote_connect_timeout_secs, context.remote_read_timeout_secs + session = get_session(url) + + partial = False + if size and (md5 or sha256): + partial = True + + streamed_bytes = 0 + size_builder = 0 + + # Use `.partial` even for full downloads. Avoid creating incomplete files + # with the final filename. + with download_partial_file( + target_full_path, url=url, md5=md5, sha256=sha256, size=size + ) as target: + stat_result = os.fstat(target.fileno()) + if size is not None and stat_result.st_size >= size: + return # moves partial onto target_path, checksum will be checked + + headers = {} + if partial and stat_result.st_size > 0: + headers = {"Range": f"bytes={stat_result.st_size}-"} + target.seek(stat_result.st_size) + + resp = session.get( + url, stream=True, headers=headers, proxies=session.proxies, timeout=timeout + ) + if log.isEnabledFor(DEBUG): + log.debug(stringify(resp, content_max_len=256)) + resp.raise_for_status() + + # Reset file if we think we're downloading partial content but the + # server doesn't respond with 206 Partial Content + if partial and resp.status_code != 206: + target.seek(0) + target.truncate() + + content_length = total_content_length = int( + resp.headers.get("Content-Length", 0) + ) + if partial and headers: + # Get total content length, not the range we are currently fetching. + # ex. Content-Range: bytes 200-1000/67589 + content_range = resp.headers.get("Content-Range", "bytes 0-0/0") + try: + total_content_length = int( + content_range.split(" ", 1)[1].rsplit("/")[-1] + ) + except (LookupError, ValueError): + pass + + for chunk in resp.iter_content(chunk_size=CHUNK_SIZE): + # chunk could be the decompressed form of the real data + # but we want the exact number of bytes read till now + streamed_bytes = resp.raw.tell() + try: + target.write(chunk) + except OSError as e: + message = "Failed to write to %(target_path)s\n errno: %(errno)d" + raise CondaError(message, target_path=target.name, errno=e.errno) + size_builder += len(chunk) + + if total_content_length and 0 <= streamed_bytes <= content_length: + if progress_update_callback: + progress_update_callback( + (stat_result.st_size + streamed_bytes) / total_content_length + ) + + if content_length and streamed_bytes != content_length: + # TODO: needs to be a more-specific error type + message = dals( + """ + Downloaded bytes did not match Content-Length + url: %(url)s + target_path: %(target_path)s + Content-Length: %(content_length)d + downloaded bytes: %(downloaded_bytes)d + """ + ) + raise CondaError( + message, + url=url, + target_path=target_full_path, + content_length=content_length, + downloaded_bytes=streamed_bytes, + ) + # exit context manager, renaming target to target_full_path + + +@contextmanager +def download_partial_file( + target_full_path: str | Path, *, url: str, sha256: str, md5: str, size: int +): + """ + Create or open locked partial download file, moving onto target_full_path + when finished. Preserve partial file on exception. + """ + target_full_path = Path(target_full_path) + parent = target_full_path.parent + name = Path(target_full_path).name + partial_name = f"{name}{PARTIAL_EXTENSION}" + partial_path = parent / partial_name + + # read+ to open file, not truncate existing, or write+ to create file, + # truncate existing. + partial_download = partial_path.exists() + mode = "r+b" if partial_download else "w+b" + + def check(target): + target.seek(0) + if md5 or sha256: + checksum_type = "sha256" if sha256 else "md5" + checksum = sha256 if sha256 else md5 + try: + checksum_bytes = bytes.fromhex(checksum) + except (ValueError, TypeError) as exc: + raise CondaValueError(exc) from exc + hasher = hashlib.new(checksum_type) + target.seek(0) + while read := target.read(CHUNK_SIZE): + hasher.update(read) + + if hasher.digest() != checksum_bytes: + actual_checksum = hasher.hexdigest() + log.debug( + "%s mismatch for download: %s (%s != %s)", + checksum_type, + url, + actual_checksum, + checksum, + ) + raise ChecksumMismatchError( + url, + target_full_path, + checksum_type, + checksum, + actual_checksum, + partial_download=partial_download, + ) + if size is not None: + actual_size = os.fstat(target.fileno()).st_size + if actual_size != size: + log.debug( + "size mismatch for download: %s (%s != %s)", + url, + actual_size, + size, + ) + raise ChecksumMismatchError( + url, + target_full_path, + "size", + size, + actual_size, + partial_download=partial_download, + ) + + try: + with partial_path.open(mode=mode) as partial, lock(partial): + yield partial + check(partial) + except HTTPError as e: # before conda error handler wrapper + # Don't keep `.partial` for errors like 404 not found, or 'Range not + # Satisfiable' that will never succeed + try: + status_code = e.response.status_code + except AttributeError: + status_code = None + if isinstance(status_code, int) and 400 <= status_code < 500: + partial_path.unlink() + raise + except ChecksumMismatchError: + partial_path.unlink() + raise + + try: + partial_path.rename(target_full_path) + except OSError: # Windows doesn't rename onto existing paths + target_full_path.unlink() + partial_path.rename(target_full_path) + + +@contextmanager +def download_http_errors(url: str): + """Exception translator used inside download()""" + # This complex exception translation strategy is reminiscent of def + # conda_http_errors(url, repodata_fn): in gateways/repodata + + try: + yield + + except ConnectionResetError as e: + log.debug(f"{e}, trying again") + # where does retry happen? + raise + + except RequestsProxyError: + raise ProxyError() # see #3962 + + except InvalidSchema as e: + if "SOCKS" in str(e): + message = dals( + """ + Requests has identified that your current working environment is configured + to use a SOCKS proxy, but pysocks is not installed. To proceed, remove your + proxy configuration, run `conda install pysocks`, and then you can re-enable + your proxy configuration. + """ + ) + raise CondaDependencyError(message) + else: + raise + + except SSLError as e: + # SSLError: either an invalid certificate or OpenSSL is unavailable + try: + import ssl # noqa: F401 + except ImportError: + raise CondaSSLError( + dals( + f""" + OpenSSL appears to be unavailable on this machine. OpenSSL is required to + download and install packages. + + Exception: {e} + """ + ) + ) + else: + raise CondaSSLError( + dals( + f""" + Encountered an SSL error. Most likely a certificate verification issue. + + Exception: {e} + """ + ) + ) + + except (ConnectionError, HTTPError) as e: + status_code = getattr(e.response, "status_code", None) + + if status_code == 403: + channel = Channel(url) + if channel.token: + help_message = dals( + f""" + The token given for the URL has insufficient permissions to access this resource. + + You may not have the required permissions to access this channel or package. + Consider requesting access from the channel owner. + + Use `conda config --show` to view your configuration's current state. + Further configuration help can be found at <{join_url(CONDA_HOMEPAGE_URL, "docs/config.html")}>. + """ + ) + elif context.channel_alias.location in url: + help_message = dals( + f""" + The remote server has indicated you do not have permission to access this resource. + + This may mean: + (a) You are not authenticated. Check if authentication is required for this channel + and verify your credentials are correctly configured. + (b) You do not have access to this private channel or package. Contact the + channel owner to request access. + + Further configuration help can be found at <{join_url(CONDA_HOMEPAGE_URL, "docs/config.html")}>. + """ + ) + else: + help_message = dals( + f""" + You do not have permission to access this resource. + + This may indicate: + - The channel requires authentication. Check your credentials. + - You do not have access to this private channel or package. + + You will need to modify your conda configuration to proceed. + Use `conda config --show` to view your configuration's current state. + Further configuration help can be found at <{join_url(CONDA_HOMEPAGE_URL, "docs/config.html")}>. + """ + ) + + elif status_code == 401: + channel = Channel(url) + if channel.token: + help_message = dals( + f""" + The token given for the URL is invalid. + + You will need to adjust your conda configuration to proceed. + + Use `conda config --show` to view your configuration's current state. + Further configuration help can be found at <{join_url(CONDA_HOMEPAGE_URL, "docs/config.html")}>. + """ + ) + elif context.channel_alias.location in url: + help_message = dals( + f""" + The remote server has indicated you are using invalid credentials for this channel. + + You may need to: + (a) Remove or update the invalid token from your configuration, or + (b) Provide conda with a valid token directly. + + Further configuration help can be found at <{join_url(CONDA_HOMEPAGE_URL, "docs/config.html")}>. + """ + ) + else: + help_message = dals( + f""" + The credentials you have provided for this URL are invalid. + + You will need to modify your conda configuration to proceed. + Use `conda config --show` to view your configuration's current state. + Further configuration help can be found at <{join_url(CONDA_HOMEPAGE_URL, "docs/config.html")}>. + """ + ) + + else: + help_message = dals( + """ + An HTTP error occurred when trying to retrieve this URL. + HTTP errors are often intermittent, and a simple retry will get you on your way. + """ + ) + + raise CondaHTTPError( + help_message, + url, + status_code, + getattr(e.response, "reason", None), + getattr(e.response, "elapsed", None), + e.response, + caused_by=e, + ) + + +def download_text(url): + if not context.ssl_verify: + disable_ssl_verify_warning() + with download_http_errors(url): + timeout = context.remote_connect_timeout_secs, context.remote_read_timeout_secs + session = get_session(url) + response = session.get( + url, stream=True, proxies=session.proxies, timeout=timeout + ) + if log.isEnabledFor(DEBUG): + log.debug(stringify(response, content_max_len=256)) + response.raise_for_status() + return response.text + + +class TmpDownload: + """Context manager to handle downloads to a tempfile.""" + + def __init__(self, url, verbose=True): + self.url = url + self.verbose = verbose + + def __enter__(self): + if "://" not in self.url: + # if we provide the file itself, no tmp dir is created + self.tmp_dir = None + return self.url + else: + self.tmp_dir = tempfile.mkdtemp() + dst = join(self.tmp_dir, basename(self.url)) + download(self.url, dst) + return dst + + def __exit__(self, exc_type, exc_value, traceback): + if self.tmp_dir: + rm_rf(self.tmp_dir) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/session.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/session.py new file mode 100644 index 0000000000000000000000000000000000000000..869eef6d817a67968c35fd60ae9c19b599e5215c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/connection/session.py @@ -0,0 +1,435 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Requests session configured with all accepted scheme adapters.""" + +from __future__ import annotations + +from fnmatch import fnmatch +from functools import cache +from logging import getLogger +from threading import local +from typing import TYPE_CHECKING + +from ... import CondaError +from ...auxlib.ish import dals +from ...base.constants import CONDA_HOMEPAGE_URL +from ...base.context import context +from ...common.url import ( + add_username_and_password, + get_proxy_username_and_pass, + split_anaconda_token, + urlparse, +) +from ...exceptions import OfflineError, PluginError, ProxyError +from ...models.channel import Channel +from ..anaconda_client import read_binstar_tokens +from . import ( + AuthBase, + BaseAdapter, + CaseInsensitiveDict, + Retry, + Session, + _basic_auth_str, + extract_cookies_to_jar, + get_auth_from_url, + get_netrc_auth, +) +from .adapters.ftp import FTPAdapter +from .adapters.http import HTTPAdapter +from .adapters.localfs import LocalFSAdapter +from .adapters.s3 import S3Adapter + +if TYPE_CHECKING: + from requests.models import PreparedRequest, Request + +log = getLogger(__name__) +RETRIES = 3 + + +CONDA_SESSION_SCHEMES = frozenset( + ( + "http", + "https", + "ftp", + "s3", + "file", + ) +) + +# Forbidden headers, which should never be set by plugins. Based on +# https://web.archive.org/web/20251124174612/https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header +# (last updated as of November 17, 2025). Set-Cookie is a response header and not a request header, but +# it's semantically invalid, so we include it here. + +FORBIDDEN_HEADERS = frozenset( + [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "date", + "dnt", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "set-cookie", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via", + ] +) +# Headers that override HTTP methods, which are forbidden when they contain the following. +FORBIDDEN_METHOD_OVERRIDE_HEADERS = frozenset( + [ + "x-http-method", + "x-http-method-override", + "x-method-override", + ] +) +FORBIDDEN_HTTP_METHODS = frozenset(["connect", "trace", "track"]) + + +class EnforceUnusedAdapter(BaseAdapter): + def send(self, request: Request, *args, **kwargs): + raise OfflineError( + f"EnforceUnusedAdapter called with url {request.url}.\n" + "This command is using a remote connection in offline mode." + ) + + def close(self): + raise NotImplementedError() + + +def get_channel_name_from_url(url: str) -> str | None: + """ + Given a URL, determine the channel it belongs to and return its name. + """ + return Channel.from_url(url).canonical_name + + +def _validate_plugin_headers(headers: dict) -> None: + """ + Validate plugin-provided headers and raise PluginError if any forbidden + headers are detected. This prevents plugins from compromising conda's + core network stack. + + :param headers: Dictionary of headers to validate + :raises PluginError: If any forbidden headers are detected + """ + for key, value in headers.items(): + key_lower = key.lower() + + if key_lower in FORBIDDEN_HEADERS: + raise PluginError( + f"Plugin attempted to set forbidden header '{key}'. " + "This header is not allowed as it could compromise conda's network stack. " + "See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header" + ) + + if key_lower.startswith("proxy-") or key_lower.startswith("sec-"): + raise PluginError( + f"Plugin attempted to set forbidden header '{key}'. " + "Headers starting with 'Proxy-' or 'Sec-' are not allowed as they could " + "compromise conda's network stack. " + "See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header" + ) + + if key_lower in FORBIDDEN_METHOD_OVERRIDE_HEADERS: + if isinstance(value, str) and value.lower() in FORBIDDEN_HTTP_METHODS: + raise PluginError( + f"Plugin attempted to set header '{key}' with forbidden method '{value}'. " + "This method override is not allowed as it could compromise conda's network stack. " + "See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header" + ) + + +@cache +def get_session(url: str): + """ + Function that determines the correct Session object to be returned + based on the URL that is passed in. + """ + channel_name = get_channel_name_from_url(url) + + # If for whatever reason a channel name can't be determined, (should be unlikely) + # we just return the default session object. + if channel_name is None: + return CondaSession() + + # We ensure here if there are duplicates defined, we choose the last one + channel_settings = {} + for settings in context.channel_settings: + channel = settings.get("channel", "") + if channel == channel_name: + # First we check for exact match + channel_settings = settings + continue + + # If we don't have an exact match, we attempt to match a URL pattern + parsed_url = urlparse(url) + parsed_setting = urlparse(channel) + + # We require that the schemes must be identical to prevent downgrade attacks. + # This includes the case of a scheme-less pattern like "*", which is not allowed. + if parsed_setting.scheme != parsed_url.scheme: + continue + + url_without_schema = parsed_url.netloc + parsed_url.path + pattern = parsed_setting.netloc + parsed_setting.path + if fnmatch(url_without_schema, pattern): + channel_settings = settings + + auth_handler = channel_settings.get("auth", "").strip() or None + + # Return default session object + if auth_handler is None: + return CondaSession() + + auth_handler_cls = context.plugin_manager.get_auth_handler(auth_handler) + + if not auth_handler_cls: + return CondaSession() + + return CondaSession(auth=auth_handler_cls(channel_name)) + + +def get_session_storage_key(auth) -> str: + """ + Function that determines which storage key to use for our CondaSession object caching + """ + if auth is None: + return "default" + + if isinstance(auth, tuple): + return hash(auth) + + auth_type = type(auth) + + return f"{auth_type.__module__}.{auth_type.__qualname__}::{auth.channel_name}" + + +class CondaSessionType(type): + """ + Takes advice from https://github.com/requests/requests/issues/1871#issuecomment-33327847 + and creates one Session instance per thread. + """ + + def __new__(mcs, name, bases, dct): + dct["_thread_local"] = local() + return super().__new__(mcs, name, bases, dct) + + def __call__(cls, **kwargs): + storage_key = get_session_storage_key(kwargs.get("auth")) + + try: + return cls._thread_local.sessions[storage_key] + except AttributeError: + session = super().__call__(**kwargs) + cls._thread_local.sessions = {storage_key: session} + except KeyError: + session = cls._thread_local.sessions[storage_key] = super().__call__( + **kwargs + ) + + return session + + +class CondaSession(Session, metaclass=CondaSessionType): + def __init__( + self, + auth: AuthBase | tuple[str, str] | None = None, + ): + """ + :param auth: Optionally provide ``requests.AuthBase`` compliant objects + """ + super().__init__() + + self.auth = auth or CondaHttpAuth() + + self.proxies.update(context.proxy_servers) + + ssl_context = None + if context.ssl_verify == "truststore": + try: + import ssl + + import truststore + + ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + except ImportError: + raise CondaError( + "The `ssl_verify: truststore` setting is only supported on" + "Python 3.10 or later." + ) + self.verify = True + else: + self.verify = context.ssl_verify + + if context.offline: + unused_adapter = EnforceUnusedAdapter() + self.mount("http://", unused_adapter) + self.mount("https://", unused_adapter) + self.mount("ftp://", unused_adapter) + self.mount("s3://", unused_adapter) + + else: + # Configure retries + retry = Retry( + total=context.remote_max_retries, + backoff_factor=context.remote_backoff_factor, + status_forcelist=[413, 429, 500, 503], + raise_on_status=False, + respect_retry_after_header=False, + ) + http_adapter = HTTPAdapter(max_retries=retry, ssl_context=ssl_context) + self.mount("http://", http_adapter) + self.mount("https://", http_adapter) + self.mount("ftp://", FTPAdapter()) + self.mount("s3://", S3Adapter()) + + self.mount("file://", LocalFSAdapter()) + + self.headers["User-Agent"] = context.user_agent + + if context.client_ssl_cert_key: + self.cert = (context.client_ssl_cert, context.client_ssl_cert_key) + elif context.client_ssl_cert: + self.cert = context.client_ssl_cert + + def prepare_request(self, request: Request) -> PreparedRequest: + # inject headers from plugins if this is a https/http request + url = urlparse(request.url) + if url.scheme in ("https", "http"): + session_headers = context.plugin_manager.get_cached_session_headers( + host=url.netloc + ) + request_headers = context.plugin_manager.get_cached_request_headers( + host=url.netloc, path=url.path + ) + + # Validate plugin headers - raises PluginError if forbidden headers detected + _validate_plugin_headers(session_headers) + _validate_plugin_headers(request_headers) + + request.headers = CaseInsensitiveDict( + { + # hardcoded session headers (self.headers) are injected in super().prepare_request + **session_headers, + **request_headers, + **(request.headers or {}), + } + ) + return super().prepare_request(request) + + @classmethod + def cache_clear(cls): + try: + cls._thread_local.sessions.clear() + except AttributeError: + # AttributeError: thread's session cache has not been initialized + pass + + +class CondaHttpAuth(AuthBase): + # TODO: make this class thread-safe by adding some of the requests.auth.HTTPDigestAuth() code + + def __call__(self, request): + request.url = CondaHttpAuth.add_binstar_token(request.url) + self._apply_basic_auth(request) + request.register_hook("response", self.handle_407) + return request + + @staticmethod + def _apply_basic_auth(request): + # this logic duplicated from Session.prepare_request and PreparedRequest.prepare_auth + url_auth = get_auth_from_url(request.url) + auth = url_auth if any(url_auth) else None + + if auth is None: + # look for auth information in a .netrc file + auth = get_netrc_auth(request.url) + + if isinstance(auth, tuple) and len(auth) == 2: + request.headers["Authorization"] = _basic_auth_str(*auth) + + return request + + @staticmethod + def add_binstar_token(url): + clean_url, token = split_anaconda_token(url) + if not token and context.add_anaconda_token: + for binstar_url, token in read_binstar_tokens().items(): + if clean_url.startswith(binstar_url): + log.debug("Adding anaconda token for url <%s>", clean_url) + from ...models.channel import Channel + + channel = Channel(clean_url) + channel.token = token + return channel.url(with_credentials=True) + return url + + @staticmethod + def handle_407(response, **kwargs): # pragma: no cover + """ + Prompts the user for the proxy username and password and modifies the + proxy in the session object to include it. + + This method is modeled after + * requests.auth.HTTPDigestAuth.handle_401() + * requests.auth.HTTPProxyAuth + * the previous conda.fetch.handle_proxy_407() + + It both adds 'username:password' to the proxy URL, as well as adding a + 'Proxy-Authorization' header. If any of this is incorrect, please file an issue. + + """ + # kwargs = {'verify': True, 'cert': None, 'proxies': {}, 'stream': False, + # 'timeout': (3.05, 60)} + + if response.status_code != 407: + return response + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + response.content + response.close() + + proxies = kwargs.pop("proxies") + + proxy_scheme = urlparse(response.url).scheme + if proxy_scheme not in proxies: + raise ProxyError( + dals( + f""" + Could not find a proxy for {proxy_scheme!r}. See + {CONDA_HOMEPAGE_URL}/docs/html#configure-conda-for-use-behind-a-proxy-server + for more information on how to configure proxies. + """ + ) + ) + + # fix-up proxy_url with username & password + proxy_url = proxies[proxy_scheme] + username, password = get_proxy_username_and_pass(proxy_scheme) + proxy_url = add_username_and_password(proxy_url, username, password) + proxy_authorization_header = _basic_auth_str(username, password) + proxies[proxy_scheme] = proxy_url + kwargs["proxies"] = proxies + + prep = response.request.copy() + extract_cookies_to_jar(prep._cookies, response.request, response.raw) + prep.prepare_cookies(prep._cookies) + prep.headers["Proxy-Authorization"] = proxy_authorization_header + + _response = response.connection.send(prep, **kwargs) + _response.history.append(response) + _response.request = prep + + return _response diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4266b40adef99cc48b7044f395faaf5242ed8d9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/__init__.py @@ -0,0 +1,115 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import os +import sys +from errno import EACCES, EEXIST, ENOENT, ENOTEMPTY, EPERM, errorcode +from logging import getLogger +from os.path import basename, dirname, isdir +from subprocess import CalledProcessError +from time import sleep + +from ...common.compat import on_win +from ...common.constants import TRACE + +log = getLogger(__name__) + +MAX_TRIES = 7 + + +def exp_backoff_fn(fn, *args, **kwargs): + """Mostly for retrying file operations that fail on Windows due to virus scanners""" + max_tries = kwargs.pop("max_tries", MAX_TRIES) + if not on_win: + return fn(*args, **kwargs) + + import random + + # with max_tries = 6, max total time ~= 3.2 sec + # with max_tries = 7, max total time ~= 6.5 sec + + def sleep_some(n, exc): + if n == max_tries - 1: + raise + sleep_time = ((2**n) + random.random()) * 0.1 + caller_frame = sys._getframe(1) + log.log( + TRACE, + "retrying %s/%s %s() in %g sec", + basename(caller_frame.f_code.co_filename), + caller_frame.f_lineno, + fn.__name__, + sleep_time, + ) + sleep(sleep_time) + + for n in range(max_tries): + try: + result = fn(*args, **kwargs) + except OSError as e: + log.log(TRACE, repr(e)) + if e.errno in (EPERM, EACCES): + sleep_some(n, e) + elif e.errno in (ENOENT, ENOTEMPTY): + # errno.ENOENT File not found error / No such file or directory + # errno.ENOTEMPTY OSError(41, 'The directory is not empty') + raise + else: + log.warning( + "Uncaught backoff with errno %s %d", errorcode[e.errno], e.errno + ) + raise + except CalledProcessError as e: + sleep_some(n, e) + else: + return result + + +def mkdir_p(path): + # putting this here to help with circular imports + try: + log.log(TRACE, "making directory %s", path) + if path: + os.makedirs(path) + return isdir(path) and path + except OSError as e: + if e.errno == EEXIST and isdir(path): + return path + else: + raise + + +def mkdir_p_sudo_safe(path): + if isdir(path): + return + base_dir = dirname(path) + if not isdir(base_dir): + mkdir_p_sudo_safe(base_dir) + log.log(TRACE, "making directory %s", path) + try: + os.mkdir(path) + except OSError as e: + if not (e.errno == EEXIST and isdir(path)): + raise + # # per the following issues, removing this code as of 4.6.0: + # # - https://github.com/conda/conda/issues/6569 + # # - https://github.com/conda/conda/issues/6576 + # # - https://github.com/conda/conda/issues/7109 + # if not on_win and os.environ.get('SUDO_UID') is not None: + # uid = int(os.environ['SUDO_UID']) + # gid = int(os.environ.get('SUDO_GID', -1)) + # log.log(TRACE, "chowning %s:%s %s", uid, gid, path) + # os.chown(path, uid, gid) + if not on_win: + # set newly-created directory permissions to 02775 + # https://github.com/conda/conda/issues/6610#issuecomment-354478489 + try: + os.chmod(path, 0o2775) + except OSError as e: + log.log( + TRACE, + "Failed to set permissions to 2775 on %s (%d %d)", + path, + e.errno, + errorcode[e.errno], + ) + pass diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/create.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/create.py new file mode 100644 index 0000000000000000000000000000000000000000..d26f2ab59a4cfbcf3c9e06fc845b3569c1fe92dd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/create.py @@ -0,0 +1,507 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Disk utility functions for creating new files or directories.""" + +import os +import sys +import tempfile +import warnings as _warnings +from errno import EACCES, EPERM, EROFS +from logging import getLogger +from os.path import dirname, isdir, isfile, join, splitext +from shutil import copyfileobj, copystat + +from ... import CondaError +from ...auxlib.ish import dals +from ...base.constants import PACKAGE_CACHE_MAGIC_FILE +from ...base.context import context +from ...common.compat import on_win +from ...common.constants import TRACE +from ...common.path import ensure_pad, expand, win_path_double_escape, win_path_ok +from ...common.serialize import json +from ...deprecations import deprecated +from ...exceptions import ( + BasicClobberError, + CondaOSError, + NoWritableEnvsDirError, + maybe_raise, +) +from ...models.enums import LinkType +from . import mkdir_p +from .delete import rm_rf +from .link import islink, lexists, link, readlink, symlink +from .permissions import make_executable +from .update import touch + + +# we have our own TemporaryDirectory implementation both for historical reasons and because +# using our rm_rf function is more robust than the shutil equivalent +class TemporaryDirectory: + """Create and return a temporary directory. This has the same + behavior as mkdtemp but can be used as a context manager. For + example: + + with TemporaryDirectory() as tmpdir: + ... + + Upon exiting the context, the directory and everything contained + in it are removed. + """ + + # Handle mkdtemp raising an exception + name = None + _closed = False + + def __init__(self, suffix="", prefix="tmp", dir=None): + self.name = tempfile.mkdtemp(suffix, prefix, dir) + + def __repr__(self): + return f"<{self.__class__.__name__} {self.name!r}>" + + def __enter__(self): + return self.name + + def cleanup(self, _warn=False, _warnings=_warnings): + from .delete import rm_rf as _rm_rf + + if self.name and not self._closed: + try: + _rm_rf(self.name) + except (TypeError, AttributeError) as ex: + if "None" not in f"{ex}": + raise + _rm_rf(self.name) + self._closed = True + + def __exit__(self, exc, value, tb): + self.cleanup() + + def __del__(self): + # Issue a ResourceWarning if implicit cleanup needed + self.cleanup(_warn=True) + + +log = getLogger(__name__) +stdoutlog = getLogger("conda.stdoutlog") + +# in __init__.py to help with circular imports +mkdir_p = mkdir_p + +python_entry_point_template = dals( + r""" +# -*- coding: utf-8 -*- +import re +import sys + +from %(module)s import %(import_name)s + +if __name__ == '__main__': + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) + sys.exit(%(func)s()) +""" +) + +application_entry_point_template = dals( + """ +# -*- coding: utf-8 -*- +if __name__ == '__main__': + import os + import sys + args = ["%(source_full_path)s"] + if len(sys.argv) > 1: + args += sys.argv[1:] + os.execv(args[0], args) +""" +) + + +def write_as_json_to_file(file_path, obj): + log.log(TRACE, "writing json to file %s", file_path) + with open(file_path, mode="w", encoding="utf-8") as fo: + json.dump(obj, fo) + + +def create_python_entry_point(target_full_path, python_full_path, module, func): + if lexists(target_full_path): + maybe_raise( + BasicClobberError( + source_path=None, + target_path=target_full_path, + context=context, + ), + context, + ) + + import_name = func.split(".")[0] + pyscript = python_entry_point_template % { + "module": module, + "func": func, + "import_name": import_name, + } + if python_full_path is not None: + from ...core.portability import generate_shebang_for_entry_point + + shebang = generate_shebang_for_entry_point(python_full_path) + else: + shebang = None + + with open(target_full_path, mode="w", encoding="utf-8") as fo: + if shebang is not None: + fo.write(shebang) + fo.write(pyscript) + + if shebang is not None: + make_executable(target_full_path) + + return target_full_path + + +@deprecated("26.3", "26.9") +def create_application_entry_point( + source_full_path, target_full_path, python_full_path +): + # source_full_path: where the entry point file points to + # target_full_path: the location of the new entry point file being created + if lexists(target_full_path): + maybe_raise( + BasicClobberError( + source_path=None, + target_path=target_full_path, + context=context, + ), + context, + ) + + entry_point = application_entry_point_template % { + "source_full_path": win_path_double_escape(source_full_path), + } + if not isdir(dirname(target_full_path)): + mkdir_p(dirname(target_full_path)) + with open(target_full_path, "w") as fo: + if " " in python_full_path: + python_full_path = ensure_pad(python_full_path, '"') + fo.write(f"#!{python_full_path}\n") + fo.write(entry_point) + make_executable(target_full_path) + + +@deprecated("26.3", "26.9") +class ProgressFileWrapper: + def __init__(self, fileobj, progress_update_callback): + self.progress_file = fileobj + self.progress_update_callback = progress_update_callback + self.progress_file_size = max(1, os.fstat(fileobj.fileno()).st_size) + self.progress_max_pos = 0 + + def __getattr__(self, name): + return getattr(self.progress_file, name) + + def __setattr__(self, name, value): + if name.startswith("progress_"): + super().__setattr__(name, value) + else: + setattr(self.progress_file, name, value) + + def read(self, size=-1): + data = self.progress_file.read(size) + self.progress_update() + return data + + def progress_update(self): + pos = max(self.progress_max_pos, self.progress_file.tell()) + pos = min(pos, self.progress_file_size) + self.progress_max_pos = pos + rel_pos = pos / self.progress_file_size + self.progress_update_callback(rel_pos) + + +@deprecated( + "26.9", + "27.3", + addendum="Use `conda.base.context.context.plugin_manager.extract_package` instead.", +) +def extract_tarball( + tarball_full_path, destination_directory=None, progress_update_callback=None +): + from ...plugins.package_extractors.conda import extract_conda_or_tarball + + return extract_conda_or_tarball(tarball_full_path, destination_directory) + + +def make_menu(prefix, file_path, remove=False): + """ + Create cross-platform menu items (e.g. Windows Start Menu) + + Passes all menu config files %PREFIX%/Menu/*.json to ``menuinst.install``. + ``remove=True`` will remove the menu items. + """ + try: + import menuinst + + menuinst.install( + join(prefix, win_path_ok(file_path)), + remove=remove, + prefix=prefix, + root_prefix=context.root_prefix, + ) + except Exception: + stdoutlog.error("menuinst Exception", exc_info=True) + + +def create_hard_link_or_copy(src, dst): + if islink(src): + message = dals( + f""" + Cannot hard link a soft link + source: {src} + destination: {dst} + """ + ) + raise CondaOSError(message) + + try: + log.log(TRACE, "creating hard link %s => %s", src, dst) + link(src, dst) + except OSError: + log.info("hard link failed, so copying %s => %s", src, dst) + _do_copy(src, dst) + + +def _is_unix_executable_using_ORIGIN(path): + if on_win: + return False + else: + return isfile(path) and not islink(path) and os.access(path, os.X_OK) + + +def _do_softlink(src, dst): + if _is_unix_executable_using_ORIGIN(src): + # for extra details, see https://github.com/conda/conda/pull/4625#issuecomment-280696371 + # We only need to do this copy for executables which have an RPATH containing $ORIGIN + # on Linux, so `is_executable()` is currently overly aggressive. + # A future optimization will be to copy code from @mingwandroid's virtualenv patch. + copy(src, dst) + else: + log.log(TRACE, "soft linking %s => %s", src, dst) + symlink(src, dst) + + +@deprecated("26.3", "26.9") +def create_fake_executable_softlink(src, dst): + if not on_win: + raise RuntimeError("Only runs on Windows.") + src_root, _ = splitext(src) + # TODO: this open will clobber, consider raising + with open(dst, "w") as f: + f.write(f'@echo off\ncall "{src_root}" %*\n') + return dst + + +def copy(src, dst): + # on unix, make sure relative symlinks stay symlinks + if not on_win and islink(src): + src_points_to = readlink(src) + if not src_points_to.startswith("/"): + # copy relative symlinks as symlinks + log.log(TRACE, "soft linking %s => %s", src, dst) + symlink(src_points_to, dst) + return + _do_copy(src, dst) + + +def _do_copy(src, dst): + log.log(TRACE, "copying %s => %s", src, dst) + # src and dst are always files. So we can bypass some checks that shutil.copy does. + # Also shutil.copy calls shutil.copymode, which we can skip because we are explicitly + # calling copystat. + + # Same size as used by Linux cp command (has performance advantage). + # Python's default is 16k. + buffer_size = 4194304 # 4 * 1024 * 1024 == 4 MB + with open(src, "rb") as fsrc: + with open(dst, "wb") as fdst: + copyfileobj(fsrc, fdst, buffer_size) + + try: + copystat(src, dst) + except OSError as e: # pragma: no cover + # shutil.copystat gives a permission denied when using the os.setxattr function + # on the security.selinux property. + log.debug("%r", e) + + +def create_link(src, dst, link_type=LinkType.hardlink, force=False): + if link_type == LinkType.directory: + # A directory is technically not a link. So link_type is a misnomer. + # Naming is hard. + if lexists(dst) and not isdir(dst): + if not force: + maybe_raise(BasicClobberError(src, dst, context), context) + log.info(f"file exists, but clobbering for directory: {dst!r}") + rm_rf(dst) + mkdir_p(dst) + return + + if not lexists(src): + raise CondaError( + f"Cannot link a source that does not exist. {src}\n" + "Running `conda clean --packages` may resolve your problem." + ) + + if lexists(dst): + if not force: + maybe_raise(BasicClobberError(src, dst, context), context) + log.info(f"file exists, but clobbering: {dst!r}") + rm_rf(dst) + + if link_type == LinkType.hardlink: + if isdir(src): + raise CondaError(f"Cannot hard link a directory. {src}") + try: + log.log(TRACE, "hard linking %s => %s", src, dst) + link(src, dst) + except OSError as e: + log.debug("%r", e) + log.debug( + "hard-link failed. falling back to copy\n" + " error: %r\n" + " src: %s\n" + " dst: %s", + e, + src, + dst, + ) + + copy(src, dst) + elif link_type == LinkType.softlink: + _do_softlink(src, dst) + elif link_type == LinkType.copy: + copy(src, dst) + else: + raise CondaError(f"Did not expect linktype={link_type!r}") + + +def compile_multiple_pyc( + python_exe_full_path, py_full_paths, pyc_full_paths, prefix, py_ver +): + py_full_paths = tuple(py_full_paths) + pyc_full_paths = tuple(pyc_full_paths) + if len(py_full_paths) == 0: + return [] + + fd, filename = tempfile.mkstemp() + try: + for f in py_full_paths: + f = os.path.relpath(f, prefix) + if hasattr(f, "encode"): + f = f.encode(sys.getfilesystemencoding(), errors="replace") + os.write(fd, f + b"\n") + os.close(fd) + command = ["-Wi", "-m", "compileall", "-q", "-l", "-i", filename] + # if the python version in the prefix is 3.5+, we have some extra args. + # -j 0 will do the compilation in parallel, with os.cpu_count() cores + if int(py_ver[0]) >= 3 and int(py_ver.split(".")[1]) > 5: + command.extend(["-j", "0"]) + command[0:0] = [python_exe_full_path] + # command[0:0] = ['--cwd', prefix, '--dev', '-p', prefix, python_exe_full_path] + log.log(TRACE, command) + from ..subprocess import any_subprocess + + # from ...common.io import env_vars + # This stack does not maintain its _argparse_args correctly? + # from ...base.context import stack_context_default + # with env_vars({}, stack_context_default): + # stdout, stderr, rc = run_command(Commands.RUN, *command) + stdout, stderr, rc = any_subprocess(command, prefix) + finally: + os.remove(filename) + + created_pyc_paths = [] + for py_full_path, pyc_full_path in zip(py_full_paths, pyc_full_paths): + if not isfile(pyc_full_path): + message = dals( + """ + pyc file failed to compile successfully (run_command failed) + python_exe_full_path: %s + py_full_path: %s + pyc_full_path: %s + compile rc: %s + compile stdout: %s + compile stderr: %s + """ + ) + log.info( + message, + python_exe_full_path, + py_full_path, + pyc_full_path, + rc, + stdout, + stderr, + ) + else: + created_pyc_paths.append(pyc_full_path) + + return created_pyc_paths + + +def create_package_cache_directory(pkgs_dir): + # returns False if package cache directory cannot be created + try: + log.log(TRACE, "creating package cache directory '%s'", pkgs_dir) + sudo_safe = expand(pkgs_dir).startswith(expand("~")) + touch(join(pkgs_dir, PACKAGE_CACHE_MAGIC_FILE), mkdir=True, sudo_safe=sudo_safe) + touch(join(pkgs_dir, "urls"), sudo_safe=sudo_safe) + except OSError as e: + if e.errno in (EACCES, EPERM, EROFS): + log.log(TRACE, "cannot create package cache directory '%s'", pkgs_dir) + return False + else: + raise + return True + + +def create_envs_directory(envs_dir): + # returns False if envs directory cannot be created + + # The magic file being used here could change in the future. Don't write programs + # outside this code base that rely on the presence of this file. + # This value is duplicated in conda.base.context._first_writable_envs_dir(). + envs_dir_magic_file = join(envs_dir, ".conda_envs_dir_test") + try: + log.log(TRACE, "creating envs directory '%s'", envs_dir) + sudo_safe = expand(envs_dir).startswith(expand("~")) + touch(join(envs_dir, envs_dir_magic_file), mkdir=True, sudo_safe=sudo_safe) + except OSError as e: + if e.errno in (EACCES, EPERM, EROFS): + log.log(TRACE, "cannot create envs directory '%s'", envs_dir) + return False + else: + raise + return True + + +def first_writable_envs_dir(create=True): + # Calling this function will *create* an envs directory if one does not already + # exist. Any caller should intend to *use* that directory for *writing*, not just reading. + for envs_dir in context.envs_dirs: + if envs_dir == os.devnull: + continue + + # The magic file being used here could change in the future. Don't write programs + # outside this code base that rely on the presence of this file. + # This value is duplicated in conda.gateways.disk.create.create_envs_directory(). + envs_dir_magic_file = join(envs_dir, ".conda_envs_dir_test") + + if isfile(envs_dir_magic_file): + try: + open(envs_dir_magic_file, "a").close() + return envs_dir + except OSError: + log.log(TRACE, "Tried envs_dir but not writable: %s", envs_dir) + elif create: + was_created = create_envs_directory(envs_dir) + if was_created: + return envs_dir + + raise NoWritableEnvsDirError(context.envs_dirs) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/delete.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/delete.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe2b22ae1770b4164752ca8b2a56a12cec7c178 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/delete.py @@ -0,0 +1,277 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Disk utility functions for deleting files and folders.""" + +from __future__ import annotations + +import fnmatch +import os +import shutil +import sys +from logging import getLogger +from os.path import ( + abspath, + basename, + dirname, + exists, + isdir, + isfile, + join, + normpath, + split, +) +from subprocess import STDOUT, CalledProcessError, check_output + +from ...base.constants import CONDA_TEMP_EXTENSION +from ...base.context import context +from ...common.compat import on_win +from ...common.constants import TRACE +from . import MAX_TRIES +from .link import islink, lexists +from .permissions import make_writable + +if not on_win: + from shutil import which + + +log = getLogger(__name__) + + +def rmtree(path): + # subprocessing to delete large folders can be quite a bit faster + path = normpath(path) + if on_win: + try: + # the fastest way seems to be using DEL to recursively delete files + # https://www.ghacks.net/2017/07/18/how-to-delete-large-folders-in-windows-super-fast/ + # However, this is not entirely safe, as it can end up following symlinks to folders + # https://superuser.com/a/306618/184799 + # so, we stick with the slower, but hopefully safer way. Maybe if we figured out how + # to scan for any possible symlinks, we could do the faster way. + # out = check_output('DEL /F/Q/S *.* > NUL 2> NUL'.format(path), shell=True, + # stderr=STDOUT, cwd=path) + + out = check_output( + f'RD /S /Q "{path}" > NUL 2> NUL', shell=True, stderr=STDOUT + ) + except: + try: + # Try to delete in Unicode + name = None + from ...auxlib.compat import Utf8NamedTemporaryFile + from ...utils import quote_for_shell + + with Utf8NamedTemporaryFile( + mode="w", suffix=".bat", delete=False + ) as batch_file: + batch_file.write(f"RD /S {quote_for_shell(path)}\n") + batch_file.write("chcp 65001\n") + batch_file.write(f"RD /S {quote_for_shell(path)}\n") + batch_file.write("EXIT 0\n") + name = batch_file.name + # If the above is bugged we can end up deleting hard-drives, so we check + # that 'path' appears in it. This is not bulletproof but it could save you (me). + with open(name) as contents: + content = contents.read() + if path not in content: + raise RuntimeError(f"Path {path} not listed in file {name}") + comspec = os.getenv("COMSPEC") + CREATE_NO_WINDOW = 0x08000000 + # It is essential that we `pass stdout=None, stderr=None, stdin=None` here because + # if we do not, then the standard console handles get attached and chcp affects the + # parent process (and any which share those console handles!) + out = check_output( + [comspec, "/d", "/c", name], + shell=False, + stdout=None, + stderr=None, + stdin=None, + creationflags=CREATE_NO_WINDOW, + ) + + except CalledProcessError as e: + if e.returncode != 5: + log.error( + f"Removing folder {name} the fast way failed. Output was: {out}" + ) + raise + else: + log.debug( + f"removing dir contents the fast way failed. Output was: {out}" + ) + else: + try: + os.makedirs(".empty") + except: + pass + # yes, this looks strange. See + # https://unix.stackexchange.com/a/79656/34459 + # https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html + + if isdir(".empty"): + rsync = which("rsync") + + if rsync: + try: + out = check_output( + [ + rsync, + "-a", + "--force", + "--delete", + join(os.getcwd(), ".empty") + "/", + path + "/", + ], + stderr=STDOUT, + ) + except CalledProcessError: + log.debug( + f"removing dir contents the fast way failed. Output was: {out}" + ) + + shutil.rmtree(".empty") + shutil.rmtree(path) + + +def unlink_or_rename_to_trash(path): + """If files are in use, especially on windows, we can't remove them. + The fallback path is to rename them (but keep their folder the same), + which maintains the file handle validity. See comments at: + https://serverfault.com/a/503769 + """ + try: + make_writable(path) + os.unlink(path) + except OSError: + try: + os.rename(path, path + ".conda_trash") + except OSError: + if on_win: + # on windows, it is important to use the rename program, as just using python's + # rename leads to permission errors when files are in use. + condabin_dir = join(context.conda_prefix, "condabin") + trash_script = join(condabin_dir, "rename_tmp.bat") + if exists(trash_script): + _dirname, _fn = split(path) + dest_fn = path + ".conda_trash" + counter = 1 + while isfile(dest_fn): + dest_fn = dest_fn.splitext[0] + f".conda_trash_{counter}" + counter += 1 + out = "< empty >" + try: + out = check_output( + [ + "cmd.exe", + "/C", + trash_script, + _dirname, + _fn, + basename(dest_fn), + ], + stderr=STDOUT, + ) + except CalledProcessError: + log.debug( + f"renaming file path {path} to trash failed. Output was: {out}" + ) + + else: + log.debug( + f"{trash_script} is missing. Conda was not installed correctly or has been " + "corrupted. Please file an issue on the conda github repo." + ) + log.warning( + f"Could not remove or rename {path}. Please remove this file manually (you " + "may need to reboot to free file handles)" + ) + + +def remove_empty_parent_paths(path): + # recurse to clean up empty folders that were created to have a nested hierarchy + parent_path = dirname(path) + + while isdir(parent_path) and not next(os.scandir(parent_path), None): + os.rmdir(parent_path) + parent_path = dirname(parent_path) + + +def rm_rf(path: str | os.PathLike, clean_empty_parents: bool = False) -> bool: + """ + Completely delete path + max_retries is the number of times to retry on failure. The default is 5. This only applies + to deleting a directory. + If removing path fails and trash is True, files will be moved to the trash directory. + """ + path = abspath(path) + log.log(TRACE, "rm_rf %s", path) + + # attempt to delete the path + if isdir(path) and not islink(path): + backoff_rmdir(path) + elif lexists(path): + unlink_or_rename_to_trash(path) + else: + log.log(TRACE, "rm_rf failed. Not a link, file, or directory: %s", path) + + # post-processing to clean up trash and empty parent paths + if isdir(path) and not islink(path): + delete_trash(path) + if clean_empty_parents: + remove_empty_parent_paths(path) + + if lexists(path): + log.info("rm_rf failed for %s", path) + return False + return True + + +def delete_trash(prefix): + if not prefix: + prefix = sys.prefix + exclude = {"envs", "pkgs"} + for root, dirs, files in os.walk(prefix, topdown=True): + dirs[:] = [d for d in dirs if d not in exclude] + for fn in files: + if fnmatch.fnmatch(fn, "*.conda_trash*") or fnmatch.fnmatch( + fn, "*" + CONDA_TEMP_EXTENSION + ): + filename = join(root, fn) + try: + os.unlink(filename) + remove_empty_parent_paths(filename) + except OSError as e: + log.debug("%r errno %d\nCannot unlink %s.", e, e.errno, filename) + + +def backoff_rmdir(dirpath, max_tries=MAX_TRIES): + if not isdir(dirpath): + return + + try: + rmtree(dirpath) + except: + # we don't really care about errors that much. We'll catch remaining files + # with slower python logic. + pass + + for root, dirs, files in os.walk(dirpath, topdown=False): + for file in files: + unlink_or_rename_to_trash(join(root, file)) + + +def path_is_clean(path): + """Sometimes we can't completely remove a path because files are considered in use + by python (hardlinking confusion). For our tests, it is sufficient that either the + folder doesn't exist, or nothing but temporary file copies are left. + """ + clean = not exists(path) + if not clean: + for root, dirs, fns in os.walk(path): + for fn in fns: + if not ( + fnmatch.fnmatch(fn, "*.conda_trash*") + or fnmatch.fnmatch(fn, "*" + CONDA_TEMP_EXTENSION) + ): + return False + return True diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/link.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/link.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc3d1dde3714ed6957d01aab0d50129b2ebeee8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/link.py @@ -0,0 +1,416 @@ +# Copyright (C) 2012 Anaconda, Inc & Jason R. Coombs +# SPDX-License-Identifier: BSD-3-Clause, MIT +"""Disk utility functions for symlinking files and folders. + +Portions of the code within this module are taken from https://github.com/jaraco/jaraco.windows +which is MIT licensed by Jason R. Coombs. + +https://github.com/jaraco/skeleton/issues/1#issuecomment-285448440 +""" + +import sys +from logging import getLogger +from os import chmod as os_chmod +from os.path import abspath, isdir +from os.path import islink as os_islink +from os.path import lexists as os_lexists + +from ...common.compat import on_win +from ...exceptions import CondaOSError, ParseError + +__all__ = ("islink", "lchmod", "lexists", "link", "readlink", "symlink") + +log = getLogger(__name__) +PYPY = sys.implementation.name == "pypy" + + +try: + from os import lchmod as os_lchmod + + lchmod = os_lchmod +except ImportError: # pragma: no cover + + def lchmod(path, mode): + # On systems that don't allow permissions on symbolic links, skip + # links entirely. + if not islink(path): + os_chmod(path, mode) + + +if not on_win: # pragma: win no cover + from os import link, symlink + + link = link + symlink = symlink + +else: # pragma: unix no cover + from ctypes import windll, wintypes + + CreateHardLink = windll.kernel32.CreateHardLinkW + CreateHardLink.restype = wintypes.BOOL + CreateHardLink.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPVOID] + try: + CreateSymbolicLink = windll.kernel32.CreateSymbolicLinkW + CreateSymbolicLink.restype = wintypes.BOOL + CreateSymbolicLink.argtypes = [ + wintypes.LPCWSTR, + wintypes.LPCWSTR, + wintypes.DWORD, + ] + except AttributeError: + CreateSymbolicLink = None + + def win_hard_link(src, dst): + """Equivalent to os.link, using the win32 CreateHardLink call.""" + if not CreateHardLink(dst, src, None): + raise CondaOSError(f"win32 hard link failed\n src: {src}\n dst: {dst}") + + def win_soft_link(src, dst): + """Equivalent to os.symlink, using the win32 CreateSymbolicLink call.""" + if CreateSymbolicLink is None: + raise CondaOSError("win32 soft link not supported") + if not CreateSymbolicLink(dst, src, isdir(src)): + raise CondaOSError(f"win32 soft link failed\n src: {src}\n dst: {dst}") + + link = win_hard_link + symlink = win_soft_link + + +if not (on_win and PYPY): + from os import readlink + + islink = os_islink + lexists = os_lexists + readlink = readlink + +else: # pragma: no cover + import builtins + import inspect + import sys + from ctypes import POINTER, Structure, byref, c_uint64, cast, windll, wintypes + from os import getcwd + from os.path import isfile + + def islink(path): + """Determine if the given path is a symlink""" + return is_reparse_point(path) and is_symlink(path) + + def lexists(path): + if islink(path): + return True + if isdir(path): + return True + if isfile(path): + return True + return False + + MAX_PATH = 260 + IO_REPARSE_TAG_SYMLINK = 0xA000000C + INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF + FILE_ATTRIBUTE_REPARSE_POINT = 0x400 + NULL = 0 + ERROR_NO_MORE_FILES = 0x12 + + class WIN32_FIND_DATA(Structure): + _fields_ = [ + ("file_attributes", wintypes.DWORD), + ("creation_time", wintypes.FILETIME), + ("last_access_time", wintypes.FILETIME), + ("last_write_time", wintypes.FILETIME), + ("file_size_words", wintypes.DWORD * 2), + ("reserved", wintypes.DWORD * 2), + ("filename", wintypes.WCHAR * MAX_PATH), + ("alternate_filename", wintypes.WCHAR * 14), + ] + + @property + def file_size(self): + return cast(self.file_size_words, POINTER(c_uint64)).contents + + LPWIN32_FIND_DATA = POINTER(WIN32_FIND_DATA) + FindFirstFile = windll.kernel32.FindFirstFileW + FindFirstFile.argtypes = (wintypes.LPWSTR, LPWIN32_FIND_DATA) + FindFirstFile.restype = wintypes.HANDLE + FindNextFile = windll.kernel32.FindNextFileW + FindNextFile.argtypes = (wintypes.HANDLE, LPWIN32_FIND_DATA) + FindNextFile.restype = wintypes.BOOLEAN + INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value + GetFileAttributes = windll.kernel32.GetFileAttributesW + GetFileAttributes.restype = wintypes.DWORD + GetFileAttributes.argtypes = (wintypes.LPWSTR,) + + def handle_nonzero_success(result): + if result == 0: + raise OSError() + + def format_system_message(errno): + """ + Call FormatMessage with a system error number to retrieve + the descriptive error message. + """ + # first some flags used by FormatMessageW + ALLOCATE_BUFFER = 0x100 + FROM_SYSTEM = 0x1000 + + # Let FormatMessageW allocate the buffer (we'll free it below) + # Also, let it know we want a system error message. + flags = ALLOCATE_BUFFER | FROM_SYSTEM + source = None + message_id = errno + language_id = 0 + result_buffer = wintypes.LPWSTR() + buffer_size = 0 + arguments = None + bytes = windll.kernel32.FormatMessageW( + flags, + source, + message_id, + language_id, + byref(result_buffer), + buffer_size, + arguments, + ) + # note the following will cause an infinite loop if GetLastError + # repeatedly returns an error that cannot be formatted, although + # this should not happen. + handle_nonzero_success(bytes) + message = result_buffer.value + windll.kernel32.LocalFree(result_buffer) + return message + + class WindowsError(builtins.WindowsError): + # more info about errors at http://msdn.microsoft.com/en-us/library/ms681381(VS.85).aspx + + def __init__(self, value=None): + if value is None: + value = windll.kernel32.GetLastError() + strerror = format_system_message(value) + args = 0, strerror, None, value + super().__init__(*args) + + @property + def message(self): + return self.strerror + + @property + def code(self): + return self.winerror + + def __str__(self): + return self.message + + def __repr__(self): + return "{self.__class__.__name__}({self.winerror})".format(**vars()) + + def _is_symlink(find_data): + return find_data.reserved[0] == IO_REPARSE_TAG_SYMLINK + + def _patch_path(path): + r""" + Paths have a max length of api.MAX_PATH characters (260). If a target path + is longer than that, it needs to be made absolute and prepended with + \\?\ in order to work with API calls. + See http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx for + details. + """ + if path.startswith("\\\\?\\"): + return path + path = abspath(path) + if not path[1] == ":": + # python doesn't include the drive letter, but \\?\ requires it + path = getcwd()[:2] + path + return "\\\\?\\" + path + + def local_format(string): + """Format the string using variables in the caller's local namespace. + + .. code-block:: pycon + >>> a = 3 + >>> local_format("{a:5}") + ' 3' + """ + context = inspect.currentframe().f_back.f_locals + return string.format_map(context) + + def is_symlink(path): + """Assuming path is a reparse point, determine if it's a symlink.""" + path = _patch_path(path) + try: + return _is_symlink(next(find_files(path))) + except OSError as orig_error: # NOQA + tmpl = "Error accessing {path}: {orig_error.message}" + raise OSError(local_format(tmpl)) + + def find_files(spec): + r""" + A pythonic wrapper around the FindFirstFile/FindNextFile win32 api. + >>> root_files = tuple(find_files(r'c:\*')) + >>> len(root_files) > 1 + True + >>> root_files[0].filename == root_files[1].filename + False + >>> # This test might fail on a non-standard installation + >>> 'Windows' in (fd.filename for fd in root_files) + True + """ + fd = WIN32_FIND_DATA() + handle = FindFirstFile(spec, byref(fd)) + while True: + if handle == INVALID_HANDLE_VALUE: + raise OSError() + yield fd + fd = WIN32_FIND_DATA() + res = FindNextFile(handle, byref(fd)) + if res == 0: # error + error = WindowsError() + if error.code == ERROR_NO_MORE_FILES: + break + else: + raise error + # todo: how to close handle when generator is destroyed? + # hint: catch GeneratorExit + windll.kernel32.FindClose(handle) + + def is_reparse_point(path): + """ + Determine if the given path is a reparse point. + Return False if the file does not exist or the file attributes cannot + be determined. + """ + res = GetFileAttributes(path) + return res != INVALID_FILE_ATTRIBUTES and bool( + res & FILE_ATTRIBUTE_REPARSE_POINT + ) + + OPEN_EXISTING = 3 + FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 + FILE_FLAG_BACKUP_SEMANTICS = 0x2000000 + FSCTL_GET_REPARSE_POINT = 0x900A8 + LPDWORD = POINTER(wintypes.DWORD) + LPOVERLAPPED = wintypes.LPVOID + # VOLUME_NAME_DOS = 0 + + class SECURITY_ATTRIBUTES(Structure): + _fields_ = ( + ("length", wintypes.DWORD), + ("p_security_descriptor", wintypes.LPVOID), + ("inherit_handle", wintypes.BOOLEAN), + ) + + LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES) + + CreateFile = windll.kernel32.CreateFileW + CreateFile.argtypes = ( + wintypes.LPWSTR, + wintypes.DWORD, + wintypes.DWORD, + LPSECURITY_ATTRIBUTES, + wintypes.DWORD, + wintypes.DWORD, + wintypes.HANDLE, + ) + CreateFile.restype = wintypes.HANDLE + + CloseHandle = windll.kernel32.CloseHandle + CloseHandle.argtypes = (wintypes.HANDLE,) + CloseHandle.restype = wintypes.BOOLEAN + + from ctypes import Array, c_byte, c_ulong, c_ushort, create_string_buffer, sizeof + + class REPARSE_DATA_BUFFER(Structure): + _fields_ = [ + ("tag", c_ulong), + ("data_length", c_ushort), + ("reserved", c_ushort), + ("substitute_name_offset", c_ushort), + ("substitute_name_length", c_ushort), + ("print_name_offset", c_ushort), + ("print_name_length", c_ushort), + ("flags", c_ulong), + ("path_buffer", c_byte * 1), + ] + + def get_print_name(self): + wchar_size = sizeof(wintypes.WCHAR) + arr_typ = wintypes.WCHAR * (self.print_name_length // wchar_size) + data = byref(self.path_buffer, self.print_name_offset) + return cast(data, POINTER(arr_typ)).contents.value + + def get_substitute_name(self): + wchar_size = sizeof(wintypes.WCHAR) + arr_typ = wintypes.WCHAR * (self.substitute_name_length // wchar_size) + data = byref(self.path_buffer, self.substitute_name_offset) + return cast(data, POINTER(arr_typ)).contents.value + + def readlink(link): + """Return a string representing the path to which the symbolic link points. + + readlink(link) -> target + """ + handle = CreateFile( + link, + 0, + 0, + None, + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, + None, + ) + + if handle == INVALID_HANDLE_VALUE: + raise OSError() + + res = reparse_DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, None, 10240) + + bytes = create_string_buffer(res) + p_rdb = cast(bytes, POINTER(REPARSE_DATA_BUFFER)) + rdb = p_rdb.contents + if not rdb.tag == IO_REPARSE_TAG_SYMLINK: + raise ParseError("Expected IO_REPARSE_TAG_SYMLINK, but got %d" % rdb.tag) + + handle_nonzero_success(CloseHandle(handle)) + return rdb.get_substitute_name() + + DeviceIoControl = windll.kernel32.DeviceIoControl + DeviceIoControl.argtypes = [ + wintypes.HANDLE, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + LPDWORD, + LPOVERLAPPED, + ] + DeviceIoControl.restype = wintypes.BOOL + + def reparse_DeviceIoControl( + device, io_control_code, in_buffer, out_buffer, overlapped=None + ): + if overlapped is not None: + raise NotImplementedError("overlapped handles not yet supported") + + if isinstance(out_buffer, int): + out_buffer = create_string_buffer(out_buffer) + + in_buffer_size = len(in_buffer) if in_buffer is not None else 0 + out_buffer_size = len(out_buffer) + if not isinstance(out_buffer, Array): + raise TypeError("out_buffer must be Array") + + returned_bytes = wintypes.DWORD() + + res = DeviceIoControl( + device, + io_control_code, + in_buffer, + in_buffer_size, + out_buffer, + out_buffer_size, + returned_bytes, + overlapped, + ) + + handle_nonzero_success(res) + handle_nonzero_success(returned_bytes) + return out_buffer[: returned_bytes.value] diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/lock.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/lock.py new file mode 100644 index 0000000000000000000000000000000000000000..8abf8e0dd621da81135a8ae4d13497d5c9ab6686 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/lock.py @@ -0,0 +1,95 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Record locking to manage potential repodata / repodata metadata file contention +between conda processes. Try to acquire a lock on a single byte in the metadat +file; modify both files; then release the lock. +""" + +import time +import warnings +from contextlib import contextmanager + +from ...base.context import context +from ...exceptions import LockError + +LOCK_BYTE = 21 # mamba interop +LOCK_ATTEMPTS = 10 +LOCK_SLEEP = 1 + + +@contextmanager +def _lock_noop(fd, lock_attempts): + """When locking is not available.""" + yield + + +try: # pragma: no cover + import msvcrt + + @contextmanager + def _lock_impl(fd, lock_attempts): # type: ignore + tell = fd.tell() + fd.seek(LOCK_BYTE) + try: + msvcrt.locking(fd.fileno(), msvcrt.LK_LOCK, 1) # type: ignore + except OSError: + raise LockError("Failed to acquire lock.") + else: + try: + fd.seek(tell) + yield + finally: + fd.seek(LOCK_BYTE) + try: + msvcrt.locking(fd.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore + except OSError: + raise LockError("Failed to release lock.") + + +except ImportError: + try: + import fcntl + except ImportError: # pragma: no cover + # "fcntl Availibility: not Emscripten, not WASI." + warnings.warn("file locking not available") + + _lock_impl = _lock_noop # type: ignore + + else: + + class _lock_impl: + def __init__(self, fd, lock_attempts): + self.fd = fd + self.lock_attempts = lock_attempts + + def __enter__(self): + for attempt in range(self.lock_attempts): + try: + # msvcrt locking does something similar + fcntl.lockf( + self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 1, LOCK_BYTE + ) + break + except OSError: + if attempt > self.lock_attempts - 2: + raise LockError("Failed to acquire lock.") + time.sleep(LOCK_SLEEP) + + def __exit__(self, *exc): + try: + fcntl.lockf(self.fd, fcntl.LOCK_UN, 1, LOCK_BYTE) + except OSError: + raise LockError("Failed to release lock.") + + +def lock(fd, *, lock_attempts=LOCK_ATTEMPTS): + if not context.no_lock: + # locking required for jlap, now default for all + return _lock_impl(fd, lock_attempts) + return _lock_noop(fd, lock_attempts) + + +def locking_supported(): + "Return a bool to report whether file locking is supported or not" + return _lock_impl is not _lock_noop diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/permissions.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..49a3ba38dfb6ca249fcdc1fda854b6fa6eaf3648 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/permissions.py @@ -0,0 +1,88 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Disk utility functions for modifying file and directory permissions.""" + +from errno import EACCES, ENOENT, EPERM, EROFS +from itertools import chain +from logging import getLogger +from os import X_OK, access, chmod, lstat, walk +from os.path import isdir, isfile, join +from stat import S_IEXEC, S_IMODE, S_ISDIR, S_ISREG, S_IWRITE, S_IXGRP, S_IXOTH, S_IXUSR + +from ...common.compat import on_win +from ...common.constants import TRACE +from . import MAX_TRIES, exp_backoff_fn +from .link import islink, lchmod + +log = getLogger(__name__) + + +def make_writable(path): + try: + mode = lstat(path).st_mode + if S_ISDIR(mode): + chmod(path, S_IMODE(mode) | S_IWRITE | S_IEXEC) + elif islink(path): + lchmod(path, S_IMODE(mode) | S_IWRITE) + elif S_ISREG(mode): + chmod(path, S_IMODE(mode) | S_IWRITE) + else: + log.debug("path cannot be made writable: %s", path) + return True + except Exception as e: + eno = getattr(e, "errno", None) + if eno in (ENOENT,): + log.debug("tried to make writable, but didn't exist: %s", path) + raise + elif eno in (EACCES, EPERM, EROFS): + log.debug("tried make writable but failed: %s\n%r", path, e) + return False + else: + log.warning("Error making path writable: %s\n%r", path, e) + raise + + +def make_read_only(path): + mode = lstat(path).st_mode + if S_ISDIR(mode): + chmod(path, S_IMODE(mode) & ~S_IWRITE) + elif islink(path): + lchmod(path, S_IMODE(mode) & ~S_IWRITE) + elif S_ISREG(mode): + chmod(path, S_IMODE(mode) & ~S_IWRITE) + else: + log.debug("path cannot be made read only: %s", path) + return True + + +def recursive_make_writable(path, max_tries=MAX_TRIES): + # The need for this function was pointed out at + # https://github.com/conda/conda/issues/3266#issuecomment-239241915 + # Especially on windows, file removal will often fail because it is marked read-only + if isdir(path): + for root, dirs, files in walk(path): + for path in chain.from_iterable((files, dirs)): + try: + exp_backoff_fn(make_writable, join(root, path), max_tries=max_tries) + except OSError as e: + if e.errno == ENOENT: + log.debug("no such file or directory: %s", path) + else: + raise + else: + exp_backoff_fn(make_writable, path, max_tries=max_tries) + + +def make_executable(path): + if isfile(path): + mode = lstat(path).st_mode + log.log(TRACE, "chmod +x %s", path) + chmod(path, S_IMODE(mode) | S_IXUSR | S_IXGRP | S_IXOTH) + else: + log.error("Cannot make path '%s' executable", path) + + +def is_executable(path): + if isfile(path): # for now, leave out `and not islink(path)` + return path.endswith((".exe", ".bat")) if on_win else access(path, X_OK) + return False diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/read.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/read.py new file mode 100644 index 0000000000000000000000000000000000000000..fd1adaa8c3ddce8e674a1f5a88601043daa6b9f6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/read.py @@ -0,0 +1,257 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Disk utility functions for reading and processing file contents.""" + +from __future__ import annotations + +import hashlib +import os +from base64 import b64encode +from collections import namedtuple +from errno import ENOENT +from functools import partial +from itertools import chain +from logging import getLogger +from os.path import isdir, isfile, join # noqa +from pathlib import Path +from typing import TYPE_CHECKING + +from ...auxlib.collection import first +from ...auxlib.compat import shlex_split_unicode +from ...auxlib.ish import dals +from ...base.constants import PREFIX_PLACEHOLDER +from ...common.compat import open_utf8 +from ...common.serialize import json +from ...deprecations import deprecated +from ...exceptions import CondaUpgradeError, CondaVerificationError, PathNotFoundError +from ...models.channel import Channel +from ...models.enums import FileMode, PathEnum +from ...models.package_info import PackageInfo, PackageMetadata +from ...models.records import PathDataV1, PathsData +from .create import TemporaryDirectory +from .link import islink, lexists # noqa + +if TYPE_CHECKING: + from typing import Literal + +log = getLogger(__name__) + +listdir = lambda d: list(entry.name for entry in os.scandir(d)) + + +def yield_lines(path): + """Generator function for lines in file. Empty generator if path does not exist. + + Args: + path (str): path to file + + Returns: + iterator: each line in file, not starting with '#' + + """ + try: + path = Path(path) + with path.open() as f: + for line in f: + line = line.strip() + if line and not line.startswith("#"): + yield line + except FileNotFoundError: + pass + except OSError as e: + if e.errno == ENOENT: + pass + else: + raise + + +def compute_sum(path: str | os.PathLike, algo: Literal["md5", "sha256"]) -> str: + path = Path(path) + if not path.is_file(): + raise PathNotFoundError(path) + + # FUTURE: Python 3.11+, replace with hashlib.file_digest + hasher = hashlib.new(algo) + with path.open("rb") as fh: + for chunk in iter(partial(fh.read, 8192), b""): + hasher.update(chunk) + return hasher.hexdigest() + + +# #################################################### +# functions supporting read_package_info() +# #################################################### + + +def read_package_info(record, package_cache_record): + epd = package_cache_record.extracted_package_dir + icondata = read_icondata(epd) + package_metadata = read_package_metadata(epd) + paths_data = read_paths_json(epd) + + return PackageInfo( + extracted_package_dir=epd, + package_tarball_full_path=package_cache_record.package_tarball_full_path, + channel=Channel(record.channel_name or record.channel), + repodata_record=record, + url=package_cache_record.url, + icondata=icondata, + package_metadata=package_metadata, + paths_data=paths_data, + ) + + +def read_index_json(extracted_package_directory): + with open_utf8(join(extracted_package_directory, "info", "index.json")) as fi: + return json.load(fi) + + +def read_index_json_from_tarball(package_tarball_full_path): + import conda_package_handling.api + + with TemporaryDirectory() as tmpdir: + conda_package_handling.api.extract(package_tarball_full_path, tmpdir, "info") + with open_utf8(join(tmpdir, "info", "index.json")) as f: + json_data = json.load(f) + return json_data + + +def read_repodata_json(extracted_package_directory): + with open_utf8( + join(extracted_package_directory, "info", "repodata_record.json") + ) as fi: + return json.load(fi) + + +def read_icondata(extracted_package_directory): + icon_file_path = join(extracted_package_directory, "info", "icon.png") + if isfile(icon_file_path): + with open_utf8(icon_file_path, "rb") as f: + data = f.read() + return b64encode(data).decode("utf-8") + else: + return None + + +def read_package_metadata(extracted_package_directory): + def _paths(): + yield join(extracted_package_directory, "info", "link.json") + yield join(extracted_package_directory, "info", "package_metadata.json") + + path = first(_paths(), key=isfile) + if not path: + return None + else: + with open_utf8(path) as f: + data = json.loads(f.read()) + if data.get("package_metadata_version") != 1: + raise CondaUpgradeError( + dals( + """ + The current version of conda is too old to install this package. (This version + only supports link.json schema version 1.) Please update conda to install + this package. + """ + ) + ) + package_metadata = PackageMetadata(**data) + return package_metadata + + +def read_paths_json(extracted_package_directory): + info_dir = join(extracted_package_directory, "info") + paths_json_path = join(info_dir, "paths.json") + if isfile(paths_json_path): + with open_utf8(paths_json_path) as paths_json: + data = json.load(paths_json) + if data.get("paths_version") != 1: + raise CondaUpgradeError( + dals( + """ + The current version of conda is too old to install this package. (This version + only supports paths.json schema version 1.) Please update conda to install + this package.""" + ) + ) + paths_data = PathsData( + paths_version=1, + paths=(PathDataV1(**f) for f in data["paths"]), + ) + else: + has_prefix_files = read_has_prefix(join(info_dir, "has_prefix")) + no_link = read_no_link(info_dir) + + def read_files_file(): + files_path = join(info_dir, "files") + for f in ( + ln for ln in (line.strip() for line in yield_lines(files_path)) if ln + ): + path_info = {"_path": f} + if f in has_prefix_files.keys(): + path_info["prefix_placeholder"] = has_prefix_files[f][0] + path_info["file_mode"] = has_prefix_files[f][1] + if f in no_link: + path_info["no_link"] = True + if islink(join(extracted_package_directory, f)): + path_info["path_type"] = PathEnum.softlink + else: + path_info["path_type"] = PathEnum.hardlink + yield PathDataV1(**path_info) + + paths = tuple(read_files_file()) + paths_data = PathsData( + paths_version=0, + paths=paths, + ) + return paths_data + + +def read_has_prefix(path): + """Reads `has_prefix` file and return dict mapping filepaths to tuples(placeholder, FileMode). + + A line in `has_prefix` contains one of: + * filepath + * placeholder mode filepath + + Mode values are one of: + * text + * binary + """ + ParseResult = namedtuple("ParseResult", ("placeholder", "filemode", "filepath")) + + def parse_line(line): + # placeholder, filemode, filepath + parts = tuple(x.strip("\"'") for x in shlex_split_unicode(line, posix=False)) + if len(parts) == 1: + return ParseResult(PREFIX_PLACEHOLDER, FileMode.text, parts[0]) + elif len(parts) == 3: + return ParseResult(parts[0], FileMode(parts[1]), parts[2]) + else: + raise CondaVerificationError(f"Invalid has_prefix file at path: {path}") + + parsed_lines = (parse_line(line) for line in yield_lines(path)) + return {pr.filepath: (pr.placeholder, pr.filemode) for pr in parsed_lines} + + +def read_no_link(info_dir): + return set( + chain( + yield_lines(join(info_dir, "no_link")), + yield_lines(join(info_dir, "no_softlink")), + ) + ) + + +def read_soft_links(extracted_package_directory, files): + return tuple(f for f in files if islink(join(extracted_package_directory, f))) + + +@deprecated( + "25.9", + "26.3", + addendum="Use 'conda.plugins.prefix_data_loaders.pypi.pkg_format.read_python_record'", +) +def read_python_record(prefix_path, anchor_file, python_version): + from ...plugins.prefix_data_loaders.pypi.pkg_format import read_python_record + + return read_python_record(prefix_path, anchor_file, python_version) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/test.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/test.py new file mode 100644 index 0000000000000000000000000000000000000000..678332194228bc882a7d7831aeada1513f44553c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/test.py @@ -0,0 +1,96 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Disk utility functions testing path properties (e.g., writable, hardlinks, softlinks, etc.).""" + +from functools import cache +from logging import getLogger +from os import W_OK, access +from os.path import basename, dirname, isdir, isfile, join +from uuid import uuid4 + +from ...base.constants import PREFIX_MAGIC_FILE +from ...common.constants import TRACE +from ...common.path import expand +from ...deprecations import deprecated +from ...models.enums import LinkType +from .create import create_link +from .delete import rm_rf +from .link import islink, lexists + +log = getLogger(__name__) + + +def file_path_is_writable(path) -> bool: + path = expand(path) + log.log(TRACE, "checking path is writable %s", path) + if isdir(dirname(path)): + path_existed = lexists(path) + try: + fh = open(path, "a+") + except OSError as e: + log.debug(e) + return False + else: + fh.close() + if not path_existed: + rm_rf(path) + return True + else: + # TODO: probably won't work well on Windows + return access(path, W_OK) + + +@cache +def hardlink_supported(source_file, dest_dir): + test_file = join(dest_dir, f".tmp.{basename(source_file)}.{str(uuid4())[:8]}") + if not isfile(source_file): + raise OSError(f"Path {source_file} is not a file") + if not isdir(dest_dir): + raise OSError(f"Path {dest_dir} is not a directory") + if lexists(test_file): + rm_rf(test_file) + if lexists(test_file): + raise OSError(f"{test_file} should not exist anymore") + try: + # BeeGFS is a file system that does not support hard links between files in different + # directories. Sometimes a soft link will be created with the hard link system call. + create_link(source_file, test_file, LinkType.hardlink, force=True) + is_supported = not islink(test_file) + if is_supported: + log.log(TRACE, "hard link supported for %s => %s", source_file, dest_dir) + else: + log.log( + TRACE, "hard link IS NOT supported for %s => %s", source_file, dest_dir + ) + return is_supported + except OSError: + log.log(TRACE, "hard link IS NOT supported for %s => %s", source_file, dest_dir) + return False + finally: + rm_rf(test_file) + + +@cache +def softlink_supported(source_file, dest_dir): + # On Windows, softlink creation is restricted to Administrative users by default. It can + # optionally be enabled for non-admin users through explicit registry modification. + log.log(TRACE, "checking soft link capability for %s => %s", source_file, dest_dir) + test_path = join(dest_dir, ".tmp." + basename(source_file)) + if not isfile(source_file): + raise OSError(f"Path {source_file} is not a file") + if not isdir(dest_dir): + raise OSError(f"Path {dest_dir} is not a directory") + if lexists(test_path): + raise OSError(f"{test_path} should not exist") + try: + create_link(source_file, test_path, LinkType.softlink, force=True) + return islink(test_path) + except OSError: + return False + finally: + rm_rf(test_path) + + +@deprecated("25.9", "26.3", addendum="Use PrefixData.is_environment()") +def is_conda_environment(prefix): + return isfile(join(prefix, PREFIX_MAGIC_FILE)) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/update.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/update.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc403919f54c9a0bf745b6c5cd9d70457337d4a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/disk/update.py @@ -0,0 +1,173 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Disk utility functions for modifying existing files or directories.""" + +from __future__ import annotations + +import os +import re +import tempfile +from contextlib import contextmanager +from errno import EINVAL, EPERM, EXDEV +from logging import getLogger +from os.path import basename, dirname, exists, isdir, join, split +from shutil import move +from subprocess import PIPE, Popen + +from ...base.constants import DRY_RUN_PREFIX +from ...base.context import context +from ...common.compat import on_win +from ...common.constants import TRACE +from ...common.path import expand +from ...exceptions import NotWritableError +from . import exp_backoff_fn, mkdir_p, mkdir_p_sudo_safe +from .delete import rm_rf +from .link import lexists + +log = getLogger(__name__) + +SHEBANG_REGEX = re.compile(rb"^(#!((?:\\ |[^ \n\r])+)(.*))") + + +class CancelOperation(Exception): + pass + + +def update_file_in_place_as_binary(file_full_path, callback): + # callback should be a callable that takes one positional argument, which is the + # content of the file before updating + # this method updates the file in-place, without releasing the file lock + fh = None + try: + fh = exp_backoff_fn(open, file_full_path, "rb+") + log.log(TRACE, "in-place update path locked for %s", file_full_path) + data = fh.read() + fh.seek(0) + try: + fh.write(callback(data)) + fh.truncate() + return True + except CancelOperation: + pass + finally: + if fh: + fh.close() + return False + + +def rename(source_path, destination_path, force=False): + if lexists(destination_path) and force: + rm_rf(destination_path) + if lexists(source_path): + log.log(TRACE, "renaming %s => %s", source_path, destination_path) + try: + os.rename(source_path, destination_path) + except OSError as e: + if ( + on_win + and dirname(source_path) == dirname(destination_path) + and os.path.isfile(source_path) + ): + condabin_dir = join(context.conda_prefix, "condabin") + rename_script = join(condabin_dir, "rename_tmp.bat") + if exists(rename_script): + _dirname, _src_fn = split(source_path) + _dest_fn = basename(destination_path) + p = Popen( + ["cmd.exe", "/C", rename_script, _dirname, _src_fn, _dest_fn], + stdout=PIPE, + stderr=PIPE, + ) + stdout, stderr = p.communicate() + else: + log.debug( + f"{rename_script} is missing. Conda was not installed correctly or has been " + "corrupted. Please file an issue on the conda github repo." + ) + elif e.errno in (EINVAL, EXDEV, EPERM): + # https://github.com/conda/conda/issues/6811 + # https://github.com/conda/conda/issues/6711 + log.log( + TRACE, + "Could not rename %s => %s due to errno [%s]. Falling back" + " to copy/unlink", + source_path, + destination_path, + e.errno, + ) + # https://github.com/moby/moby/issues/25409#issuecomment-238537855 + # shutil.move() falls back to copy+unlink + move(source_path, destination_path) + else: + raise + else: + log.log(TRACE, "cannot rename; source path does not exist '%s'", source_path) + + +@contextmanager +def rename_context(source: str, destination: str | None = None, dry_run: bool = False): + """ + Used for removing a directory when there are dependent actions (i.e. you need to ensure + other actions succeed before removing it). + + Example: + with rename_context(directory): + # Do dependent actions here + """ + if destination is None: + destination = tempfile.mkdtemp() + + if dry_run: + print(f"{DRY_RUN_PREFIX} rename_context {source} > {destination}") + yield + return + + try: + rename(source, destination, force=True) + yield + except Exception as exc: + # Error occurred, roll back change + rename(destination, source, force=True) + raise exc + + +def backoff_rename(source_path, destination_path, force=False): + exp_backoff_fn(rename, source_path, destination_path, force) + + +def touch(path, mkdir=False, sudo_safe=False): + # sudo_safe: use any time `path` is within the user's home directory + # returns: + # True if the file did not exist but was created + # False if the file already existed + # raises: NotWritableError, which is also an OSError having attached errno + try: + path = expand(path) + log.log(TRACE, "touching path %s", path) + if lexists(path): + os.utime(path, None) + return True + else: + dirpath = dirname(path) + if not isdir(dirpath) and mkdir: + if sudo_safe: + mkdir_p_sudo_safe(dirpath) + else: + mkdir_p(dirpath) + else: + if not isdir(dirname(path)): + raise OSError("Target path is not a directory.") + with open(path, "a"): + pass + # This chown call causes a false positive PermissionError to be + # raised (similar to #7109) when called in an environment which + # comes from sudo -u. + # + # if sudo_safe and not on_win and os.environ.get('SUDO_UID') is not None: + # uid = int(os.environ['SUDO_UID']) + # gid = int(os.environ.get('SUDO_GID', -1)) + # log.log(TRACE, "chowning %s:%s %s", uid, gid, path) + # os.chown(path, uid, gid) + return False + except OSError as e: + raise NotWritableError(path, e.errno, caused_by=e) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/logging.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..a47d744782a8aaf8050c0cc0f7730acec5b6c9b9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/logging.py @@ -0,0 +1,216 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Configure logging for conda.""" + +import logging +import re +import sys +from datetime import datetime, timezone +from functools import cache, partial +from logging import ( + DEBUG, + INFO, + WARN, + Filter, + Formatter, + StreamHandler, + getLogger, +) + +from ..common.constants import TRACE +from ..common.io import _FORMATTER, attach_stderr_handler + +log = getLogger(__name__) +_VERBOSITY_LEVELS = { + 0: WARN, # standard output + 1: WARN, # -v, detailed output + 2: INFO, # -vv, info logging + 3: DEBUG, # -vvv, debug logging + 4: TRACE, # -vvvv, trace logging +} + +# Labels log messages with log level TRACE (5) as "TRACE" +logging.addLevelName(TRACE, "TRACE") + + +class TokenURLFilter(Filter): + TOKEN_URL_PATTERN = re.compile( + r"(|https?://)" # \1 scheme + r"(|\s" # \2 space, or + r"|(?:(?:\d{1,3}\.){3}\d{1,3})" # ipv4, or + r"|(?:" # domain name + r"(?:[a-zA-Z0-9-]{1,20}\.){0,10}" # non-tld + r"(?:[a-zA-Z]{2}[a-zA-Z0-9-]{0,18})" # tld + r"))" # end domain name + r"(|:\d{1,5})?" # \3 port + r"/t/[a-z0-9A-Z-]+/" # token + ) + TOKEN_REPLACE = staticmethod(partial(TOKEN_URL_PATTERN.sub, r"\1\2\3/t//")) + + def filter(self, record): + """ + Since Python 2's getMessage() is incapable of handling any + strings that are not unicode when it interpolates the message + with the arguments, we fix that here by doing it ourselves. + + At the same time we replace tokens in the arguments which was + not happening until now. + """ + if not isinstance(record.msg, str): + # This should always be the case but it's not checked so + # we avoid any potential logging errors. + return True + if record.args: + record.msg = record.msg % record.args + record.args = None + record.msg = self.TOKEN_REPLACE(record.msg) + return True + + +class StdStreamHandler(StreamHandler): + """Log StreamHandler that always writes to the current sys stream.""" + + terminator = "\n" + + def __init__(self, sys_stream): + """ + Args: + sys_stream: stream name, either "stdout" or "stderr" (attribute of module sys) + """ + super().__init__(getattr(sys, sys_stream)) + self.sys_stream = sys_stream + del self.stream + + def __getattr__(self, attr): + # always get current sys.stdout/sys.stderr, unless self.stream has been set explicitly + if attr == "stream": + return getattr(sys, self.sys_stream) + return super().__getattribute__(attr) + + """ + def emit(self, record): + # in contrast to the Python 2.7 StreamHandler, this has no special Unicode handling; + # however, this backports the Python >=3.2 terminator attribute and additionally makes it + # further customizable by giving record an identically named attribute, e.g., via + # logger.log(..., extra={"terminator": ""}) or LoggerAdapter(logger, {"terminator": ""}). + try: + msg = self.format(record) + terminator = getattr(record, "terminator", self.terminator) + stream = self.stream + stream.write(msg) + stream.write(terminator) + self.flush() + except Exception: + self.handleError(record) + + """ + + # Updated Python 2.7.15's stdlib, with terminator and unicode support. + def emit(self, record): + """ + Emit a record. + + If a formatter is specified, it is used to format the record. + The record is then written to the stream with a trailing newline. If + exception information is present, it is formatted using + traceback.print_exception and appended to the stream. If the stream + has an 'encoding' attribute, it is used to determine how to do the + output to the stream. + """ + try: + msg = self.format(record) + stream = self.stream + fs = "%s" + stream.write(fs % msg) + terminator = getattr(record, "terminator", self.terminator) + stream.write(terminator) + self.flush() + # How does conda handle Ctrl-C? Find out.. + # except (KeyboardInterrupt, SystemExit): + # raise + except Exception: + self.handleError(record) + + +# Don't use initialize_logging/set_conda_log_level in +# cli.python_api! There we want the user to have control over their logging, +# e.g., using their own levels, handlers, formatters and propagation settings. + + +@cache +def initialize_logging(): + # 'conda' gets level WARN and does not propagate to root. + getLogger("conda").setLevel(WARN) + set_conda_log_level() + initialize_std_loggers() + + +def initialize_std_loggers(): + # Set up special loggers 'conda.stdout'/'conda.stderr' which output directly to the + # corresponding sys streams, filter token urls and don't propagate. + formatter = Formatter("%(message)s") + + for stream in ("stdout", "stderr"): + logger = getLogger(f"conda.{stream}") + logger.handlers = [] + logger.setLevel(INFO) + handler = StdStreamHandler(stream) + handler.setLevel(INFO) + handler.setFormatter(formatter) + logger.addHandler(handler) + logger.addFilter(TokenURLFilter()) + logger.propagate = False + + stdlog_logger = getLogger(f"conda.{stream}log") + stdlog_logger.handlers = [] + stdlog_logger.setLevel(DEBUG) + stdlog_handler = StdStreamHandler(stream) + stdlog_handler.terminator = "" + stdlog_handler.setLevel(DEBUG) + stdlog_handler.setFormatter(formatter) + stdlog_logger.addHandler(stdlog_handler) + stdlog_logger.propagate = False + + verbose_logger = getLogger("conda.stdout.verbose") + verbose_logger.handlers = [] + verbose_logger.setLevel(INFO) + verbose_handler = StdStreamHandler("stdout") + verbose_handler.setLevel(INFO) + verbose_handler.setFormatter(formatter) + verbose_handler.addFilter(TokenURLFilter()) + verbose_logger.addHandler(verbose_handler) + verbose_logger.propagate = False + + +def set_conda_log_level(level=WARN): + attach_stderr_handler(level=level, logger_name="conda", filters=[TokenURLFilter()]) + + +def set_all_logger_level(level=DEBUG): + formatter = Formatter("%(message)s\n") if level >= INFO else None + attach_stderr_handler(level, formatter=formatter, filters=[TokenURLFilter()]) + set_conda_log_level(level) + # 'requests' loggers get their own handlers so that they always output messages in long format + # regardless of the level. + attach_stderr_handler(level, "requests", filters=[TokenURLFilter()]) + attach_stderr_handler( + level, "requests.packages.urllib3", filters=[TokenURLFilter()] + ) + + +@cache +def set_file_logging(logger_name=None, level=DEBUG, path=None): + if path is None: + timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") + path = f".conda.{timestamp}.log" + + conda_logger = getLogger(logger_name) + handler = logging.FileHandler(path) + handler.setFormatter(_FORMATTER) + handler.setLevel(level) + conda_logger.addHandler(handler) + + +def set_log_level(log_level: int): + set_all_logger_level(log_level) + log.debug("log_level set to %d", log_level) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f32e3a5dc23f0787efa24b2f71406a34a2ed045e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/__init__.py @@ -0,0 +1,989 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Repodata interface.""" + +from __future__ import annotations + +import abc +import datetime +import errno +import hashlib +import logging +import os +import pathlib +import re +import time +import warnings +from collections import UserDict +from contextlib import contextmanager +from os.path import dirname +from typing import TYPE_CHECKING + +from ... import CondaError +from ...auxlib.logz import stringify +from ...base.constants import CONDA_HOMEPAGE_URL, REPODATA_FN +from ...base.context import context +from ...common.serialize import json +from ...common.url import join_url, maybe_unquote +from ...core.package_cache_data import PackageCacheData +from ...exceptions import ( + CondaDependencyError, + CondaHTTPError, + CondaSSLError, + NotWritableError, + ProxyError, + UnavailableInvalidChannel, +) +from ...models.channel import Channel +from ..connection import ( + ChunkedEncodingError, + ConnectionError, + HTTPError, + InsecureRequestWarning, + InvalidSchema, + RequestsProxyError, + SSLError, +) +from ..connection.session import get_session +from ..disk import mkdir_p_sudo_safe +from ..disk.lock import lock + +if TYPE_CHECKING: + from pathlib import Path + from typing import Any + + from ..connection import Response + +log = logging.getLogger(__name__) +stderrlog = logging.getLogger("conda.stderrlog") + + +# if repodata_shards.msgpack.zst, repodata.json.zst or repodata.jlap were unavailable, check again later. +CHECK_ALTERNATE_FORMAT_INTERVAL = datetime.timedelta(days=7) + +# repodata.info/state.json keys to keep up with the CEP +LAST_MODIFIED_KEY = "mod" +ETAG_KEY = "etag" +CACHE_CONTROL_KEY = "cache_control" +URL_KEY = "url" +CACHE_STATE_SUFFIX = ".info.json" + +# show some unparseable json in error +ERROR_SNIPPET_LENGTH = 32 + + +class RepodataIsEmpty(UnavailableInvalidChannel): + """ + Subclass used to determine when empty repodata should be cached, e.g. for a + channel that doesn't provide current_repodata.json + """ + + +class RepodataOnDisk(Exception): + """ + Indicate that RepoInterface.repodata() successfully wrote repodata to disk, + instead of returning a string. + """ + + +class RepoInterface(abc.ABC): + def repodata(self, state: dict) -> str: + """ + Given a mutable state dictionary with information about the cache, + return repodata.json (or current_repodata.json) as a str. This function + also updates state, which is expected to be saved by the caller. + """ + ... + + +class Response304ContentUnchanged(Exception): + pass + + +def get_repo_interface() -> type[RepoInterface]: + if "jlap" in context.experimental: + try: + from .jlap.interface import JlapRepoInterface + + return JlapRepoInterface + except ImportError as e: # pragma: no cover + warnings.warn( + "Could not load the configured jlap repo interface. " + f"Is the required jsonpatch package installed? {e}" + ) + + if context.repodata_use_zst: + try: + from .jlap.interface import ZstdRepoInterface + + return ZstdRepoInterface + except ImportError: # pragma: no cover + pass + + return CondaRepoInterface + + +class CondaRepoInterface(RepoInterface): + """Provides an interface for retrieving repodata data from channels.""" + + _url: str + """Channel URL.""" + + _repodata_fn: str + """Filename of the repodata file; defaults to value of conda.base.constants.REPODATA_FN.""" + + def __init__(self, url: str, repodata_fn: str | None, **kwargs) -> None: + log.debug("Using CondaRepoInterface") + self._url = url + self._repodata_fn = repodata_fn or REPODATA_FN + + def repodata(self, state: RepodataState) -> str | None: + if not context.ssl_verify: + warnings.simplefilter("ignore", InsecureRequestWarning) + + session = get_session(self._url) + + headers = {} + etag = state.etag + last_modified = state.mod + if etag: + headers["If-None-Match"] = str(etag) + if last_modified: + headers["If-Modified-Since"] = str(last_modified) + filename = self._repodata_fn + + url = join_url(self._url, filename) + + with conda_http_errors(self._url, filename): + timeout = ( + context.remote_connect_timeout_secs, + context.remote_read_timeout_secs, + ) + response: Response = session.get( + url, headers=headers, proxies=session.proxies, timeout=timeout + ) + if log.isEnabledFor(logging.DEBUG): + log.debug(stringify(response, content_max_len=256)) + response.raise_for_status() + + if response.status_code == 304: + # should we save cache-control to state here to put another n + # seconds on the "make a remote request" clock and/or touch cache + # mtime + raise Response304ContentUnchanged() + + json_str = response.text + + # We no longer add these tags to the large `resp.content` json + saved_fields = {"_url": self._url} + _add_http_value_to_dict(response, "Etag", saved_fields, "_etag") + _add_http_value_to_dict(response, "Last-Modified", saved_fields, "_mod") + _add_http_value_to_dict( + response, "Cache-Control", saved_fields, "_cache_control" + ) + + state.clear() + state.update(saved_fields) + + return json_str + + +def _add_http_value_to_dict(resp, http_key, d, dict_key): + value = resp.headers.get(http_key) + if value: + d[dict_key] = value + + +@contextmanager +def conda_http_errors(url, repodata_fn): + """Use in a with: statement to translate requests exceptions to conda ones.""" + try: + yield + except RequestsProxyError: + raise ProxyError() # see #3962 + + except InvalidSchema as e: + if "SOCKS" in str(e): + message = """\ +Requests has identified that your current working environment is configured +to use a SOCKS proxy, but pysocks is not installed. To proceed, remove your +proxy configuration, run `conda install pysocks`, and then you can re-enable +your proxy configuration. +""" + raise CondaDependencyError(message) + else: + raise + + except SSLError as e: + # SSLError: either an invalid certificate or OpenSSL is unavailable + try: + import ssl # noqa: F401 + except ImportError: + raise CondaSSLError( + f"""\ +OpenSSL appears to be unavailable on this machine. OpenSSL is required to +download and install packages. + +Exception: {e} +""" + ) + else: + raise CondaSSLError( + f"""\ +Encountered an SSL error. Most likely a certificate verification issue. + +Exception: {e} +""" + ) + + except (ConnectionError, HTTPError, ChunkedEncodingError) as e: + status_code = getattr(e.response, "status_code", None) + if status_code == 404: + if not url.endswith("/noarch"): + log.info( + "Unable to retrieve repodata (response: %d) for %s", + status_code, + url + "/" + repodata_fn, + ) + raise RepodataIsEmpty( + Channel(dirname(url)), + status_code, + response=e.response, + ) + else: + if context.allow_non_channel_urls: + stderrlog.warning( + "Unable to retrieve repodata (response: %d) for %s", + status_code, + url + "/" + repodata_fn, + ) + raise RepodataIsEmpty( + Channel(dirname(url)), + status_code, + response=e.response, + ) + else: + raise UnavailableInvalidChannel( + Channel(dirname(url)), + status_code, + response=e.response, + ) + + elif status_code == 403: + channel = Channel(url) + if channel.token: + help_message = """\ +The token given for the URL has insufficient permissions to access this resource. + +You may not have the required permissions to access this channel or package. +Consider requesting access from the channel owner. + +Use `conda config --show` to view your configuration's current state. +Further configuration help can be found at <{}>. +""".format(join_url(CONDA_HOMEPAGE_URL, "docs/config.html")) + + elif context.channel_alias.location in url: + help_message = """\ +The remote server has indicated you do not have permission to access this resource. + +This may mean: + (a) You are not authenticated. Check if authentication is required for this channel + and verify your credentials are correctly configured. + (b) You do not have access to this private channel or package. Contact the + channel owner to request access. + +Further configuration help can be found at <{}>. +""".format(join_url(CONDA_HOMEPAGE_URL, "docs/config.html")) + + else: + help_message = """\ +You do not have permission to access this resource. + +This may indicate: + - The channel requires authentication. Check your credentials. + - You do not have access to this private channel or package. + +You will need to modify your conda configuration to proceed. +Use `conda config --show` to view your configuration's current state. +Further configuration help can be found at <{}>. +""".format(join_url(CONDA_HOMEPAGE_URL, "docs/config.html")) + + elif status_code == 401: + channel = Channel(url) + if channel.token: + help_message = """\ +The token given for the URL is invalid. + +You will need to adjust your conda configuration to proceed. + +Use `conda config --show` to view your configuration's current state. +Further configuration help can be found at <{}>. +""".format(join_url(CONDA_HOMEPAGE_URL, "docs/config.html")) + + elif context.channel_alias.location in url: + help_message = """\ +The remote server has indicated you are using invalid credentials for this channel. + +You may need to: + (a) Remove or update the invalid token from your configuration, or + (b) Provide conda with a valid token directly. + +Further configuration help can be found at <{}>. +""".format(join_url(CONDA_HOMEPAGE_URL, "docs/config.html")) + + else: + help_message = """\ +The credentials you have provided for this URL are invalid. + +You will need to modify your conda configuration to proceed. +Use `conda config --show` to view your configuration's current state. +Further configuration help can be found at <{}>. +""".format(join_url(CONDA_HOMEPAGE_URL, "docs/config.html")) + + elif status_code is not None and 500 <= status_code < 600: + help_message = """\ +A remote server error occurred when trying to retrieve this URL. + +A 500-type error (e.g. 500, 501, 502, 503, etc.) indicates the server failed to +fulfill a valid request. The problem may be spurious, and will resolve itself if you +try your request again. If the problem persists, consider notifying the maintainer +of the remote server. +""" + + else: + if url.startswith("https://repo.anaconda.com/"): + help_message = f"""\ +An HTTP error occurred when trying to retrieve this URL. +HTTP errors are often intermittent, and a simple retry will get you on your way. + +If your current network has https://repo.anaconda.com blocked, please file +a support request with your network engineering team. + +{maybe_unquote(repr(url))} +""" + + else: + help_message = f"""\ +An HTTP error occurred when trying to retrieve this URL. +HTTP errors are often intermittent, and a simple retry will get you on your way. +{maybe_unquote(repr(url))} +""" + + raise CondaHTTPError( + help_message, + join_url(url, repodata_fn), + status_code, + getattr(e.response, "reason", None), + getattr(e.response, "elapsed", None), + e.response, + caused_by=e, + ) + + +class RepodataState(UserDict): + """Load/save info file that accompanies cached `repodata.json`.""" + + # Accept old keys for new serialization + _aliased = { + "_mod": LAST_MODIFIED_KEY, + "_etag": ETAG_KEY, + "_cache_control": CACHE_CONTROL_KEY, + "_url": URL_KEY, + } + + # Enforce string type on these keys + _strings = {"mod", "etag", "cache_control", "url"} + + def __init__( + self, + cache_path_json: Path | str = "", + cache_path_state: Path | str = "", + repodata_fn="", + dict=None, + ): + # dict is a positional-only argument in UserDict. + super().__init__(dict) + self.cache_path_json = pathlib.Path(cache_path_json) + self.cache_path_state = pathlib.Path(cache_path_state) + # XXX may not be that useful/used compared to the full URL + self.repodata_fn = repodata_fn + + @property + def mod(self) -> str: + """ + Last-Modified header or "" + """ + return self.get(LAST_MODIFIED_KEY) or "" + + @mod.setter + def mod(self, value): + self[LAST_MODIFIED_KEY] = value or "" + + @property + def etag(self) -> str: + """ + Etag header or "" + """ + return self.get(ETAG_KEY) or "" + + @etag.setter + def etag(self, value): + self[ETAG_KEY] = value or "" + + @property + def cache_control(self) -> str: + """ + Cache-Control header or "" + """ + return self.get(CACHE_CONTROL_KEY) or "" + + @cache_control.setter + def cache_control(self, value): + self[CACHE_CONTROL_KEY] = value or "" + + def has_format(self, format: str) -> tuple[bool, datetime.datetime | None]: + # "has_zst": { + # // UTC RFC3999 timestamp of when we last checked whether the file is available or not + # // in this case the `repodata.json.zst` file + # // Note: same format as conda TUF spec + # "last_checked": "2023-01-08T11:45:44Z", + # // false = unavailable, true = available + # "value": BOOLEAN + # }, + + key = f"has_{format}" + if key not in self: + return (True, None) # we want to check by default + + try: + obj = self[key] + last_checked_str = obj["last_checked"] + if last_checked_str.endswith("Z"): + last_checked_str = f"{last_checked_str[:-1]}+00:00" + last_checked = datetime.datetime.fromisoformat(last_checked_str) + value = bool(obj["value"]) + return (value, last_checked) + except (KeyError, ValueError, TypeError) as e: + log.warning( + f"error parsing `has_` object from `{CACHE_STATE_SUFFIX}`", + exc_info=e, + ) + self.pop(key) + + return False, datetime.datetime.now(tz=datetime.timezone.utc) + + def set_has_format(self, format: str, value: bool): + key = f"has_{format}" + self[key] = { + "last_checked": datetime.datetime.now(tz=datetime.timezone.utc).isoformat()[ + : -len("+00:00") + ] + + "Z", + "value": value, + } + + def clear_has_format(self, format: str): + """Remove 'has_{format}' instead of setting to False.""" + key = f"has_{format}" + self.pop(key, None) + + def should_check_format(self, format: str) -> bool: + """Return True if named format should be attempted.""" + has, when = self.has_format(format) + return ( + has is True + or isinstance(when, datetime.datetime) + and datetime.datetime.now(tz=datetime.timezone.utc) - when + > CHECK_ALTERNATE_FORMAT_INTERVAL + ) + + def __contains__(self, key: str) -> bool: + key = self._aliased.get(key, key) + return super().__contains__(key) + + def __setitem__(self, key: str, item: Any) -> None: + key = self._aliased.get(key, key) + if key in self._strings and not isinstance(item, str): + log.debug('Replaced non-str RepodataState[%s] with ""', key) + item = "" + return super().__setitem__(key, item) + + def __getitem__(self, key: str) -> Any: + key = self._aliased.get(key, key) + return super().__getitem__(key) + + +class RepodataCache: + """ + Handle caching for a single repodata.json + repodata.info.json + (*.json inside `dir`) + + Avoid race conditions while loading, saving repodata.json and cache state. + + Also support bytes as in repodata_shards.msgpack.zst + """ + + def __init__(self, base, repodata_fn): + """ + base: directory and filename prefix for cache, e.g. /cache/dir/abc123; + writes /cache/dir/abc123.json + """ + cache_path_base = pathlib.Path(base) + self.cache_dir = cache_path_base.parent + self.name = cache_path_base.name + # XXX can we skip repodata_fn or include the full url for debugging + self.repodata_fn = repodata_fn + self.state = RepodataState( + self.cache_path_json, self.cache_path_state, repodata_fn + ) + + @property + def cache_path_json(self): + return pathlib.Path( + self.cache_dir, + self.name + ("1" if context.use_only_tar_bz2 else "") + ".json", + ) + + @property + def cache_path_shards(self): + return pathlib.Path( + self.cache_dir, + self.name + ("1" if context.use_only_tar_bz2 else "") + ".msgpack.zst", + ) + + @property + def cache_path_state(self): + """Out-of-band etag and other state needed by the RepoInterface.""" + return self.cache_path_json.with_suffix(CACHE_STATE_SUFFIX) + + def load(self, *, state_only=False, binary=False) -> str | bytes: + # read state and repodata.json with locking + + # lock {CACHE_STATE_SUFFIX} file + # read {CACHE_STATES_SUFFIX} file + # read repodata.json + # check stat, if wrong clear cache information + + with self.lock("r+") as state_file: + # cannot use pathlib.read_text / write_text on any locked file, as + # it will release the lock early + state = json.loads(state_file.read()) + + cache_path = self.cache_path_shards if binary else self.cache_path_json + + # json and state files should match. must read json before checking + # stat (if json_data is to be trusted) + if state_only: + json_data = b"" if binary else "" + else: + if binary: + json_data = cache_path.read_bytes() + else: + json_data = cache_path.read_text() + + json_stat = cache_path.stat() + if not ( + state.get("mtime_ns") == json_stat.st_mtime_ns + and state.get("size") == json_stat.st_size + ): + # clear mod, etag, cache_control to encourage re-download + state.update( + { + ETAG_KEY: "", + LAST_MODIFIED_KEY: "", + CACHE_CONTROL_KEY: "", + "size": 0, + } + ) + # Replace data in special self.state dict subclass with key aliases + self.state.clear() + self.state.update(state) + + return json_data + + def load_state(self, binary=False): + """ + Update self.state without reading repodata. + + Return self.state. + """ + try: + self.load(state_only=True, binary=binary) + except (FileNotFoundError, json.JSONDecodeError) as e: + if isinstance(e, json.JSONDecodeError): + log.warning(f"{e.__class__.__name__} loading {self.cache_path_state}") + self.state.clear() + return self.state + + def save(self, data: str | bytes): + """Write data to cache path, by calling self.replace().""" + temp_path = self.cache_dir / f"{self.name}.{os.urandom(2).hex()}.tmp" + if isinstance(data, bytes): + mode = "bx" + target = self.cache_path_shards + else: + mode = "x" + target = self.cache_path_json + + try: + with temp_path.open(mode) as temp: # exclusive mode, error if exists + temp.write(data) + + return self.replace(temp_path, target) + + finally: + try: + temp_path.unlink() + except OSError: + pass + + def replace(self, temp_path: Path, target=None): + """ + Rename path onto path, synchronize state. + + Relies on path's mtime not changing on move. `temp_path` should be + adjacent to `self.cache_path_json` to be on the same filesystem. + """ + if target is None: + target = self.cache_path_json + with self.lock() as state_file: + # "a+" creates the file if necessary, does not trunctate file. + state_file.seek(0) + state_file.truncate() + stat = temp_path.stat() + # UserDict has inscrutable typing, which we ignore + self.state["mtime_ns"] = stat.st_mtime_ns # type: ignore + self.state["size"] = stat.st_size # type: ignore + self.state["refresh_ns"] = time.time_ns() # type: ignore + try: + temp_path.rename(target) + except FileExistsError: # Windows + target.unlink() + temp_path.rename(target) + + state_file.write(json.dumps(dict(self.state), indent=2)) + + def refresh(self, refresh_ns=0): + """ + Update access time in cache info file to indicate a HTTP 304 Not Modified response. + """ + # Note this is not thread-safe. + with self.lock() as state_file: + # "a+" creates the file if necessary, does not trunctate file. + state_file.seek(0) + state_file.truncate() + self.state["refresh_ns"] = refresh_ns or time.time_ns() + state_file.write(json.dumps(dict(self.state), indent=2)) + + @contextmanager + def lock(self, mode="a+"): + """ + Lock .info.json file. Hold lock while modifying related files. + + mode: "a+" then seek(0) to write/create; "r+" to read. + """ + with self.cache_path_state.open(mode) as state_file, lock(state_file): + yield state_file + + def stale(self): + """ + Compare state refresh_ns against cache control header and + context.local_repodata_ttl. + """ + if context.local_repodata_ttl > 1: + max_age = context.local_repodata_ttl + elif context.local_repodata_ttl == 1: + max_age = get_cache_control_max_age(self.state.cache_control) + else: + max_age = 0 + + max_age *= 10**9 # nanoseconds + now = time.time_ns() + refresh = self.state.get("refresh_ns", 0) + return (now - refresh) > max_age + + def timeout(self): + """ + Return number of seconds until cache times out (<= 0 if already timed + out). + """ + if context.local_repodata_ttl > 1: + max_age = context.local_repodata_ttl + elif context.local_repodata_ttl == 1: + max_age = get_cache_control_max_age(self.state.cache_control) + else: + max_age = 0 + + max_age *= 10**9 # nanoseconds + now = time.time_ns() + refresh = self.state.get("refresh_ns", 0) + return ((now - refresh) + max_age) / 1e9 + + +class RepodataFetch: + """ + Combine RepodataCache and RepoInterface to provide subdir_data.SubdirData() + with what it needs. + + Provide a variety of formats since some ``RepoInterface`` have to + ``json.loads(...)`` anyway, and some clients don't need the Python data + structure at all. + """ + + cache_path_base: Path + channel: Channel + repodata_fn: str + url_w_subdir: str + url_w_credentials: str + repo_interface_cls: Any + + def __init__( + self, + cache_path_base: Path, + channel: Channel, + repodata_fn: str, + *, + repo_interface_cls, + ): + self.cache_path_base = cache_path_base + self.channel = channel + self.repodata_fn = repodata_fn + + self.url_w_subdir = self.channel.url(with_credentials=False) or "" + self.url_w_credentials = self.channel.url(with_credentials=True) or "" + + self.repo_interface_cls = repo_interface_cls + + def fetch_latest_parsed(self) -> tuple[dict, RepodataState]: + """ + Retrieve parsed latest or latest-cached repodata as a dict; update + cache. + + :return: (repodata contents, state including cache headers) + """ + parsed, state = self.fetch_latest() + if isinstance(parsed, str): + try: + return json.loads(parsed), state + except json.JSONDecodeError as e: + e.args = ( + f'{e.args[0]}; got "{parsed[:ERROR_SNIPPET_LENGTH]}"', + *e.args[1:], + ) + raise + else: + return parsed, state + + def fetch_latest_path(self) -> tuple[Path, RepodataState]: + """ + Retrieve latest or latest-cached repodata; update cache. + + :return: (pathlib.Path to uncompressed repodata contents, RepodataState) + """ + _, state = self.fetch_latest() + return self.cache_path_json, state + + @property + def url_w_repodata_fn(self): + return self.url_w_subdir + "/" + self.repodata_fn + + @property + def cache_path_json(self): + return self.repo_cache.cache_path_json + + @property + def cache_path_state(self): + """ + Out-of-band etag and other state needed by the RepoInterface. + """ + return self.repo_cache.cache_path_state + + @property + def repo_cache(self) -> RepodataCache: + return RepodataCache(self.cache_path_base, self.repodata_fn) + + @property + def _repo(self) -> RepoInterface: + """ + Changes as we mutate self.repodata_fn. + """ + return self.repo_interface_cls( + self.url_w_credentials, + repodata_fn=self.repodata_fn, + cache=self.repo_cache, + ) + + def fetch_latest(self) -> tuple[dict | str, RepodataState]: + """ + Return up-to-date repodata and cache information. Fetch repodata from + remote if cache has expired; return cached data if cache has not + expired; return stale cached data or dummy data if in offline mode. + """ + cache = self.repo_cache + cache.load_state() + + # XXX cache_path_json and cache_path_state must exist; just try loading + # it and fall back to this on error? + if not cache.cache_path_json.exists(): + log.debug( + "No local cache found for %s at %s", + self.url_w_repodata_fn, + self.cache_path_json, + ) + if context.use_index_cache or ( + context.offline and not self.url_w_subdir.startswith("file://") + ): + log.debug( + "Using cached data for %s at %s forced. Returning empty repodata.", + self.url_w_repodata_fn, + self.cache_path_json, + ) + return ( + {}, + cache.state, + ) # XXX basic properties like info, packages, packages.conda? instead of {}? + + else: + if context.use_index_cache: + log.debug( + "Using cached repodata for %s at %s because use_cache=True", + self.url_w_repodata_fn, + self.cache_path_json, + ) + + _internal_state = self.read_cache() + return _internal_state + + stale = cache.stale() + if (not stale or context.offline) and not self.url_w_subdir.startswith( + "file://" + ): + timeout = cache.timeout() + log.debug( + "Using cached repodata for %s at %s. Timeout in %d sec", + self.url_w_repodata_fn, + self.cache_path_json, + timeout, + ) + _internal_state = self.read_cache() + return _internal_state + + log.debug( + "Local cache timed out for %s at %s", + self.url_w_repodata_fn, + self.cache_path_json, + ) + + try: + try: + repo = self._repo + if hasattr(repo, "repodata_parsed"): + raw_repodata = repo.repodata_parsed(cache.state) # type: ignore + else: + raw_repodata = repo.repodata(cache.state) # type: ignore + except RepodataIsEmpty: + if self.repodata_fn != REPODATA_FN: + raise # is UnavailableInvalidChannel subclass + # the surrounding try/except/else will cache "{}" + raw_repodata = None + except RepodataOnDisk: + # used as a sentinel, not the raised exception object + raw_repodata = RepodataOnDisk + + except Response304ContentUnchanged: + log.debug( + "304 NOT MODIFIED for '%s'. Updating mtime and loading from disk", + self.url_w_repodata_fn, + ) + cache.refresh() + _internal_state = self.read_cache() + return _internal_state + else: + try: + if raw_repodata is RepodataOnDisk: + # this is handled very similar to a 304. Can the cases be merged? + # we may need to read_bytes() and compare a hash to the state, instead. + # XXX use self._repo_cache.load() or replace after passing temp path to jlap + raw_repodata = self.cache_path_json.read_text() + stat = self.cache_path_json.stat() + cache.state["size"] = stat.st_size # type: ignore + mtime_ns = stat.st_mtime_ns + cache.state["mtime_ns"] = mtime_ns # type: ignore + cache.refresh() + elif isinstance(raw_repodata, dict): + # repo implementation cached it, and parsed it + # XXX check size upstream for locking reasons + stat = self.cache_path_json.stat() + cache.state["size"] = stat.st_size + mtime_ns = stat.st_mtime_ns + cache.state["mtime_ns"] = mtime_ns # type: ignore + cache.refresh() + elif isinstance(raw_repodata, (str, type(None))): + # Can we pass this information in state or with a sentinel/special exception? + if raw_repodata is None: + raw_repodata = "{}" + cache.save(raw_repodata) + else: # pragma: no cover + raise RuntimeError(f"Unreachable {raw_repodata}") + except OSError as e: + if e.errno in (errno.EACCES, errno.EPERM, errno.EROFS): + raise NotWritableError(self.cache_path_json, e.errno, caused_by=e) + else: + raise + + return raw_repodata, cache.state + + def read_cache(self) -> tuple[str, RepodataState]: + """ + Read repodata from disk, without trying to fetch a fresh version. + """ + # pickled data is bad or doesn't exist; load cached json + log.debug( + "Loading raw json for %s at %s", + self.url_w_repodata_fn, + self.cache_path_json, + ) + + cache = self.repo_cache + + try: + raw_repodata_str = cache.load() + return raw_repodata_str, cache.state + except ValueError as e: + # OSError (locked) may happen here + # ValueError: Expecting object: line 11750 column 6 (char 303397) + log.debug("Error for cache path: '%s'\n%r", self.cache_path_json, e) + message = """An error occurred when loading cached repodata. Executing +`conda clean --index-cache` will remove cached repodata files +so they can be downloaded again.""" + raise CondaError(message) + + +def _md5_not_for_security(data): + return hashlib.md5(data, usedforsecurity=False) + + +def cache_fn_url(url, repodata_fn=REPODATA_FN): + # url must be right-padded with '/' to not invalidate any existing caches + if not url.endswith("/"): + url += "/" + # add the repodata_fn in for uniqueness, but keep it off for standard stuff. + # It would be more sane to add it for everything, but old programs (Navigator) + # are looking for the cache under keys without this. + if repodata_fn != REPODATA_FN: + url += repodata_fn + + md5 = _md5_not_for_security(url.encode("utf-8")) + return f"{md5.hexdigest()[:8]}.json" + + +def get_cache_control_max_age(cache_control_value: str | None): + cache_control_value = cache_control_value or "" + max_age = re.search(r"max-age=(\d+)", cache_control_value) + return int(max_age.groups()[0]) if max_age else 0 + + +def create_cache_dir(): + cache_dir = os.path.join(PackageCacheData.first_writable().pkgs_dir, "cache") + mkdir_p_sudo_safe(cache_dir) + return cache_dir diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f2bd35a5dc213cfb16dade89ef152bae35bf68 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__init__.py @@ -0,0 +1,3 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Incremental repodata feature based on .jlap patch files.""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/core.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/core.py new file mode 100644 index 0000000000000000000000000000000000000000..ddb477e04469e81c75ea736fde2cf4731a778896 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/core.py @@ -0,0 +1,137 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""JLAP reader.""" + +from __future__ import annotations + +import logging +from collections import UserList +from hashlib import blake2b +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + +log = logging.getLogger(__name__) + + +DIGEST_SIZE = 32 # 160 bits a minimum 'for security' length? +DEFAULT_IV = b"\0" * DIGEST_SIZE + + +def keyed_hash(data: bytes, key: bytes): + """Keyed hash.""" + return blake2b(data, key=key, digest_size=DIGEST_SIZE) + + +def line_and_pos(lines: Iterable[bytes], pos=0) -> Iterator[tuple[int, bytes]]: + r""" + :param lines: iterator over input split by '\n', with '\n' removed. + :param pos: initial position + """ + for line in lines: + yield pos, line + pos += len(line) + 1 + + +class JLAP(UserList): + @classmethod + def from_lines(cls, lines: Iterable[bytes], iv: bytes, pos=0, verify=True): + r""" + :param lines: iterator over input split by b'\n', with b'\n' removed + :param pos: initial position + :param iv: initialization vector (first line of .jlap stream, hex + decoded). Ignored if pos==0. + :param verify: assert last line equals computed checksum of previous + line. Useful for writing new .jlap files if False. + + :raises ValueError: if trailing and computed checksums do not match + + :return: list of (offset, line, checksum) + """ + # save initial iv in case there were no new lines + buffer: list[tuple[int, str, str]] = [(-1, iv.hex(), iv.hex())] + initial_pos = pos + + for pos, line in line_and_pos(lines, pos=pos): + if pos == 0: + iv = bytes.fromhex(line.decode("utf-8")) + buffer = [(0, iv.hex(), iv.hex())] + else: + iv = keyed_hash(line, iv).digest() + buffer.append((pos, line.decode("utf-8"), iv.hex())) + + log.debug("%d bytes read", pos - initial_pos) # maybe + length of last line + + if verify: + if buffer[-1][1] != buffer[-2][-1]: + raise ValueError("checksum mismatch") + else: + log.info("Checksum OK") + + return cls(buffer) + + @classmethod + def from_path(cls, path: Path | str, verify=True): + # in binary mode, line separator is hardcoded as \n + with Path(path).open("rb") as p: + return cls.from_lines( + (line.rstrip(b"\n") for line in p), b"", verify=verify + ) + + def add(self, line: str): + """ + Add line to buffer, following checksum rules. + + Buffer must not be empty. + + (Remember to pop trailing checksum and possibly trailing metadata line, if + appending to a complete jlap file) + + Less efficient than creating a new buffer from many lines and our last iv, + and extending. + + :return: self + """ + if "\n" in line: + raise ValueError("\\n not allowed in line") + pos, last_line, iv = self[-1] + # include last line's utf-8 encoded length, plus 1 in pos? + pos += len(last_line.encode("utf-8")) + 1 + self.extend( + JLAP.from_lines( + (line.encode("utf-8"),), bytes.fromhex(iv), pos, verify=False + )[1:] + ) + return self + + def terminate(self): + """ + Add trailing checksum to buffer. + + :return: self + """ + _, _, iv = self[-1] + self.add(iv) + return self + + def write(self, path: Path): + """Write buffer to path.""" + with Path(path).open("w", encoding="utf-8", newline="\n") as p: + return p.write("\n".join(b[1] for b in self)) + + @property + def body(self): + """All lines except the first, and last two.""" + return self[1:-2] + + @property + def penultimate(self): + """Next-to-last line. Should contain the footer.""" + return self[-2] + + @property + def last(self): + """Last line. Should contain the trailing checksum.""" + return self[-1] diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/fetch.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd830d2a6a8f0ebf80d818728b728d0550b7a43 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/fetch.py @@ -0,0 +1,492 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""JLAP consumer.""" + +from __future__ import annotations + +import io +import logging +import pprint +import re +import time +from contextlib import contextmanager +from hashlib import blake2b +from typing import TYPE_CHECKING + +import jsonpatch +import zstandard +from requests import HTTPError + +from ....base.context import context +from ....common.serialize import json +from ....common.url import mask_anaconda_token +from .. import ETAG_KEY, LAST_MODIFIED_KEY, RepodataState +from .core import JLAP + +if TYPE_CHECKING: + import pathlib + from collections.abc import Iterator + + from ...connection import Response, Session + from .. import RepodataCache + +log = logging.getLogger(__name__) + + +DIGEST_SIZE = 32 # 256 bits + +JLAP_KEY = "jlap" +HEADERS = "headers" +NOMINAL_HASH = "blake2_256_nominal" +ON_DISK_HASH = "blake2_256" +LATEST = "latest" + +# save these headers. at least etag, last-modified, cache-control plus a few +# useful extras. +STORE_HEADERS = { + "etag", + "last-modified", + "cache-control", + "content-range", + "content-length", + "date", + "content-type", + "content-encoding", +} + + +def hash(): + """Ordinary hash.""" + return blake2b(digest_size=DIGEST_SIZE) + + +class Jlap304NotModified(Exception): + pass + + +class JlapSkipZst(Exception): + pass + + +class JlapPatchNotFound(LookupError): + pass + + +def process_jlap_response(response: Response, pos=0, iv=b""): + # if response is 304 Not Modified, could return a buffer with only the + # cached footer... + if response.status_code == 304: + raise Jlap304NotModified() + + def lines() -> Iterator[bytes]: + yield from response.iter_lines(delimiter=b"\n") # type: ignore + + buffer = JLAP.from_lines(lines(), iv, pos) + + # new iv == initial iv if nothing changed + pos, footer, _ = buffer[-2] + footer = json.loads(footer) + + new_state = { + # we need to save etag, last-modified, cache-control + "headers": { + k.lower(): v + for k, v in response.headers.items() + if k.lower() in STORE_HEADERS + }, + "iv": buffer[-3][-1], + "pos": pos, + "footer": footer, + } + + return buffer, new_state + + +def fetch_jlap(url, pos=0, etag=None, iv=b"", ignore_etag=True, session=None): + response = request_jlap( + url, pos=pos, etag=etag, ignore_etag=ignore_etag, session=session + ) + return process_jlap_response(response, pos=pos, iv=iv) + + +def request_jlap( + url, pos=0, etag=None, ignore_etag=True, session: Session | None = None +): + """Return the part of the remote .jlap file we are interested in.""" + headers = {} + if pos: + headers["range"] = f"bytes={pos}-" + if etag and not ignore_etag: + headers["if-none-match"] = etag + + log.debug("%s %s", mask_anaconda_token(url), headers) + + if session is None: + raise RuntimeError("session cannot be None") + + timeout = context.remote_connect_timeout_secs, context.remote_read_timeout_secs + response = session.get(url, stream=True, headers=headers, timeout=timeout) + response.raise_for_status() + + if response.request: + log.debug("request headers: %s", pprint.pformat(response.request.headers)) + else: + log.debug("response without request.") + log.debug( + "response headers: %s", + pprint.pformat( + {k: v for k, v in response.headers.items() if k.lower() in STORE_HEADERS} + ), + ) + log.debug("status: %d", response.status_code) + if "range" in headers: + # 200 is also a possibility that we'd rather not deal with; if the + # server can't do range requests, also mark jlap as unavailable. Which + # status codes mean 'try again' instead of 'it will never work'? + if response.status_code not in (206, 304, 404, 416): + raise HTTPError( + f"Unexpected response code for range request {response.status_code}", + response=response, + ) + + log.info("%s", response) + + return response + + +def format_hash(hash): + """Abbreviate hash for formatting.""" + return hash[:16] + "\N{HORIZONTAL ELLIPSIS}" + + +def find_patches(patches, have, want): + apply = [] + for patch in reversed(patches): + if have == want: + break + if patch["to"] == want: + apply.append(patch) + want = patch["from"] + + if have != want: + log.debug(f"No patch from local revision {format_hash(have)}") + raise JlapPatchNotFound(f"No patch from local revision {format_hash(have)}") + + return apply + + +def apply_patches(data, apply): + while apply: + patch = apply.pop() + log.debug( + f"{format_hash(patch['from'])} \N{RIGHTWARDS ARROW} {format_hash(patch['to'])}, " + f"{len(patch['patch'])} steps" + ) + data = jsonpatch.JsonPatch(patch["patch"]).apply(data, in_place=True) + + +def withext(url, ext): + return re.sub(r"(\.\w+)$", ext, url) + + +@contextmanager +def timeme(message): + begin = time.monotonic() + yield + end = time.monotonic() + log.debug("%sTook %0.02fs", message, end - begin) + + +def build_headers(json_path: pathlib.Path, state: RepodataState): + """Caching headers for a path and state.""" + headers = {} + # simplify if we require state to be empty when json_path is missing. + if json_path.exists(): + etag = state.get("_etag") + if etag: + headers["if-none-match"] = etag + return headers + + +class HashWriter(io.RawIOBase): + def __init__(self, backing, hasher): + self.backing = backing + self.hasher = hasher + + def write(self, b: bytes): + self.hasher.update(b) + return self.backing.write(b) + + def close(self): + self.backing.close() + + +def download_and_hash( + hasher, + url, + json_path: pathlib.Path, + session: Session, + state: RepodataState | None, + is_zst=False, + dest_path: pathlib.Path | None = None, +): + """Download url if it doesn't exist, passing bytes through hasher.update(). + + json_path: Path of old cached data (ignore etag if not exists). + dest_path: Path to write new data. + """ + if dest_path is None: + dest_path = json_path + state = state or RepodataState() + headers = build_headers(json_path, state) + timeout = context.remote_connect_timeout_secs, context.remote_read_timeout_secs + response = session.get(url, stream=True, timeout=timeout, headers=headers) + log.debug("%s %s", url, response.headers) + response.raise_for_status() + length = 0 + # is there a status code for which we must clear the file? + if response.status_code == 200: + if is_zst: + decompressor = zstandard.ZstdDecompressor() + writer = decompressor.stream_writer( + HashWriter(dest_path.open("wb"), hasher), # type: ignore + closefd=True, + ) + else: + writer = HashWriter(dest_path.open("wb"), hasher) + with writer as repodata: + for block in response.iter_content(chunk_size=1 << 14): + repodata.write(block) + if response.request: + try: + length = int(response.headers["Content-Length"]) + except (KeyError, ValueError, AttributeError): + pass + log.info("Download %d bytes %r", length, response.request.headers) + return response # can be 304 not modified + + +def _is_http_error_most_400_codes(e: HTTPError) -> bool: + """ + Determine whether the `HTTPError` is an HTTP 400 error code (except for 416). + """ + if e.response is None: # 404 e.response is falsey + return False + status_code = e.response.status_code + return 400 <= status_code < 500 and status_code != 416 + + +def request_url_jlap_state( + url, + state: RepodataState, + full_download=False, + *, + session: Session, + cache: RepodataCache, + temp_path: pathlib.Path, +) -> dict | None: + jlap_state = state.get(JLAP_KEY, {}) + headers = jlap_state.get(HEADERS, {}) + json_path = cache.cache_path_json + + buffer = JLAP() # type checks + + if ( + full_download + or not (NOMINAL_HASH in state and json_path.exists()) + or not state.should_check_format("jlap") + ): + hasher = hash() + with timeme(f"Download complete {url} "): + # Don't deal with 304 Not Modified if hash unavailable e.g. if + # cached without jlap + if NOMINAL_HASH not in state: + state.pop(ETAG_KEY, None) + state.pop(LAST_MODIFIED_KEY, None) + + try: + if state.should_check_format("zst"): + response = download_and_hash( + hasher, + withext(url, ".json.zst"), + json_path, # makes conditional request if exists + dest_path=temp_path, # writes to + session=session, + state=state, + is_zst=True, + ) + else: + raise JlapSkipZst() + except (JlapSkipZst, HTTPError, zstandard.ZstdError) as e: + if isinstance(e, zstandard.ZstdError): + log.warning( + "Could not decompress %s as zstd. Fall back to .json. (%s)", + mask_anaconda_token(withext(url, ".json.zst")), + e, + ) + if isinstance(e, HTTPError) and not _is_http_error_most_400_codes(e): + raise + if not isinstance(e, JlapSkipZst): + # don't update last-checked timestamp on skip + state.set_has_format("zst", False) + response = download_and_hash( + hasher, + withext(url, ".json"), + json_path, + dest_path=temp_path, + session=session, + state=state, + ) + + # will we use state['headers'] for caching against + state["_mod"] = response.headers.get("last-modified") + state["_etag"] = response.headers.get("etag") + state["_cache_control"] = response.headers.get("cache-control") + + # was not re-hashed if 304 not modified + if response.status_code == 200: + state[NOMINAL_HASH] = state[ON_DISK_HASH] = hasher.hexdigest() + + have = state[NOMINAL_HASH] + + # a jlap buffer with zero patches. the buffer format is (position, + # payload, checksum) where position is the offset from the beginning of + # the file; payload is the leading or trailing checksum or other data; + # and checksum is the running checksum for the file up to that point. + buffer = JLAP([[-1, "", ""], [0, json.dumps({LATEST: have}), ""], [1, "", ""]]) + + else: + have = state[NOMINAL_HASH] + # have_hash = state.get(ON_DISK_HASH) + + need_jlap = True + try: + iv_hex = jlap_state.get("iv", "") + pos = jlap_state.get("pos", 0) + etag = headers.get(ETAG_KEY, None) + jlap_url = withext(url, ".jlap") + log.debug( + "Fetch %s from iv=%s, pos=%s", + mask_anaconda_token(jlap_url), + iv_hex, + pos, + ) + # wrong to read state outside of function, and totally rebuild inside + buffer, jlap_state = fetch_jlap( + jlap_url, + pos=pos, + etag=etag, + iv=bytes.fromhex(iv_hex), + session=session, + ignore_etag=False, + ) + state.set_has_format("jlap", True) + need_jlap = False + except ValueError: + log.info("Checksum not OK on JLAP range request. Retry with complete JLAP.") + except IndexError: + log.exception("IndexError reading JLAP. Invalid file?") + except HTTPError as e: + # If we get a 416 Requested range not satisfiable, the server-side + # file may have been truncated and we need to fetch from 0 + if _is_http_error_most_400_codes(e): + state.set_has_format("jlap", False) + return request_url_jlap_state( + url, + state, + full_download=True, + session=session, + cache=cache, + temp_path=temp_path, + ) + log.info( + "Response code %d on JLAP range request. Retry with complete JLAP.", + e.response.status_code, + ) + + if need_jlap: # retry whole file, if range failed + try: + buffer, jlap_state = fetch_jlap(withext(url, ".jlap"), session=session) + except (ValueError, IndexError) as e: + log.exception("Error parsing jlap", exc_info=e) + # a 'latest' hash that we can't achieve, triggering later error handling + buffer = JLAP( + [[-1, "", ""], [0, json.dumps({LATEST: "0" * 32}), ""], [1, "", ""]] + ) + state.set_has_format("jlap", False) + + state[JLAP_KEY] = jlap_state + + with timeme("Apply Patches "): + # buffer[0] == previous iv + # buffer[1:-2] == patches + # buffer[-2] == footer = new_state["footer"] + # buffer[-1] == trailing checksum + + patches = list(json.loads(patch) for _, patch, _ in buffer.body) + _, footer, _ = buffer.penultimate + want = json.loads(footer)["latest"] + + try: + apply = find_patches(patches, have, want) + log.info( + f"Apply {len(apply)} patches " + f"{format_hash(have)} \N{RIGHTWARDS ARROW} {format_hash(want)}" + ) + + if apply: + with timeme("Load "): + # we haven't loaded repodata yet; it could fail to parse, or + # have the wrong hash. + # if this fails, then we also need to fetch again from 0 + repodata_json = json.loads(cache.load()) + # XXX cache.state must equal what we started with, otherwise + # bail with 'repodata on disk' (indicating another process + # downloaded repodata.json in parallel with us) + if have != cache.state.get(NOMINAL_HASH): # or check mtime_ns? + log.warning("repodata cache changed during jlap fetch.") + return None + + apply_patches(repodata_json, apply) + + with timeme("Write changed "), temp_path.open("wb") as repodata: + hasher = hash() + HashWriter(repodata, hasher).write( + json.dumps(repodata_json, separators=(",", ":")).encode("utf-8") + ) + + # actual hash of serialized json + state[ON_DISK_HASH] = hasher.hexdigest() + + # hash of equivalent upstream json + state[NOMINAL_HASH] = want + + # avoid duplicate parsing + return repodata_json + else: + if state[NOMINAL_HASH] != want: + raise RuntimeError( + f"{NOMINAL_HASH} mismatch. Expected {want}, got {state[NOMINAL_HASH]}." + ) + + except (JlapPatchNotFound, json.JSONDecodeError) as e: + if isinstance(e, JlapPatchNotFound): + # 'have' hash not mentioned in patchset + # + # XXX or skip jlap at top of fn; make sure it is not + # possible to download the complete json twice + log.info( + "Current repodata.json %s not found in patchset. Re-download repodata.json" + ) + + if full_download: + raise RecursionError() + + return request_url_jlap_state( + url, + state, + full_download=True, + session=session, + cache=cache, + temp_path=temp_path, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/interface.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee10eecd685700aba8b5ea6363d6d7a182a5b9f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/jlap/interface.py @@ -0,0 +1,152 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""JLAP interface for repodata.""" + +from __future__ import annotations + +import logging +import os +from typing import TYPE_CHECKING + +from ....base.context import context +from ...connection.download import disable_ssl_verify_warning +from ...connection.session import get_session +from .. import ( + CACHE_CONTROL_KEY, + ETAG_KEY, + LAST_MODIFIED_KEY, + URL_KEY, + RepodataOnDisk, + RepodataState, + RepoInterface, + Response304ContentUnchanged, + conda_http_errors, +) +from . import fetch + +if TYPE_CHECKING: + from .. import RepodataCache + +log = logging.getLogger(__name__) + + +class JlapRepoInterface(RepoInterface): + def __init__( + self, + url: str, + repodata_fn: str | None, + *, + cache: RepodataCache, + **kwargs, + ) -> None: + log.debug("Using %s", self.__class__.__name__) + + self._cache = cache + + self._url = url + self._repodata_fn = repodata_fn + + self._log = logging.getLogger(__name__) + self._stderrlog = logging.getLogger("conda.stderrlog") + + def repodata(self, state: dict | RepodataState) -> str | None: + """ + Fetch newest repodata if necessary. + + Always writes to ``cache_path_json``. + """ + self.repodata_parsed(state) + raise RepodataOnDisk() + + def repodata_parsed(self, state: dict | RepodataState) -> dict | None: + """ + JLAP has to parse the JSON anyway. + + Use this to avoid a redundant parse when repodata is updated. + + When repodata is not updated, it doesn't matter whether this function or + the caller reads from a file. + """ + session = get_session(self._url) + + if not context.ssl_verify: + disable_ssl_verify_warning() + + repodata_url = f"{self._url}/{self._repodata_fn}" + + # XXX won't modify caller's state dict + state_ = self._repodata_state_copy(state) + + # at this point, self._cache.state == state == state_ + + temp_path = ( + self._cache.cache_dir / f"{self._cache.name}.{os.urandom(2).hex()}.tmp" + ) + try: + with conda_http_errors(self._url, self._repodata_fn): + repodata_json_or_none = fetch.request_url_jlap_state( + repodata_url, + state_, + session=session, + cache=self._cache, + temp_path=temp_path, + ) + + # update caller's state dict-or-RepodataState. Do this before + # the self._cache.replace() call which also writes state, then + # signal not to write state to caller. + state.update(state_) + + state[URL_KEY] = self._url + headers = state.get("jlap", {}).get( + "headers" + ) # XXX overwrite headers in jlapper.request_url_jlap_state + if headers: + state[ETAG_KEY] = headers.get("etag") + state[LAST_MODIFIED_KEY] = headers.get("last-modified") + state[CACHE_CONTROL_KEY] = headers.get("cache-control") + + self._cache.state.update(state) + + if temp_path.exists(): + self._cache.replace(temp_path) + except fetch.Jlap304NotModified: + raise Response304ContentUnchanged() + finally: + # Clean up the temporary file. In the successful case it raises + # OSError as self._cache_replace() removed temp_file. + try: + temp_path.unlink() + except OSError: + pass + + if repodata_json_or_none is None: # common + # Indicate that subdir_data mustn't rewrite cache_path_json + raise RepodataOnDisk() + else: + return repodata_json_or_none + + def _repodata_state_copy(self, state: dict | RepodataState): + return RepodataState(dict=state) + + +class RepodataStateSkipFormat(RepodataState): + skip_formats: set[str] + + def __init__(self, *args, skip_formats=set(), **kwargs): + super().__init__(*args, **kwargs) + self.skip_formats = set(skip_formats) + + def should_check_format(self, format): + if format in self.skip_formats: + return False + return super().should_check_format(format) + + +class ZstdRepoInterface(JlapRepoInterface): + """ + Support repodata.json.zst (if available) without checking .jlap + """ + + def _repodata_state_copy(self, state: dict | RepodataState): + return RepodataStateSkipFormat(dict=state, skip_formats=["jlap"]) diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/lock.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/lock.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8621a1aacd7fbaa84d1820c325ca31363b938c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/repodata/lock.py @@ -0,0 +1,9 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Backwards compatibility import. + +Moved to prevent circular imports. +""" + +from ..disk.lock import lock # noqa: F401 diff --git a/miniconda3/lib/python3.13/site-packages/conda/gateways/subprocess.py b/miniconda3/lib/python3.13/site-packages/conda/gateways/subprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..8300903019258ce2fed49d6bad06ea626bd36429 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/gateways/subprocess.py @@ -0,0 +1,164 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Helpler functions for subprocess.""" + +from __future__ import annotations + +import os +import sys +from collections import namedtuple +from logging import getLogger +from os.path import abspath +from subprocess import PIPE, CalledProcessError, Popen +from typing import TYPE_CHECKING + +from .. import ACTIVE_SUBPROCESSES +from ..auxlib.compat import shlex_split_unicode +from ..auxlib.ish import dals +from ..base.context import context +from ..common.compat import encode_environment, isiterable +from ..common.constants import TRACE +from ..gateways.disk.delete import rm_rf +from ..utils import wrap_subprocess_call + +if TYPE_CHECKING: + from collections.abc import Sequence + from pathlib import Path + +log = getLogger(__name__) +Response = namedtuple("Response", ("stdout", "stderr", "rc")) + + +def _format_output(command_str, cwd, rc, stdout, stderr): + return dals( + """ + $ %s + ==> cwd: %s <== + ==> exit code: %d <== + ==> stdout <== + %s + ==> stderr <== + %s + """ + ) % (command_str, cwd, rc, stdout, stderr) + + +def any_subprocess(args: Sequence[str], prefix, env=None, cwd=None): + script_caller, command_args = wrap_subprocess_call( + context.root_prefix, + prefix, + context.dev, + context.debug, + args, + ) + process = Popen( + command_args, + cwd=cwd or prefix, + universal_newlines=False, + stdout=PIPE, + stderr=PIPE, + env=env, + ) + stdout, stderr = process.communicate() + if script_caller is not None: + if "CONDA_TEST_SAVE_TEMPS" not in os.environ: + rm_rf(script_caller) + else: + log.warning( + f"CONDA_TEST_SAVE_TEMPS :: retaining pip run_script {script_caller}" + ) + if hasattr(stdout, "decode"): + stdout = stdout.decode("utf-8", errors="replace") + if hasattr(stderr, "decode"): + stderr = stderr.decode("utf-8", errors="replace") + return stdout, stderr, process.returncode + + +def subprocess_call( + command: str | os.PathLike | Path | Sequence[str | os.PathLike | Path], + env: dict[str, str] | None = None, + path: str | os.PathLike | Path | None = None, + stdin: str | None = None, + raise_on_error: bool = True, + capture_output: bool = True, +): + """This utility function should be preferred for all conda subprocessing. + It handles multiple tricky details. + """ + env = encode_environment(env or os.environ) + cwd = sys.prefix if path is None else abspath(path) + if not isiterable(command): + command = shlex_split_unicode(command) + try: + command_str = os.fspath(command) + except TypeError: + # TypeError: command is not a str or PathLike + command_str = " ".join(map(os.fspath, command)) + log.debug("executing>> %s", command_str) + + pipe = None + if capture_output: + pipe = PIPE + elif stdin: + raise ValueError("When passing stdin, output needs to be captured") + else: + stdin = None + + # spawn subprocess + process = Popen( + command, + cwd=cwd, + stdin=pipe, + stdout=pipe, + stderr=pipe, + env=env, + text=True, # open streams in text mode so that we don't have to decode + errors="replace", + ) + ACTIVE_SUBPROCESSES.add(process) + + # decode output, if not PIPE, stdout/stderr will be None + stdout, stderr = process.communicate(input=stdin) + rc = process.returncode + ACTIVE_SUBPROCESSES.remove(process) + + if (raise_on_error and rc != 0) or log.isEnabledFor(TRACE): + formatted_output = _format_output(command_str, cwd, rc, stdout, stderr) + if raise_on_error and rc != 0: + log.info(formatted_output) + raise CalledProcessError(rc, command, output=formatted_output) + if log.isEnabledFor(TRACE): + log.log(TRACE, formatted_output) + + return Response(stdout, stderr, int(rc)) + + +def _subprocess_clean_env(env, clean_python=True, clean_conda=True): + dels = [] + if clean_python: + dels.extend(("PYTHONPATH", "PYTHONHOME")) + if clean_conda: + dels.extend( + ("CONDA_ROOT", "CONDA_PROMPT_MODIFIER", "CONDA_EXE", "CONDA_DEFAULT_ENV") + ) + for key in dels: + if key in env: + del env[key] + + +def subprocess_call_with_clean_env( + command, + path=None, + stdin=None, + raise_on_error=True, + clean_python=True, + clean_conda=True, +): + # Any of these env vars are likely to mess the whole thing up. + # This has been seen to be the case with PYTHONPATH. + env = os.environ.copy() + _subprocess_clean_env(env, clean_python, clean_conda) + # env['CONDA_DLL_SEARCH_MODIFICATION_ENABLE'] = '1' + return subprocess_call( + command, env=env, path=path, stdin=stdin, raise_on_error=raise_on_error + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/history.py b/miniconda3/lib/python3.13/site-packages/conda/history.py new file mode 100644 index 0000000000000000000000000000000000000000..7947531acbe3146f180e1310271fc8b745082cc3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/history.py @@ -0,0 +1,426 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Tools interfacing with conda's history file.""" + +from __future__ import annotations + +import logging +import os +import re +import sys +import time +import warnings +from ast import literal_eval +from errno import EACCES, EPERM, EROFS +from itertools import islice +from operator import itemgetter +from os.path import isdir, isfile, join +from textwrap import dedent +from typing import TYPE_CHECKING + +from . import __version__ as CONDA_VERSION +from .auxlib.ish import dals +from .base.constants import DEFAULTS_CHANNEL_NAME +from .base.context import context +from .common.compat import ensure_text_type, open_utf8 +from .common.iterators import groupby_to_dict as groupby +from .common.path import paths_equal +from .core.prefix_data import PrefixData +from .exceptions import CondaHistoryError, NotWritableError +from .gateways.disk.update import touch +from .models.dist import dist_str_to_quad +from .models.match_spec import MatchSpec +from .models.version import VersionOrder, version_relation_re + +if TYPE_CHECKING: + from .common.path import PathType + +log = logging.getLogger(__name__) + + +class CondaHistoryWarning(Warning): + pass + + +def write_head(fo): + fo.write("==> {} <==\n".format(time.strftime("%Y-%m-%d %H:%M:%S"))) + fo.write("# cmd: {}\n".format(" ".join(ensure_text_type(s) for s in sys.argv))) + fo.write( + "# conda version: {}\n".format(".".join(islice(CONDA_VERSION.split("."), 3))) + ) + + +def is_diff(content): + return any(s.startswith(("-", "+")) for s in content) + + +def pretty_diff(diff): + added = {} + removed = {} + for s in diff: + fn = s[1:] + name, version, _, channel = dist_str_to_quad(fn) + if channel != DEFAULTS_CHANNEL_NAME: + version += f" ({channel})" + if s.startswith("-"): + removed[name.lower()] = version + elif s.startswith("+"): + added[name.lower()] = version + changed = set(added) & set(removed) + for name in sorted(changed): + yield f" {name} {{{removed[name]} -> {added[name]}}}" + for name in sorted(set(removed) - changed): + yield f"-{name}-{removed[name]}" + for name in sorted(set(added) - changed): + yield f"+{name}-{added[name]}" + + +def pretty_content(content): + if is_diff(content): + return pretty_diff(content) + else: + return iter(sorted(content)) + + +class History: + com_pat = re.compile(r"#\s*cmd:\s*(.+)") + spec_pat = re.compile(r"#\s*(\w+)\s*specs:\s*(.+)?") + conda_v_pat = re.compile(r"#\s*conda version:\s*(.+)") + + def __init__(self, prefix: PathType): + self.prefix = prefix + self.meta_dir = join(prefix, "conda-meta") + self.path = join(self.meta_dir, "history") + + def __enter__(self): + self.init_log_file() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.update() + + def init_log_file(self): + touch(self.path, True) + + def file_is_empty(self): + return os.stat(self.path).st_size == 0 + + def update(self) -> None: + """Update the history file (creating a new one if necessary).""" + try: + try: + last = set(self.get_state()) + except CondaHistoryError as e: + warnings.warn(f"Error in {self.path}: {e}", CondaHistoryWarning) + return + pd = PrefixData(self.prefix) + curr = {prefix_rec.dist_str() for prefix_rec in pd.iter_records()} + self.write_changes(last, curr) + except OSError as e: + if e.errno in (EACCES, EPERM, EROFS): + raise NotWritableError(self.path, e.errno) + else: + raise + + def parse(self) -> list[tuple[str, set[str], list[str]]]: + """Parse the history file. + + Return a list of tuples(datetime strings, set of distributions/diffs, comments). + + Comments appearing before the first section header (e.g. ``==> 2024-01-01 00:00:00 <==``) + in the history file will be ignored. + """ + res = [] + if not isfile(self.path): + return res + sep_pat = re.compile(r"==>\s*(.+?)\s*<==") + with open_utf8(self.path) as f: + lines = f.read().splitlines() + for line in lines: + line = line.strip() + if not line: + continue + m = sep_pat.match(line) + if m: + res.append((m.group(1), set(), [])) + elif line.startswith("#") and res: + res[-1][2].append(line) + elif res: + res[-1][1].add(line) + return res + + @staticmethod + def _parse_old_format_specs_string(specs_string): + """ + Parse specifications string that use conda<4.5 syntax. + + Examples + -------- + - "param >=1.5.1,<2.0'" + - "python>=3.5.1,jupyter >=1.0.0,<2.0,matplotlib >=1.5.1,<2.0" + """ + specs = [] + for spec in specs_string.split(","): + # If the spec starts with a version qualifier, then it actually belongs to the + # previous spec. But don't try to join if there was no previous spec. + if version_relation_re.match(spec) and specs: + specs[-1] = ",".join([specs[-1], spec]) + else: + specs.append(spec) + return specs + + @classmethod + def _parse_comment_line(cls, line): + """ + Parse comment lines in the history file. + + These lines can be of command type or action type. + + Examples + -------- + - "# cmd: /scratch/mc3/bin/conda install -c conda-forge param>=1.5.1,<2.0" + - "# install specs: python>=3.5.1,jupyter >=1.0.0,<2.0,matplotlib >=1.5.1,<2.0" + """ + item = {} + m = cls.com_pat.match(line) + if m: + argv = m.group(1).split() + if argv[0].endswith("conda"): + argv[0] = "conda" + item["cmd"] = argv + + m = cls.conda_v_pat.match(line) + if m: + item["conda_version"] = m.group(1) + + m = cls.spec_pat.match(line) + if m: + action, specs_string = m.groups() + specs_string = specs_string or "" + item["action"] = action + + if specs_string.startswith("["): + specs = literal_eval(specs_string) + elif "[" not in specs_string: + specs = History._parse_old_format_specs_string(specs_string) + + specs = [spec for spec in specs if spec and not spec.endswith("@")] + + if specs and action in ("update", "install", "create"): + item["update_specs"] = item["specs"] = specs + elif specs and action in ("remove", "uninstall"): + item["remove_specs"] = item["specs"] = specs + elif specs and action in ("neutered",): + item["neutered_specs"] = item["specs"] = specs + + return item + + def get_user_requests(self): + """Return a list of user requested items. + + Each item is a dict with the following keys: + 'date': the date and time running the command + 'cmd': a list of argv of the actual command which was run + 'action': install/remove/update + 'specs': the specs being used + """ + res = [] + for dt, unused_cont, comments in self.parse(): + item = {"date": dt} + for line in comments: + comment_items = self._parse_comment_line(line) + item.update(comment_items) + + if "cmd" in item: + res.append(item) + + dists = groupby(itemgetter(0), unused_cont) + item["unlink_dists"] = dists.get("-", ()) + item["link_dists"] = dists.get("+", ()) + + conda_versions_from_history = tuple( + x["conda_version"] for x in res if "conda_version" in x + ) + if conda_versions_from_history and not context.allow_conda_downgrades: + minimum_conda_version = sorted( + conda_versions_from_history, key=VersionOrder + )[-1] + minimum_major_minor = ".".join(islice(minimum_conda_version.split("."), 2)) + current_major_minor = ".".join(islice(CONDA_VERSION.split("."), 2)) + if VersionOrder(current_major_minor) < VersionOrder(minimum_major_minor): + message = dals( + """ + This environment has previously been operated on by a conda version that's newer + than the conda currently being used. A newer version of conda is required. + target environment location: %(target_prefix)s + current conda version: %(conda_version)s + minimum conda version: %(minimum_version)s + """ + ) % { + "target_prefix": self.prefix, + "conda_version": CONDA_VERSION, + "minimum_version": minimum_major_minor, + } + if not paths_equal(self.prefix, context.root_prefix): + message += dedent( + """ + Update conda and try again. + $ conda install -p "%(base_prefix)s" "conda>=%(minimum_version)s" + """ + ) % { + "base_prefix": context.root_prefix, + "minimum_version": minimum_major_minor, + } + message += dedent( + """ + To work around this restriction, one can also set the config parameter + 'allow_conda_downgrades' to False at their own risk. + """ + ) + + # TODO: we need to rethink this. It's fine as a warning to try to get users + # to avoid breaking their system. However, right now it is preventing + # normal conda operation after downgrading conda. + # raise CondaUpgradeError(message) + + return res + + def get_requested_specs_map(self): + # keys are package names and values are specs + spec_map = {} + for request in self.get_user_requests(): + remove_specs = (MatchSpec(spec) for spec in request.get("remove_specs", ())) + for spec in remove_specs: + spec_map.pop(spec.name, None) + update_specs = (MatchSpec(spec) for spec in request.get("update_specs", ())) + spec_map.update((s.name, s) for s in update_specs) + # here is where the neutering takes effect, overriding past values + neutered_specs = ( + MatchSpec(spec) for spec in request.get("neutered_specs", ()) + ) + spec_map.update((s.name, s) for s in neutered_specs) + + # Conda hasn't always been good about recording when specs have been removed from + # environments. If the package isn't installed in the current environment, then we + # shouldn't try to force it here. + prefix_recs = {_.name for _ in PrefixData(self.prefix).iter_records()} + return {name: spec for name, spec in spec_map.items() if name in prefix_recs} + + def construct_states(self): + """Return a list of tuples(datetime strings, set of distributions).""" + res = [] + cur = set() + for dt, cont, unused_com in self.parse(): + if not is_diff(cont): + cur = cont + else: + for s in cont: + if s.startswith("-"): + cur.discard(s[1:]) + elif s.startswith("+"): + cur.add(s[1:]) + else: + raise CondaHistoryError(f"Did not expect: {s}") + res.append((dt, cur.copy())) + return res + + def get_state(self, rev=-1): + """Return the state, i.e. the set of distributions, for a given revision. + + Defaults to latest (which is the same as the current state when + the log file is up-to-date). + + Returns a list of dist_strs. + """ + states = self.construct_states() + if not states: + return set() + times, pkgs = zip(*states) + return pkgs[rev] + + def print_log(self): + for i, (date, content, unused_com) in enumerate(self.parse()): + print("%s (rev %d)" % (date, i)) + for line in pretty_content(content): + print(f" {line}") + print() + + def object_log(self): + result = [] + for i, (date, content, unused_com) in enumerate(self.parse()): + # Based on Mateusz's code; provides more details about the + # history event + event = { + "date": date, + "rev": i, + "install": [], + "remove": [], + "upgrade": [], + "downgrade": [], + } + added = {} + removed = {} + if is_diff(content): + for pkg in content: + name, version, build, channel = dist_str_to_quad(pkg[1:]) + if pkg.startswith("+"): + added[name.lower()] = (version, build, channel) + elif pkg.startswith("-"): + removed[name.lower()] = (version, build, channel) + + changed = set(added) & set(removed) + for name in sorted(changed): + old = removed[name] + new = added[name] + details = { + "old": "-".join((name,) + old), + "new": "-".join((name,) + new), + } + + if new > old: + event["upgrade"].append(details) + else: + event["downgrade"].append(details) + + for name in sorted(set(removed) - changed): + event["remove"].append("-".join((name,) + removed[name])) + + for name in sorted(set(added) - changed): + event["install"].append("-".join((name,) + added[name])) + else: + for pkg in sorted(content): + event["install"].append(pkg) + result.append(event) + return result + + def write_changes(self, last_state, current_state): + if not isdir(self.meta_dir): + os.makedirs(self.meta_dir) + with open(self.path, mode="a", encoding="utf-8") as fo: + write_head(fo) + for fn in sorted(last_state - current_state): + fo.write(f"-{fn}\n") + for fn in sorted(current_state - last_state): + fo.write(f"+{fn}\n") + + def write_specs(self, remove_specs=(), update_specs=(), neutered_specs=()): + remove_specs = [str(MatchSpec(s)) for s in remove_specs] + update_specs = [str(MatchSpec(s)) for s in update_specs] + neutered_specs = [str(MatchSpec(s)) for s in neutered_specs] + if any((update_specs, remove_specs, neutered_specs)): + with open(self.path, mode="a", encoding="utf-8") as fh: + if remove_specs: + fh.write(f"# remove specs: {remove_specs}\n") + if update_specs: + fh.write(f"# update specs: {update_specs}\n") + if neutered_specs: + fh.write(f"# neutered specs: {neutered_specs}\n") + + +if __name__ == "__main__": + from pprint import pprint + + # Don't use in context manager mode---it augments the history every time + h = History(sys.prefix) + pprint(h.get_user_requests()) + print(h.get_requested_specs_map()) diff --git a/miniconda3/lib/python3.13/site-packages/conda/instructions.py b/miniconda3/lib/python3.13/site-packages/conda/instructions.py new file mode 100644 index 0000000000000000000000000000000000000000..c38a07516e94ca52763d0dae2a9a6e56304077ec --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/instructions.py @@ -0,0 +1,108 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Define the instruction set (constants) for conda operations.""" + +from logging import getLogger +from os.path import isfile, join + +from .core.link import UnlinkLinkTransaction +from .core.package_cache_data import ProgressiveFetchExtract +from .exceptions import CondaFileIOError +from .gateways.disk.link import islink + +log = getLogger(__name__) + +# op codes +CHECK_FETCH = "CHECK_FETCH" +FETCH = "FETCH" +CHECK_EXTRACT = "CHECK_EXTRACT" +EXTRACT = "EXTRACT" +RM_EXTRACTED = "RM_EXTRACTED" +RM_FETCHED = "RM_FETCHED" +PRINT = "PRINT" +PROGRESS = "PROGRESS" +SYMLINK_CONDA = "SYMLINK_CONDA" +UNLINK = "UNLINK" +LINK = "LINK" +UNLINKLINKTRANSACTION = "UNLINKLINKTRANSACTION" +PROGRESSIVEFETCHEXTRACT = "PROGRESSIVEFETCHEXTRACT" + + +PROGRESS_COMMANDS = {EXTRACT, RM_EXTRACTED} +ACTION_CODES = ( + CHECK_FETCH, + FETCH, + CHECK_EXTRACT, + EXTRACT, + UNLINK, + LINK, + SYMLINK_CONDA, + RM_EXTRACTED, + RM_FETCHED, +) + + +def PRINT_CMD(state, arg): # pragma: no cover + if arg.startswith(("Unlinking packages", "Linking packages")): + return + getLogger("conda.stdout.verbose").info(arg) + + +def FETCH_CMD(state, package_cache_entry): + raise NotImplementedError() + + +def EXTRACT_CMD(state, arg): + raise NotImplementedError() + + +def PROGRESSIVEFETCHEXTRACT_CMD(state, progressive_fetch_extract): # pragma: no cover + if not isinstance(progressive_fetch_extract, ProgressiveFetchExtract): + raise TypeError( + "'progressive_fetch_extract' must be a ProgressiveFetchExtract instance." + ) + progressive_fetch_extract.execute() + + +def UNLINKLINKTRANSACTION_CMD(state, arg): # pragma: no cover + unlink_link_transaction = arg + if not isinstance(unlink_link_transaction, UnlinkLinkTransaction): + raise TypeError( + "'unlink_link_transaction' must be an UnlinkLinkTransaction instance." + ) + unlink_link_transaction.execute() + + +def check_files_in_package(source_dir, files): + for f in files: + source_file = join(source_dir, f) + if isfile(source_file) or islink(source_file): + return True + else: + raise CondaFileIOError(source_file, f"File {f} does not exist in tarball") + + +# Map instruction to command (a python function) +commands = { + PRINT: PRINT_CMD, + FETCH: FETCH_CMD, + PROGRESS: lambda x, y: None, + EXTRACT: EXTRACT_CMD, + RM_EXTRACTED: lambda x, y: None, + RM_FETCHED: lambda x, y: None, + UNLINK: None, + LINK: None, + SYMLINK_CONDA: lambda x, y: None, + UNLINKLINKTRANSACTION: UNLINKLINKTRANSACTION_CMD, + PROGRESSIVEFETCHEXTRACT: PROGRESSIVEFETCHEXTRACT_CMD, +} + + +OP_ORDER = ( + RM_FETCHED, + FETCH, + RM_EXTRACTED, + EXTRACT, + UNLINK, + LINK, +) diff --git a/miniconda3/lib/python3.13/site-packages/conda/misc.py b/miniconda3/lib/python3.13/site-packages/conda/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..e28be9f09a422f4503c8f3068e373b704985bdca --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/misc.py @@ -0,0 +1,395 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Miscellaneous utility functions.""" + +from __future__ import annotations + +import os +import re +import shutil +from logging import getLogger +from os.path import abspath, dirname, exists, isdir, isfile, join, relpath +from typing import TYPE_CHECKING + +from .base.constants import EXPLICIT_MARKER +from .base.context import context +from .common.compat import on_mac, on_win, open_utf8 +from .common.io import dashlist +from .common.path import expand +from .common.url import is_url, join_url, path_to_url +from .core.index import Index +from .core.link import PrefixSetup, UnlinkLinkTransaction +from .core.package_cache_data import PackageCacheData, ProgressiveFetchExtract +from .core.prefix_data import PrefixData +from .deprecations import deprecated +from .exceptions import ( + DisallowedPackageError, + DryRunExit, + PackagesNotFoundError, + ParseError, + SpecNotFoundInPackageCache, +) +from .gateways.disk.delete import rm_rf +from .gateways.disk.link import islink, readlink, symlink +from .models.match_spec import ChannelMatch, MatchSpec +from .models.prefix_graph import PrefixGraph + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + from typing import Any + + from .models.records import PackageCacheRecord, PackageRecord + + +log = getLogger(__name__) + + +def conda_installed_files(prefix, exclude_self_build=False): + """ + Return the set of files which have been installed (using conda) into + a given prefix. + """ + res = set() + for meta in PrefixData(prefix).iter_records(): + if exclude_self_build and "file_hash" in meta: + continue + res.update(set(meta.get("files", ()))) + return res + + +deprecated.constant( + "26.9", + "27.3", + "url_pat", + re.compile( + r"(?:(?P.+)(?:[/\\]))?" + r"(?P[^/\\#]+(?:\.conda|\.tar\.bz2))" + r"(?:#(" + r"(?P[0-9a-f]{32})" + r"|((sha256:)?(?P[0-9a-f]{64}))" + r"))?$" + ), + addendum="Use `conda.misc._get_url_pattern()` instead.", +) + + +def _get_url_pattern() -> re.Pattern: + """Build URL pattern dynamically based on registered package extensions.""" + extensions = context.plugin_manager.get_package_extractors().keys() + ext_pattern = "|".join(map(re.escape, extensions)) + return re.compile( + r"(?:(?P.+)(?:[/\\]))?" + rf"(?P[^/\\#]+(?:{ext_pattern}))" + r"(?:#(" + r"(?P[0-9a-f]{32})" + r"|((sha256:)?(?P[0-9a-f]{64}))" + r"))?$" + ) + + +def _match_specs_from_explicit(specs: Iterable[str]) -> Iterable[MatchSpec]: + url_pat = _get_url_pattern() + for spec in specs: + if spec == EXPLICIT_MARKER: + continue + + if not is_url(spec): + """ + # This does not work because url_to_path does not enforce Windows + # backslashes. Should it? Seems like a dangerous change to make but + # it would be cleaner. + expanded = expand(spec) + urled = path_to_url(expanded) + pathed = url_to_path(urled) + assert pathed == expanded + """ + spec = path_to_url(expand(spec)) + + # parse URL + m = url_pat.match(spec) + if m is None: + raise ParseError(f"Could not parse explicit URL: {spec}") + url_p, fn = m.group("url_p"), m.group("fn") + url = join_url(url_p, fn) + # url_p is everything but the tarball_basename and the checksum + checksums = {} + if md5 := m.group("md5"): + checksums["md5"] = md5 + if sha256 := m.group("sha256"): + checksums["sha256"] = sha256 + yield MatchSpec(url, **checksums) + + +def explicit( + specs: Iterable[str], + prefix: str, + verbose: bool = False, + force_extract: bool = True, + index: Any = None, + requested_specs: Sequence[str] | None = None, +) -> None: + package_cache_records = get_package_records_from_explicit(specs) + install_explicit_packages( + package_cache_records=package_cache_records, + prefix=prefix, + requested_specs=requested_specs, + ) + + +def install_explicit_packages( + package_cache_records: list[PackageRecord], + prefix: str, + requested_specs: Sequence[str] | None = None, +): + """Install a list of PackageRecords into a prefix""" + specs_pcrecs = tuple([rec.to_match_spec(), rec] for rec in package_cache_records) + + precs_to_remove = [] + prefix_data = PrefixData(prefix) + for q, (spec, pcrec) in enumerate(specs_pcrecs): + new_spec = MatchSpec(spec, name=pcrec.name) + specs_pcrecs[q][0] = new_spec + + prec = prefix_data.get(pcrec.name, None) + if prec: + # If we've already got matching specifications, then don't bother re-linking it + if next(prefix_data.query(new_spec), None): + specs_pcrecs[q][0] = None + else: + precs_to_remove.append(prec) + + # Record user-requested specs in history when provided, otherwise fall back to + # all processed specs for backwards compatibility + if requested_specs: + update_specs_for_history = tuple(MatchSpec(spec) for spec in requested_specs) + else: + update_specs_for_history = tuple(sp[0] for sp in specs_pcrecs if sp[0]) + + stp = PrefixSetup( + prefix, + precs_to_remove, + tuple(sp[1] for sp in specs_pcrecs if sp[0]), + (), + update_specs_for_history, + (), + ) + + txn = UnlinkLinkTransaction(stp) + if not context.json and not context.quiet: + txn.print_transaction_summary() + txn.execute() + + +def _get_package_record_from_specs(specs: list[str]) -> Iterable[PackageCacheRecord]: + """Given a list of specs, find the corresponding PackageCacheRecord. If + some PackageCacheRecords are missing, raise an error. + """ + specs_pcrecs = tuple( + [spec, next(PackageCacheData.query_all(spec), None)] for spec in specs + ) + + # Assert that every spec has a PackageCacheRecord + specs_with_missing_pcrecs = [ + str(spec) for spec, pcrec in specs_pcrecs if pcrec is None + ] + if specs_with_missing_pcrecs: + if len(specs_with_missing_pcrecs) == len(specs_pcrecs): + raise SpecNotFoundInPackageCache("No package cache records found") + else: + missing_precs_list = ", ".join(specs_with_missing_pcrecs) + raise SpecNotFoundInPackageCache( + f"Missing package cache records for: {missing_precs_list}" + ) + return [rec[1] for rec in specs_pcrecs] + + +def get_package_records_from_explicit(lines: list[str]) -> Iterable[PackageCacheRecord]: + """Given the lines from an explicit.txt, create the PackageRecords for each of the + specified packages. This may require downloading the package, if it does not already + exist in the package cache. + """ + # Extract the list of specs + fetch_specs = list(_match_specs_from_explicit(lines)) + + if context.dry_run: + raise DryRunExit() + + # Fetch the packages - if they are already cached nothing new will be downloaded + pfe = ProgressiveFetchExtract(fetch_specs) + pfe.execute() + + # Get the package records from the cache + return _get_package_record_from_specs(fetch_specs) + + +def walk_prefix(prefix, ignore_predefined_files=True, windows_forward_slashes=True): + """Return the set of all files in a given prefix directory.""" + res = set() + prefix = abspath(prefix) + ignore = { + "pkgs", + "envs", + "conda-bld", + "conda-meta", + ".conda_lock", + "users", + "LICENSE.txt", + "info", + "conda-recipes", + ".index", + ".unionfs", + ".nonadmin", + } + binignore = {"conda", "activate", "deactivate"} + if on_mac: + ignore.update({"python.app", "Launcher.app"}) + for fn in (entry.name for entry in os.scandir(prefix)): + if ignore_predefined_files and fn in ignore: + continue + if isfile(join(prefix, fn)): + res.add(fn) + continue + for root, dirs, files in os.walk(join(prefix, fn)): + should_ignore = ignore_predefined_files and root == join(prefix, "bin") + for fn2 in files: + if should_ignore and fn2 in binignore: + continue + res.add(relpath(join(root, fn2), prefix)) + for dn in dirs: + path = join(root, dn) + if islink(path): + res.add(relpath(path, prefix)) + + if on_win and windows_forward_slashes: + return {path.replace("\\", "/") for path in res} + else: + return res + + +def untracked(prefix, exclude_self_build=False): + """Return (the set) of all untracked files for a given prefix.""" + conda_files = conda_installed_files(prefix, exclude_self_build) + return { + path + for path in walk_prefix(prefix) - conda_files + if not ( + path.endswith("~") + or on_mac + and path.endswith(".DS_Store") + or path.endswith(".pyc") + and path[:-1] in conda_files + ) + } + + +@deprecated("25.9", "26.3", addendum="Use PrefixData.set_nonadmin()") +def touch_nonadmin(prefix): + """Creates $PREFIX/.nonadmin if sys.prefix/.nonadmin exists (on Windows).""" + if on_win and exists(join(context.root_prefix, ".nonadmin")): + if not isdir(prefix): + os.makedirs(prefix) + with open_utf8(join(prefix, ".nonadmin"), "w") as fo: + fo.write("") + + +def clone_env(prefix1, prefix2, verbose=True, quiet=False, index_args=None): + """Clone existing prefix1 into new prefix2.""" + untracked_files = untracked(prefix1) + drecs = {prec for prec in PrefixData(prefix1).iter_records()} + + # Resolve URLs for packages that do not have URLs + index = {} + unknowns = [prec for prec in drecs if not prec.get("url")] + notfound = [] + if unknowns: + index_args = index_args or {} + index_args["channels"] = index_args.pop("channel_urls") + index = Index(**index_args) + + for prec in unknowns: + spec = MatchSpec(name=prec.name, version=prec.version, build=prec.build) + precs = tuple(prec for prec in index.values() if spec.match(prec)) + if not precs: + notfound.append(spec) + elif len(precs) > 1: + drecs.remove(prec) + drecs.add(_get_best_prec_match(precs)) + else: + drecs.remove(prec) + drecs.add(precs[0]) + if notfound: + raise PackagesNotFoundError(notfound) + + # Assemble the URL and channel list + urls = {} + for prec in drecs: + urls[prec] = prec["url"] + + precs = tuple(PrefixGraph(urls).graph) + urls = [urls[prec] for prec in precs] + + disallowed = tuple(MatchSpec(s) for s in context.disallowed_packages) + for prec in precs: + if any(d.match(prec) for d in disallowed): + raise DisallowedPackageError(prec) + + if verbose: + print("Packages: %d" % len(precs)) + print("Files: %d" % len(untracked_files)) + + if context.dry_run: + raise DryRunExit() + + for f in untracked_files: + src = join(prefix1, f) + dst = join(prefix2, f) + dst_dir = dirname(dst) + if islink(dst_dir) or isfile(dst_dir): + rm_rf(dst_dir) + if not isdir(dst_dir): + os.makedirs(dst_dir) + if islink(src): + symlink(readlink(src), dst) + continue + + try: + with open_utf8(src, "rb") as fi: + data = fi.read() + except OSError: + continue + + try: + s = data.decode("utf-8") + s = s.replace(prefix1, prefix2) + data = s.encode("utf-8") + except UnicodeDecodeError: # data is binary + pass + + with open_utf8(dst, "wb") as fo: + fo.write(data) + shutil.copystat(src, dst) + + actions = explicit( + urls, + prefix2, + verbose=not quiet, + index=index, + force_extract=False, + ) + return actions, untracked_files + + +def _get_best_prec_match(precs): + if not precs: + raise ValueError("'precs' cannot be empty.") + for channel in context.channels: + channel_matcher = ChannelMatch(channel) + prec_matches = tuple( + prec for prec in precs if channel_matcher.match(prec.channel.name) + ) + if prec_matches: + break + else: + prec_matches = precs + log.warning("Multiple packages found: %s", dashlist(prec_matches)) + return prec_matches[0] diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8865bd1006886c03552ce00b01f0b6d04d6de619 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/__init__.py @@ -0,0 +1,16 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Models are data transfer objects or "light-weight" domain objects with no appreciable logic +other than their own validation. Models are used to pass data between layers of the stack. In +many ways they are similar to ORM objects. Unlike ORM objects, they are NOT themselves allowed +to load data from a remote resource. Thought of another way, they cannot import from +``conda.gateways``, but rather ``conda.gateways`` imports from ``conda.models`` as appropriate +to create model objects from remote resources. + +Conda modules importable from ``conda.models`` are + +- ``conda.common`` +- ``conda.models`` + +""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/channel.py b/miniconda3/lib/python3.13/site-packages/conda/models/channel.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3e97c34e3696ec06e4e65bddcac44e3362d4cc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/channel.py @@ -0,0 +1,741 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Defines Channel and MultiChannel objects and other channel-related functions. + +Object inheritance: + +.. autoapi-inheritance-diagram:: Channel MultiChannel + :top-classes: conda.models.channel.Channel + :parts: 1 +""" + +from __future__ import annotations + +from copy import copy +from logging import getLogger +from typing import TYPE_CHECKING + +from boltons.setutils import IndexedSet + +from ..base.constants import ( + DEFAULTS_CHANNEL_NAME, + MAX_CHANNEL_PRIORITY, + UNKNOWN_CHANNEL, +) +from ..base.context import context +from ..common.compat import ensure_text_type, isiterable +from ..common.path import is_path, win_path_backout +from ..common.url import ( + Url, + has_scheme, + is_url, + join_url, + path_to_url, + percent_decode, + split_conda_url_easy_parts, + split_platform, + split_scheme_auth_token, + urlparse, +) + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from typing import Any + + from ..base.context import Context + from ..common.path import PathType + + +log = getLogger(__name__) + + +class ChannelType(type): + """ + This metaclass does basic caching and enables static constructor method usage with a + single arg. + """ + + def __call__(cls, *args, **kwargs): + if len(args) == 1 and not kwargs: + value = args[0] + if isinstance(value, Channel): + return value + elif value in Channel._cache_: + return Channel._cache_[value] + else: + c = Channel._cache_[value] = Channel.from_value(value) + return c + elif "channels" in kwargs: + # presence of 'channels' kwarg indicates MultiChannel + channels = tuple(cls(**_kwargs) for _kwargs in kwargs["channels"]) + return MultiChannel(kwargs["name"], channels) + else: + return super().__call__(*args, **kwargs) + + +class Channel(metaclass=ChannelType): + """ + Channel: + scheme <> auth <> location <> token <> channel <> subchannel <> platform <> package_filename + + Package Spec: + channel <> subchannel <> namespace <> package_name + + """ + + _cache_ = {} + + @staticmethod + def _reset_state() -> None: + Channel._cache_ = {} + + def __init__( + self, + scheme: str | None = None, + auth: str | None = None, + location: str | None = None, + token: str | None = None, + name: str | None = None, + platform: str | None = None, + package_filename: str | None = None, + ): + self.scheme = scheme + self.auth = auth + self.location = location + self.token = token + self.name = name or "" + self.platform = platform + self.package_filename = package_filename + + @property + def channel_location(self) -> str | None: + return self.location + + @property + def channel_name(self) -> str: + return self.name + + @property + def subdir(self) -> str | None: + return self.platform + + @staticmethod + def from_url(url: str) -> Channel: + return parse_conda_channel_url(url) + + @staticmethod + def from_channel_name(channel_name: str) -> Channel: + return _get_channel_for_name(channel_name) + + @staticmethod + def from_value(value: str | None) -> Channel: + """Construct a new :class:`Channel` from a single value. + + Args: + value: Anyone of the following forms: + + `None`, or one of the special strings "", "None:///", or "None": + represents the unknown channel, used for packages with unknown origin. + + A URL including a scheme like ``file://`` or ``https://``: + represents a channel URL. + + A local directory path: + represents a local channel; relative paths must start with ``./``. + + A package file (i.e. the path to a file ending in ``.conda`` or ``.tar.bz2``): + represents a channel for a single package + + A known channel name: + represents a known channel, e.g. from the users ``.condarc`` file or + the global configuration. + + Returns: + A channel object. + """ + if value in (None, "", "None:///", "None"): + return Channel(name=UNKNOWN_CHANNEL) + value = ensure_text_type(value) + if has_scheme(value): + if value.startswith("file:"): + value = win_path_backout(value) + return Channel.from_url(value) + elif is_path(value): + return Channel.from_url(path_to_url(value)) + elif context.plugin_manager.has_package_extension(value): + if value.startswith("file:"): + value = win_path_backout(value) + return Channel.from_url(value) + else: + # at this point assume we don't have a bare (non-scheme) url + # e.g. this would be bad: repo.anaconda.com/pkgs/free + _stripped, platform = split_platform(context.known_subdirs, value) + if _stripped in context.custom_multichannels: + return MultiChannel( + _stripped, context.custom_multichannels[_stripped], platform + ) + else: + return Channel.from_channel_name(value) + + @staticmethod + def make_simple_channel( + channel_alias: Channel, channel_url: str, name: str | None = None + ) -> Channel: + ca = channel_alias + test_url, scheme, auth, token = split_scheme_auth_token(channel_url) + if name and scheme: + return Channel( + scheme=scheme, + auth=auth, + location=test_url, + token=token, + name=name.strip("/"), + ) + if scheme: + if ca.location and test_url.startswith(ca.location): + location, name = ca.location, test_url.replace(ca.location, "", 1) + else: + url_parts = urlparse(test_url) + location = str(Url(hostname=url_parts.hostname, port=url_parts.port)) + name = url_parts.path or "" + return Channel( + scheme=scheme, + auth=auth, + location=location, + token=token, + name=name.strip("/"), + ) + else: + return Channel( + scheme=ca.scheme, + auth=ca.auth, + location=ca.location, + token=ca.token, + name=name and name.strip("/") or channel_url.strip("/"), + ) + + @property + def canonical_name(self) -> str: + try: + return self.__canonical_name + except AttributeError: + pass + + for multiname, channels in context.custom_multichannels.items(): + for channel in channels: + if self.name == channel.name: + cn = self.__canonical_name = multiname + return cn + + for that_name in context.custom_channels: + if self.name and tokenized_startswith( + self.name.split("/"), that_name.split("/") + ): + cn = self.__canonical_name = self.name + return cn + + if any( + alias.location == self.location + for alias in ( + context.channel_alias, + *context.migrated_channel_aliases, + ) + ): + cn = self.__canonical_name = self.name + return cn + + # fall back to the equivalent of self.base_url + # re-defining here because base_url for MultiChannel is None + if self.scheme: + cn = self.__canonical_name = ( + f"{self.scheme}://{join_url(self.location, self.name)}" + ) + return cn + else: + cn = self.__canonical_name = join_url(self.location, self.name).lstrip("/") + return cn + + def urls( + self, + with_credentials: bool = False, + subdirs: Iterable[str] | None = None, + ) -> list[str]: + """Generate URLs for this channel across specified platforms. + + Args: + with_credentials: If True, include authentication credentials (token, auth) in URLs. + subdirs: Specific platform subdirs to generate URLs for. If None, uses the channel's + platform (if defined) or falls back to `context.subdirs`. If this is explicitly + provided, overrides any platform defined in the channel. + + Examples: + >>> channel = Channel("conda-forge") + >>> channel.urls() # Uses context.subdirs + ['https://conda.anaconda.org/conda-forge/linux-64', + 'https://conda.anaconda.org/conda-forge/noarch'] + + >>> channel = Channel("conda-forge/linux-aarch64") + >>> channel.urls() # Uses channel's platform + ['https://conda.anaconda.org/conda-forge/linux-aarch64', + 'https://conda.anaconda.org/conda-forge/noarch'] + + >>> channel.urls(subdirs=("osx-64", "noarch")) + ['https://conda.anaconda.org/conda-forge/osx-64', + 'https://conda.anaconda.org/conda-forge/noarch'] + + Returns: + list[str]: List of URLs for accessing this channel's specified subdirectories. + """ + if subdirs is not None and not isiterable(subdirs): + raise ValueError( + f"`subdirs` must be an iterable of strings. Got: {subdirs}." + ) + + if self.canonical_name == UNKNOWN_CHANNEL: + return Channel(DEFAULTS_CHANNEL_NAME).urls(with_credentials, subdirs) + + base = [self.location] + if with_credentials and self.token: + base.extend(["t", self.token]) + base.append(self.name) + base = join_url(*base) + + def _platforms() -> Iterator[str]: + # kwargs 'subdir' takes precedence, if passed explicitly + if subdirs is not None: + yield from subdirs + elif self.platform: + yield self.platform + if self.platform != "noarch": + yield "noarch" + else: + yield from context.subdirs + + bases = (join_url(base, p) for p in _platforms()) + if with_credentials and self.auth: + return [f"{self.scheme}://{self.auth}@{b}" for b in bases] + else: + return [f"{self.scheme}://{b}" for b in bases] + + def url(self, with_credentials: bool = False) -> str | None: + if self.canonical_name == UNKNOWN_CHANNEL: + return None + + base = [self.location] + if with_credentials and self.token: + base.extend(["t", self.token]) + base.append(self.name) + if self.platform: + base.append(self.platform) + if self.package_filename: + base.append(self.package_filename) + else: + first_non_noarch = next( + (s for s in context.subdirs if s != "noarch"), "noarch" + ) + base.append(first_non_noarch) + + base = join_url(*base) + + if with_credentials and self.auth: + return f"{self.scheme}://{self.auth}@{base}" + else: + return f"{self.scheme}://{base}" + + @property + def base_url(self) -> str | None: + if self.canonical_name == UNKNOWN_CHANNEL: + return None + return f"{self.scheme}://{join_url(self.location, self.name)}" + + @property + def base_urls(self) -> tuple[str | None, ...]: + return (self.base_url,) + + @property + def subdir_url(self) -> str: + url = self.url(True) + if self.package_filename and url: + url = url.rsplit("/", 1)[0] + return url + + @property + def channels(self) -> tuple[Channel, ...]: + return (self,) + + def __str__(self) -> str: + base = self.base_url or self.name + if self.subdir: + return join_url(base, self.subdir) + else: + return base + + def __repr__(self) -> str: + return 'Channel("%s")' % ( + join_url(self.name, self.subdir) if self.subdir else self.name + ) + + def __eq__(self, other: Any) -> bool: + if isinstance(other, Channel): + return ( + self.location == other.location + and self.name == other.name + and self.platform == other.platform + ) + else: + try: + _other = Channel(other) + return ( + self.location == _other.location + and self.name == _other.name + and self.platform == _other.platform + ) + except Exception as e: + log.debug("%r", e) + return False + + def __hash__(self) -> int: + return hash((self.location, self.name, self.platform)) + + def __nonzero__(self) -> bool: + return any((self.location, self.name)) + + def __bool__(self) -> bool: + return self.__nonzero__() + + def __json__(self) -> dict[str, Any]: + return self.__dict__ + + @property + def url_channel_wtf(self) -> tuple[str | None, str]: + return self.base_url, self.canonical_name + + def dump(self) -> dict[str, Any]: + return { + "scheme": self.scheme, + "auth": self.auth, + "location": self.location, + "token": self.token, + "name": self.name, + "platform": self.platform, + "package_filename": self.package_filename, + } + + +class MultiChannel(Channel): + def __init__( + self, + name: str, + channels: Iterable[Channel], + platform: str | None = None, + ): + self.name = name + self.location = None + + # assume all channels are Channels (not MultiChannels) + if platform: + channels = ( + Channel(**{**channel.dump(), "platform": platform}) + for channel in channels + ) + self._channels = tuple(channels) + + self.scheme = None + self.auth = None + self.token = None + self.platform = platform + self.package_filename = None + + @property + def canonical_name(self) -> str: + return self.name + + def urls( + self, + with_credentials: bool = False, + subdirs: Iterable[str] | None = None, + ) -> list[str]: + return [ + url + for channel in self.channels + for url in channel.urls(with_credentials, subdirs) + ] + + @property + def base_url(self) -> None: + return None + + @property + def base_urls(self) -> tuple[str | None, ...]: + return tuple(channel.base_url for channel in self.channels) + + def url(self, with_credentials: bool = False) -> None: + return None + + @property + def channels(self) -> tuple[Channel, ...]: + return self._channels + + def dump(self) -> dict[str, Any]: + return { + "name": self.name, + "channels": tuple(channel.dump() for channel in self.channels), + } + + +def tokenized_startswith( + test_iterable: Iterable[Any], startswith_iterable: Iterable[Any] +) -> bool: + return all(t == sw for t, sw in zip(test_iterable, startswith_iterable)) + + +def tokenized_conda_url_startswith( + test_url: Iterable[str], startswith_url: Iterable[str] +) -> bool: + test_url, startswith_url = urlparse(test_url), urlparse(startswith_url) + if ( + test_url.hostname != startswith_url.hostname + or test_url.port != startswith_url.port + ): + return False + norm_url_path = lambda url: url.path.strip("/") or "/" + return tokenized_startswith( + norm_url_path(test_url).split("/"), norm_url_path(startswith_url).split("/") + ) + + +def _get_channel_for_name(channel_name: str) -> Channel: + def _get_channel_for_name_helper(name: str) -> Channel | None: + if name in context.custom_channels: + return context.custom_channels[name] + else: + test_name = name.rsplit("/", 1)[0] # progressively strip off path segments + if test_name == name: + return None + return _get_channel_for_name_helper(test_name) + + _stripped, platform = split_platform(context.known_subdirs, channel_name) + channel = _get_channel_for_name_helper(_stripped) + + if channel is not None: + # stripping off path threw information away from channel_name (i.e. any potential subname) + # channel.name *should still be* channel_name + channel = copy(channel) + channel.name = _stripped + if platform: + channel.platform = platform + return channel + else: + ca = context.channel_alias + return Channel( + scheme=ca.scheme, + auth=ca.auth, + location=ca.location, + token=ca.token, + name=_stripped, + platform=platform, + ) + + +def _read_channel_configuration( + scheme: str | None, host: str | None, port: str | None, path: str | None +) -> tuple[str | None, str | None, str | None, str | None, str | None]: + # return location, name, scheme, auth, token + + path = path and path.rstrip("/") + test_url = str(Url(hostname=host, port=port, path=path)) + + # Step 1. No path given; channel name is None + if not path: + return ( + str(Url(hostname=host, port=port)).rstrip("/"), + None, + scheme or None, + None, + None, + ) + + # Step 2. migrated_custom_channels matches + for name, location in sorted( + context.migrated_custom_channels.items(), reverse=True, key=lambda x: len(x[0]) + ): + location, _scheme, _auth, _token = split_scheme_auth_token(location) + if tokenized_conda_url_startswith(test_url, join_url(location, name)): + # translate location to new location, with new credentials + subname = test_url.replace(join_url(location, name), "", 1).strip("/") + channel_name = join_url(name, subname) + channel = _get_channel_for_name(channel_name) + return ( + channel.location, + channel_name, + channel.scheme, + channel.auth, + channel.token, + ) + + # Step 3. migrated_channel_aliases matches + for migrated_alias in context.migrated_channel_aliases: + if test_url.startswith(migrated_alias.location): + name = test_url.replace(migrated_alias.location, "", 1).strip("/") + ca = context.channel_alias + return ca.location, name, ca.scheme, ca.auth, ca.token + + # Step 4. custom_channels matches + for name, channel in sorted( + context.custom_channels.items(), reverse=True, key=lambda x: len(x[0]) + ): + that_test_url = join_url(channel.location, channel.name) + if tokenized_startswith(test_url.split("/"), that_test_url.split("/")): + subname = test_url.replace(that_test_url, "", 1).strip("/") + return ( + channel.location, + join_url(channel.name, subname), + scheme, + channel.auth, + channel.token, + ) + + # Step 5. channel_alias match + ca = context.channel_alias + if ca.location and tokenized_startswith( + test_url.split("/"), ca.location.split("/") + ): + name = test_url.replace(ca.location, "", 1).strip("/") or None + return ca.location, name, scheme, ca.auth, ca.token + + # Step 6. not-otherwise-specified file://-type urls + if host is None: + # this should probably only happen with a file:// type url + if port is not None: + raise ValueError("Port should not be set if host is not set either.") + location, name = test_url.rsplit("/", 1) + if not location: + location = "/" + _scheme, _auth, _token = "file", None, None + return location, name, _scheme, _auth, _token + + # Step 7. fall through to host:port as channel_location and path as channel_name + # but bump the first token of paths starting with /conda for compatibility with + # Anaconda Enterprise Repository software. + bump = None + path_parts = path.strip("/").split("/") + if path_parts and path_parts[0] == "conda": + bump, path = "conda", "/".join(path_parts[1:]) + return ( + str(Url(hostname=host, port=port, path=bump)).rstrip("/"), + path.strip("/") or None, + scheme or None, + None, + None, + ) + + +def parse_conda_channel_url(url: str) -> Channel: + ( + scheme, + auth, + token, + platform, + package_filename, + host, + port, + path, + query, + ) = split_conda_url_easy_parts(context.known_subdirs, url) + + # recombine host, port, path to get a channel_name and channel_location + ( + channel_location, + channel_name, + configured_scheme, + configured_auth, + configured_token, + ) = _read_channel_configuration(scheme, host, port, path) + + # if we came out with no channel_location or channel_name, we need to figure it out + # from host, port, path + if channel_location is None and channel_name is None: + raise ValueError("channel_location and channel_name cannot both be None") + # These two fields might have URL-encodable characters that we should decode + # We don't decode the full URL because some %XX values might be part of some auth values + if channel_name: + channel_name = percent_decode(channel_name) + if package_filename: + package_filename = percent_decode(package_filename) + + return Channel( + configured_scheme or "https", + auth or configured_auth, + channel_location, + token or configured_token, + channel_name, + platform, + package_filename, + ) + + +# backward compatibility for conda-build +def get_conda_build_local_url() -> tuple[PathType]: + return (context.local_build_root,) + + +def prioritize_channels( + channels: Iterable[Channel | str], + with_credentials: bool = True, + subdirs: Iterable[str] | None = None, +) -> dict[str, tuple[str, int]]: + """Make a dictionary of channel priorities. + + Maps channel names to priorities, e.g.: + + .. code-block:: pycon + + >>> prioritize_channels(["conda-canary", "defaults", "conda-forge"]) + { + 'https://conda.anaconda.org/conda-canary/osx-arm64': ('conda-canary', 0), + 'https://conda.anaconda.org/conda-canary/noarch': ('conda-canary', 0), + 'https://repo.anaconda.com/pkgs/main/osx-arm64': ('defaults', 1), + 'https://repo.anaconda.com/pkgs/main/noarch': ('defaults', 1), + 'https://repo.anaconda.com/pkgs/r/osx-arm64': ('defaults', 2), + 'https://repo.anaconda.com/pkgs/r/noarch': ('defaults', 2), + 'https://conda.anaconda.org/conda-forge/osx-arm64': ('conda-forge', 3), + 'https://conda.anaconda.org/conda-forge/noarch': ('conda-forge', 3), + } + + Compare with ``conda.resolve.Resolve._make_channel_priorities``. + """ + channels = (channel for name in channels for channel in Channel(name).channels) + result = {} + for priority_counter, channel in enumerate(channels): + for url in channel.urls(with_credentials, subdirs): + if url in result: + continue + result[url] = ( + channel.canonical_name, + min(priority_counter, MAX_CHANNEL_PRIORITY - 1), + ) + return result + + +def all_channel_urls( + channels: Iterable[str | Channel], + subdirs: Iterable[str] | None = None, + with_credentials: bool = True, +) -> IndexedSet: + result = IndexedSet() + for chn in channels: + channel = Channel(chn) + result.update(channel.urls(with_credentials, subdirs)) + return result + + +def offline_keep(url: Any) -> bool: + return not context.offline or not is_url(url) or url.startswith("file:/") + + +def get_channel_objs(ctx: Context) -> tuple[Channel, ...]: + """Return current channels as Channel objects""" + return tuple(Channel(chn) for chn in ctx.channels) + + +context.register_reset_callaback(Channel._reset_state) diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/dist.py b/miniconda3/lib/python3.13/site-packages/conda/models/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..20fb20150ea4255870488cf312c9722a24e39338 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/dist.py @@ -0,0 +1,375 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""(Legacy) Low-level implementation of a Channel.""" + +import re +from logging import getLogger +from typing import NamedTuple + +from .. import CondaError +from ..auxlib.entity import Entity, EntityType, IntegerField, StringField +from ..base.constants import ( + DEFAULTS_CHANNEL_NAME, + UNKNOWN_CHANNEL, +) +from ..base.context import context +from ..common.compat import ensure_text_type +from ..common.constants import NULL +from ..common.url import has_platform, is_url, join_url +from .channel import Channel +from .package_info import PackageInfo +from .records import PackageRecord + +log = getLogger(__name__) + + +class DistDetails(NamedTuple): + name: str + version: str + build_string: str + build_number: str + dist_name: str + fmt: str + + +class DistType(EntityType): + def __call__(cls, *args, **kwargs): + if len(args) == 1 and not kwargs: + value = args[0] + if value in Dist._cache_: + return Dist._cache_[value] + elif isinstance(value, Dist): + dist = value + elif isinstance(value, PackageRecord): + dist = Dist.from_string( + value.fn, channel_override=value.channel.canonical_name + ) + elif hasattr(value, "dist") and isinstance(value.dist, Dist): + dist = value.dist + elif isinstance(value, PackageInfo): + dist = Dist.from_string( + value.repodata_record.fn, + channel_override=value.channel.canonical_name, + ) + elif isinstance(value, Channel): + dist = Dist.from_url(value.url()) + else: + dist = Dist.from_string(value) + Dist._cache_[value] = dist + return dist + else: + return super().__call__(*args, **kwargs) + + +# TODO: Consider deprecating in favor of conda.common.path.strip_pkg_extension +def strip_extension(original_dist: str) -> str: + if ext := context.plugin_manager.has_package_extension(original_dist): + return original_dist[: -len(ext)] + return original_dist + + +# TODO: Consider deprecating in favor of conda.common.path.strip_pkg_extension +def split_extension(original_dist: str) -> tuple[str, str]: + if ext := context.plugin_manager.has_package_extension(original_dist): + return original_dist[: -len(ext)], ext + return original_dist, "" + + +class Dist(Entity, metaclass=DistType): + _cache_ = {} + _lazy_validate = True + + channel = StringField(required=False, nullable=True, immutable=True) + + dist_name = StringField(immutable=True) + name = StringField(immutable=True) + fmt = StringField(immutable=True) + version = StringField(immutable=True) + build_string = StringField(immutable=True) + build_number = IntegerField(immutable=True) + + base_url = StringField(required=False, nullable=True, immutable=True) + platform = StringField(required=False, nullable=True, immutable=True) + + def __init__( + self, + channel, + dist_name=None, + name=None, + version=None, + build_string=None, + build_number=None, + base_url=None, + platform=None, + fmt=".tar.bz2", + ): + super().__init__( + channel=channel, + dist_name=dist_name, + name=name, + version=version, + build_string=build_string, + build_number=build_number, + base_url=base_url, + platform=platform, + fmt=fmt, + ) + + def to_package_ref(self): + return PackageRecord( + channel=self.channel, + subdir=self.platform, + name=self.name, + version=self.version, + build=self.build_string, + build_number=self.build_number, + ) + + @property + def full_name(self): + return self.__str__() + + @property + def build(self): + return self.build_string + + @property + def subdir(self): + return self.platform + + @property + def pair(self): + return self.channel or DEFAULTS_CHANNEL_NAME, self.dist_name + + @property + def quad(self): + # returns: name, version, build_string, channel + parts = self.dist_name.rsplit("-", 2) + ["", ""] + return parts[0], parts[1], parts[2], self.channel or DEFAULTS_CHANNEL_NAME + + def __str__(self): + return f"{self.channel}::{self.dist_name}" if self.channel else self.dist_name + + @property + def is_feature_package(self): + return self.dist_name.endswith("@") + + @property + def is_channel(self): + return bool(self.base_url and self.platform) + + def to_filename(self, extension=None): + if self.is_feature_package: + return self.dist_name + else: + return self.dist_name + self.fmt + + def to_matchspec(self): + return " ".join(self.quad[:3]) + + def to_match_spec(self): + from .match_spec import MatchSpec + + base = "=".join(self.quad[:3]) + return MatchSpec(f"{self.channel}::{base}" if self.channel else base) + + @classmethod + def from_string(cls, string, channel_override=NULL): + string = str(string) + + if is_url(string) and channel_override == NULL: + return cls.from_url(string) + + if string.endswith("@"): + return cls( + channel="@", + name=string, + version="", + build_string="", + build_number=0, + dist_name=string, + ) + + REGEX_STR = ( + r"(?:([^\s\[\]]+)::)?" # optional channel + r"([^\s\[\]]+)" # 3.x dist + r"(?:\[([a-zA-Z0-9_-]+)\])?" # with_features_depends + ) + channel, original_dist, w_f_d = re.search(REGEX_STR, string).groups() + + original_dist, fmt = split_extension(original_dist) + + if channel_override != NULL: + channel = channel_override + if not channel: + channel = UNKNOWN_CHANNEL + + # enforce dist format + dist_details = cls.parse_dist_name(original_dist) + return cls( + channel=channel, + name=dist_details.name, + version=dist_details.version, + build_string=dist_details.build_string, + build_number=dist_details.build_number, + dist_name=original_dist, + fmt=fmt, + ) + + @staticmethod + def parse_dist_name(string): + original_string = string + try: + string = ensure_text_type(string) + no_fmt_string, fmt = split_extension(string) + + # remove any directory or channel information + if "::" in no_fmt_string: + dist_name = no_fmt_string.rsplit("::", 1)[-1] + else: + dist_name = no_fmt_string.rsplit("/", 1)[-1] + + parts = dist_name.rsplit("-", 2) + + name = parts[0] + version = parts[1] + build_string = parts[2] if len(parts) >= 3 else "" + build_number_as_string = "".join( + filter( + lambda x: x.isdigit(), + (build_string.rsplit("_")[-1] if build_string else "0"), + ) + ) + build_number = int(build_number_as_string) if build_number_as_string else 0 + + return DistDetails( + name, version, build_string, build_number, dist_name, fmt + ) + + except: + raise CondaError( + f"dist_name is not a valid conda package: {original_string}" + ) + + @classmethod + def from_url(cls, url): + if not is_url(url): + raise ValueError("'{url}' does not seem to be a valid URL") + if not context.plugin_manager.has_package_extension(url) and "::" not in url: + raise CondaError(f"url '{url}' is not a conda package") + + dist_details = cls.parse_dist_name(url) + if "::" in url: + url_no_tarball = url.rsplit("::", 1)[0] + platform = context.subdir + base_url = url_no_tarball.split("::")[0] + channel = str(Channel(base_url)) + else: + url_no_tarball = url.rsplit("/", 1)[0] + platform = has_platform(url_no_tarball, context.known_subdirs) + base_url = url_no_tarball.rsplit("/", 1)[0] if platform else url_no_tarball + channel = Channel(base_url).canonical_name if platform else UNKNOWN_CHANNEL + + return cls( + channel=channel, + name=dist_details.name, + version=dist_details.version, + build_string=dist_details.build_string, + build_number=dist_details.build_number, + dist_name=dist_details.dist_name, + base_url=base_url, + platform=platform, + fmt=dist_details.fmt, + ) + + def to_url(self): + if not self.base_url: + return None + filename = self.dist_name + self.fmt + return ( + join_url(self.base_url, self.platform, filename) + if self.platform + else join_url(self.base_url, filename) + ) + + def __key__(self): + return self.channel, self.dist_name + + def __lt__(self, other): + if not isinstance(other, self.__class__): + raise TypeError( + "Can only compare with objects of the same type. " + f"Left side is {type(self)}, and right side is {type(other)}" + ) + return self.__key__() < other.__key__() + + def __gt__(self, other): + if not isinstance(other, self.__class__): + raise TypeError( + "Can only compare with objects of the same type. " + f"Left side is {type(self)}, and right side is {type(other)}" + ) + return self.__key__() > other.__key__() + + def __le__(self, other): + if not isinstance(other, self.__class__): + raise TypeError( + "Can only compare with objects of the same type. " + f"Left side is {type(self)}, and right side is {type(other)}" + ) + return self.__key__() <= other.__key__() + + def __ge__(self, other): + if not isinstance(other, self.__class__): + raise TypeError( + "Can only compare with objects of the same type. " + f"Left side is {type(self)}, and right side is {type(other)}" + ) + return self.__key__() >= other.__key__() + + def __hash__(self): + # dists compare equal regardless of fmt, but fmt is taken into account for + # object identity + return hash((self.__key__(), self.fmt)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__key__() == other.__key__() + + def __ne__(self, other): + return not self.__eq__(other) + + # ############ conda-build compatibility ################ + + def split(self, sep=None, maxsplit=-1): + if sep != "::": + raise ValueError("'sep' can only be '::'") + return [self.channel, self.dist_name] if self.channel else [self.dist_name] + + def rsplit(self, sep=None, maxsplit=-1): + if sep != "-": + raise ValueError("'sep' can only be '-'") + if maxsplit != 2: + raise ValueError("'maxsplit' can only be 2") + name = f"{self.channel}::{self.quad[0]}" if self.channel else self.quad[0] + return name, self.quad[1], self.quad[2] + + def startswith(self, match): + return self.dist_name.startswith(match) + + def __contains__(self, item): + item = strip_extension(ensure_text_type(item)) + return item in self.__str__() + + @property + def fn(self): + return self.to_filename() + + +def dist_str_to_quad(dist_str): + dist_str = strip_extension(dist_str) + if "::" in dist_str: + channel_str, dist_str = dist_str.split("::", 1) + else: + channel_str = UNKNOWN_CHANNEL + name, version, build = dist_str.rsplit("-", 2) + return name, version, build, channel_str diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/enums.py b/miniconda3/lib/python3.13/site-packages/conda/models/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..fea63125b52555558634190224da8a150923d0ab --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/enums.py @@ -0,0 +1,185 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of enums used throughout conda.""" + +import sys +from enum import Enum +from platform import machine + +from ..auxlib.decorators import classproperty +from ..auxlib.ish import dals +from ..auxlib.type_coercion import TypeCoercionError, boolify +from ..deprecations import deprecated +from ..exceptions import CondaUpgradeError + + +class Arch(Enum): + x86 = "x86" + x86_64 = "x86_64" + # arm64 is for macOS and Windows + arm64 = "arm64" + armv6l = "armv6l" + armv7l = "armv7l" + # aarch64 is for Linux only + aarch64 = "aarch64" + ppc64 = "ppc64" + ppc64le = "ppc64le" + riscv64 = "riscv64" + s390x = "s390x" + wasm32 = "wasm32" + z = "z" + + @classmethod + def from_sys(cls): + if sys.platform == "zos": + return cls["z"] + return cls[machine()] + + def __json__(self): + return self.value + + +class Platform(Enum): + freebsd = "freebsd" + linux = "linux" + win = "win32" + openbsd = "openbsd5" + osx = "darwin" + zos = "zos" + emscripten = "emscripten" + wasi = "wasi" + + @classmethod + def from_sys(cls): + return cls(sys.platform) + + def __json__(self): + return self.value + + +class FileMode(Enum): + text = "text" + binary = "binary" + + def __str__(self): + return f"{self.value}" + + +class LinkType(Enum): + # directory is not a link type, and copy is not a path type + # LinkType is still probably the best name here + hardlink = 1 + softlink = 2 + copy = 3 + directory = 4 + + def __int__(self): + return self.value + + def __str__(self): + return self.name + + def __json__(self): + return self.name + + +class PathEnum(Enum): + """ + Refers to if the file in question is hard linked or soft linked. Originally designed to be used + in paths.json + """ + + hardlink = "hardlink" + softlink = "softlink" + directory = "directory" + + # these additional types should not be included by conda-build in packages + linked_package_record = ( + "linked_package_record" # a package's .json file in conda-meta + ) + pyc_file = "pyc_file" + unix_python_entry_point = "unix_python_entry_point" + windows_python_entry_point_script = "windows_python_entry_point_script" + windows_python_entry_point_exe = "windows_python_entry_point_exe" + + @classproperty + def basic_types(self): + return (PathEnum.hardlink, PathEnum.softlink, PathEnum.directory) + + def __str__(self): + return self.name + + def __json__(self): + return self.name + + +deprecated.constant( + deprecate_in="26.9", + remove_in="27.3", + constant="PathType", + value=PathEnum, + addendum="Use `conda.models.enums.PathEnum` instead.", +) + + +class PackageType(Enum): + NOARCH_GENERIC = "noarch_generic" + NOARCH_PYTHON = "noarch_python" + VIRTUAL_PRIVATE_ENV = "virtual_private_env" + VIRTUAL_PYTHON_WHEEL = "virtual_python_wheel" # manageable + VIRTUAL_PYTHON_EGG_MANAGEABLE = "virtual_python_egg_manageable" + VIRTUAL_PYTHON_EGG_UNMANAGEABLE = "virtual_python_egg_unmanageable" + VIRTUAL_PYTHON_EGG_LINK = "virtual_python_egg_link" # unmanageable + VIRTUAL_SYSTEM = "virtual_system" # virtual packages representing system attributes + + @staticmethod + def conda_package_types(): + return { + None, + PackageType.NOARCH_GENERIC, + PackageType.NOARCH_PYTHON, + } + + @staticmethod + def unmanageable_package_types(): + return { + PackageType.VIRTUAL_PYTHON_EGG_UNMANAGEABLE, + PackageType.VIRTUAL_PYTHON_EGG_LINK, + PackageType.VIRTUAL_SYSTEM, + } + + +class NoarchType(Enum): + generic = "generic" + python = "python" + + @staticmethod + def coerce(val): + # what a mess + if isinstance(val, NoarchType): + return val + valtype = getattr(val, "type", None) + if isinstance(valtype, NoarchType): # see issue #8311 + return valtype + if isinstance(val, bool): + val = NoarchType.generic if val else None + if isinstance(val, str): + val = val.lower() + if val == "python": + val = NoarchType.python + elif val == "generic": + val = NoarchType.generic + else: + try: + val = NoarchType.generic if boolify(val, nullable=True) else None + except TypeCoercionError: + raise CondaUpgradeError( + dals( + f""" + The noarch type for this package is set to '{val}'. + The current version of conda is too old to install this package. + Please update conda. + """ + ) + ) + return val diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/environment.py b/miniconda3/lib/python3.13/site-packages/conda/models/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..da3f2fdd7d30a465fb71f58076284b56dc8cd748 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/environment.py @@ -0,0 +1,585 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""EXPERIMENTAL Conda environment data model""" + +from __future__ import annotations + +from dataclasses import dataclass, field, fields, replace +from functools import reduce +from itertools import chain +from logging import getLogger +from typing import TYPE_CHECKING + +from ..base.constants import EXPLICIT_MARKER, PLATFORMS, UNKNOWN_CHANNEL +from ..base.context import context + +# TODO: this cli import will be removed once the Environment.from_cli method +# is updated to use the environment spec plugins to read environment files. +from ..cli.common import specs_from_url +from ..common.iterators import groupby_to_dict as groupby +from ..core.prefix_data import PrefixData +from ..exceptions import CondaError, CondaValueError +from ..history import History +from ..misc import get_package_records_from_explicit +from .match_spec import MatchSpec + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Iterable + from typing import TypeVar + + from ..base.constants import ( + ChannelPriority, + DepsModifier, + SatSolverChoice, + UpdateModifier, + ) + from ..common.path import PathType + from .records import PackageRecord + + T = TypeVar("T") + +log = getLogger(__name__) + + +@dataclass +class EnvironmentConfig: + """ + **Experimental** While experimental, expect both major and minor changes across minor releases. + + Data model for a conda environment config. + """ + + aggressive_update_packages: tuple[str, ...] = field(default_factory=tuple) + + channel_priority: ChannelPriority | None = None + + channels: tuple[str, ...] = field(default_factory=tuple) + + channel_settings: tuple[dict[str, str], ...] = field(default_factory=tuple) + + deps_modifier: DepsModifier | None = None + + disallowed_packages: tuple[str, ...] = field(default_factory=tuple) + + pinned_packages: tuple[str, ...] = field(default_factory=tuple) + + repodata_fns: tuple[str, ...] = field(default_factory=tuple) + + sat_solver: SatSolverChoice | None = None + + solver: str | None = None + + track_features: tuple[str, ...] = field(default_factory=tuple) + + update_modifier: UpdateModifier | None = None + + use_only_tar_bz2: bool | None = None + + def _append_without_duplicates( + self, first: Iterable[T], second: Iterable[T] + ) -> tuple[T, ...]: + return tuple(dict.fromkeys(item for item in chain(first, second))) + + def _merge_channel_settings( + self, first: tuple[dict[str, str], ...], second: tuple[dict[str, str], ...] + ) -> tuple[dict[str, str], ...]: + """Merge channel settings. + + An individual channel setting is a dict that may have the key "channels". Settings + with matching "channels" should be merged together. + """ + + grouped_channel_settings = groupby( + lambda x: x.get("channel"), chain(first, second) + ) + + return tuple( + {k: v for config in configs for k, v in config.items()} + for channel, configs in grouped_channel_settings.items() + ) + + def _merge(self, other: EnvironmentConfig) -> EnvironmentConfig: + """ + **Experimental** While experimental, expect both major and minor changes across minor releases. + + Merges an EnvironmentConfig into this one. Merging rules are: + * Primitive types get clobbered if subsequent configs have a value, otherwise keep the last set value + * Lists get appended to and deduplicated + * Dicts get updated + * Special cases: + * channel settings is a list of dicts, it merges inner dicts, keyed on "channel" + """ + # Return early if there is nothing to merge + if other is None: + return self + + # Ensure that we are merging another EnvironmentConfig + if not isinstance(other, self.__class__): + raise CondaValueError( + "Cannot merge EnvironmentConfig with non-EnvironmentConfig" + ) + + self.aggressive_update_packages = self._append_without_duplicates( + self.aggressive_update_packages, other.aggressive_update_packages + ) + + if other.channel_priority is not None: + self.channel_priority = other.channel_priority + + self.channels = self._append_without_duplicates(self.channels, other.channels) + + self.channel_settings = self._merge_channel_settings( + self.channel_settings, other.channel_settings + ) + + if other.deps_modifier is not None: + self.deps_modifier = other.deps_modifier + + self.disallowed_packages = self._append_without_duplicates( + self.disallowed_packages, other.disallowed_packages + ) + + self.pinned_packages = self._append_without_duplicates( + self.pinned_packages, other.pinned_packages + ) + + self.repodata_fns = self._append_without_duplicates( + self.repodata_fns, other.repodata_fns + ) + + if other.sat_solver is not None: + self.sat_solver = other.sat_solver + + if other.solver is not None: + self.solver = other.solver + + self.track_features = self._append_without_duplicates( + self.track_features, other.track_features + ) + + if other.update_modifier is not None: + self.update_modifier = other.update_modifier + + if other.use_only_tar_bz2 is not None: + self.use_only_tar_bz2 = other.use_only_tar_bz2 + + return self + + @classmethod + def from_context(cls) -> EnvironmentConfig: + """ + **Experimental** While experimental, expect both major and minor changes across minor releases. + + Create an EnvironmentConfig from the current context + """ + field_names = {field.name for field in fields(cls)} + + environment_settings = { + key: value + for key, value in context.environment_settings.items() + if key in field_names + } + return cls(**environment_settings) + + @classmethod + def merge(cls, *configs: EnvironmentConfig) -> EnvironmentConfig: + """ + **Experimental** While experimental, expect both major and minor changes across minor releases. + + Merges a list of EnvironmentConfigs into a single one. Merging rules are: + * Primitive types get clobbered if subsequent configs have a value, otherwise keep the last set value + * Lists get appended to and deduplicated + * Dicts get updated + """ + + # Don't try to merge if there is nothing to merge + if not configs: + return + + # If there is only one config, there is nothing to merge, return the lone config + if len(configs) == 1: + return configs[0] + + # Use reduce to merge all configs into the first one + return reduce( + lambda result, config: result._merge(config), configs[1:], configs[0] + ) + + +@dataclass(kw_only=True) +class Environment: + """ + **Experimental** While experimental, expect both major and minor changes across minor releases. + + Data model for a conda environment. + """ + + platform: str + """The platform this environment may be installed on (required).""" + + config: EnvironmentConfig = field(default_factory=EnvironmentConfig) + """Environment level configuration, eg. channels, solver options, etc. + + TODO: may need to think more about the type of this field and how + conda should be merging configs between environments. + """ + + external_packages: dict[str, list[str]] = field(default_factory=dict) + """Map of other package types that conda can install. For example pypi packages.""" + + explicit_packages: list[PackageRecord] = field(default_factory=list) + """The complete list of specs for the environment. + + E.g. after a solve, or from an explicit environment spec. + """ + + name: str | None = None + """Environment name.""" + + prefix: str | None = None + """Prefix the environment is installed into.""" + + requested_packages: list[MatchSpec] = field(default_factory=list) + """User requested specs for this environment.""" + + variables: dict[str, str] = field(default_factory=dict) + """Environment variables to be applied to the environment.""" + + # Virtual packages for the environment. Either the default ones provided by + # the virtual_packages plugins or the overrides captured by CONDA_OVERRIDE_*. + virtual_packages: list[PackageRecord] = field(default_factory=list) + + def __post_init__(self): + # an environment must have a platform + if not self.platform: + raise CondaValueError("'Environment' needs a 'platform'.") + + # ensure the platform is valid + if self.platform not in PLATFORMS: + raise CondaValueError( + f"Invalid platform '{self.platform}'. Valid platforms are {PLATFORMS}." + ) + + # ensure there are no duplicate packages in explicit_packages + if len(self.explicit_packages) > 1 and len( + set(pkg.name for pkg in self.explicit_packages) + ) != len(self.explicit_packages): + raise CondaValueError("Duplicate packages found in 'explicit_packages'.") + + # ensure requested_packages matches one (and only one) explicit package + if len(self.requested_packages) > 0 and len(self.explicit_packages) > 0: + explicit_package_names = set(pkg.name for pkg in self.explicit_packages) + for requested_package in self.requested_packages: + if requested_package.name not in explicit_package_names: + raise CondaValueError( + f"Requested package '{requested_package}' is not found in 'explicit_packages'." + ) + + @classmethod + def merge(cls, *environments): + """ + **Experimental** While experimental, expect both major and minor changes across minor releases. + + Merges multiple environments into a single environment following the rules: + * Keeps first name and/or prefix. + * Concatenates and deduplicates requirements. + * Reduces configuration and variables (last key wins). + """ + name = None + prefix = None + platform = None + names = [env.name for env in environments if env.name] + prefixes = [env.prefix for env in environments if env.prefix] + + if names: + name = names[0] + if len(names) > 1: + log.debug("Several names passed %s. Picking first one %s", names, name) + + if prefixes: + prefix = prefixes[0] + if len(prefixes) > 1: + log.debug( + "Several prefixes passed %s. Picking first one %s", prefixes, prefix + ) + + platforms = [env.platform for env in environments if env.platform] + # Ensure that all environments have the same platform + if len(set(platforms)) == 1: + platform = platforms[0] + else: + raise CondaValueError( + "Conda can not merge environments of different platforms. " + f"Received environments with platforms: {platforms}" + ) + + requested_packages = list( + dict.fromkeys( + requirement + for env in environments + for requirement in env.requested_packages + ) + ) + + explicit_packages = list( + dict.fromkeys( + requirement + for env in environments + for requirement in env.explicit_packages + ) + ) + + virtual_packages = list( + dict.fromkeys( + virtual_package + for env in environments + for virtual_package in env.virtual_packages + ) + ) + + variables = {k: v for env in environments for (k, v) in env.variables.items()} + + external_packages = {} + for env in environments: + # External packages map values are always lists of strings. So, + # we'll want to concatenate each list. + for k, v in env.external_packages.items(): + if k in external_packages: + for val in v: + if val not in external_packages[k]: + external_packages[k].append(val) + elif isinstance(v, list): + external_packages[k] = v + + config = EnvironmentConfig.merge( + *[env.config for env in environments if env.config is not None] + ) + + return cls( + config=config, + external_packages=external_packages, + explicit_packages=explicit_packages, + name=name, + platform=platform, + prefix=prefix, + requested_packages=requested_packages, + variables=variables, + virtual_packages=virtual_packages, + ) + + @classmethod + def from_prefix( + cls, + prefix: str, + name: str, + platform: str, + *, + from_history: bool = False, + no_builds: bool = False, + ignore_channels: bool = False, + channels: list[str] | None = None, + ) -> Environment: + """ + Create an Environment model from an existing conda prefix. + + This method analyzes an installed conda environment and creates + an Environment model that can be used for exporting or other operations. + + :param prefix: Path to the conda environment prefix + :param name: Name for the environment + :param platform: Target platform (e.g., 'linux-64', 'osx-64') + :param from_history: Use explicit specs from history instead of installed packages + :param no_builds: Exclude build strings from package specs + :param ignore_channels: Don't include channel information in package specs + :return: Environment model representing the prefix + """ + prefix_data = PrefixData(prefix, interoperability=True) + variables = prefix_data.get_environment_env_vars() + + # Build requested packages and external packages + requested_packages = [] + external_packages = {} + + # Handle --from-history case + if from_history: + requested_packages = cls.from_history(prefix) + conda_precs = [] # No conda packages to process for channel extraction + else: + # Use PrefixData's package extraction methods + conda_precs = prefix_data.get_conda_packages() + python_precs = prefix_data.get_python_packages() + + # Create MatchSpecs for conda packages + for conda_prec in conda_precs: + spec_str = conda_prec.spec_no_build if no_builds else conda_prec.spec + + if ( + not ignore_channels + and conda_prec.channel + and conda_prec.channel.name + ): + spec_str = f"{conda_prec.channel.name}::{spec_str}" + + requested_packages.append(MatchSpec(spec_str)) + + # Add pip dependencies to external_packages if any exist + if python_precs: + # Create pip dependencies list matching current conda format + python_deps = [ + f"{python_prec.name}=={python_prec.version}" + for python_prec in python_precs + ] + external_packages["pip"] = python_deps + + # Always populate explicit_packages from prefix data (for explicit export format) + explicit_packages = list(prefix_data.iter_records()) + + # Build channels tuple + environment_channels = tuple(channels or ()) + + # Inject channels from installed conda packages (unless ignoring channels) + # This applies regardless of override_channels setting + if not ignore_channels: + environment_channels = ( + *( + canonical_name + # Reuse conda_precs instead of calling get_conda_packages() again + for conda_package in conda_precs + if (canonical_name := conda_package.channel.canonical_name) + != UNKNOWN_CHANNEL + ), + *environment_channels, + ) + + # Channels tuple is a unique ordered sequence + environment_channels = tuple(dict.fromkeys(environment_channels)) + + # Create environment config with comprehensive context settings + config = EnvironmentConfig.from_context() + + # Override/set channels with those extracted from installed packages if any were found + config = replace(config, channels=environment_channels) + + return cls( + prefix=prefix, + platform=platform, + name=name, + config=config, + variables=variables, + external_packages=external_packages, + requested_packages=requested_packages, + explicit_packages=explicit_packages, + ) + + @classmethod + def from_cli( + cls, + args: Namespace, + add_default_packages: bool = False, + ) -> Environment: + """ + Create an Environment model from command-line arguments. + + This method will parse command-line arguments and create an + Environment object. This includes: reading files provided as + cli arguments, and pulling EnvironmentConfig from the context. + + :param args: argparse Namespace containing command-line arguments + :return: An Environment object representing the cli + """ + specs = [package.strip("\"'") for package in args.packages] + requested_packages = [] + fetch_explicit_packages = [] + + # extract specs from files + # TODO: This should be replaced with reading files using the + # environment spec plugin. The core conda cli commands are not + # ready for that yet. So, use this old way of reading specs from + # files. + for fpath in args.file: + try: + specs.extend( + [spec for spec in specs_from_url(fpath) if spec != EXPLICIT_MARKER] + ) + except UnicodeError: + raise CondaError( + "Error reading file, file should be a text file containing packages\n" + "See `conda create --help` for details." + ) + + # Add default packages if required. If the default package is already + # present in the list of specs, don't add it (this will override any + # version constraint from the default package). + if add_default_packages: + names = {MatchSpec(spec).name for spec in specs} + for default_package in context.create_default_packages: + if MatchSpec(default_package).name not in names: + specs.append(default_package) + + for spec in specs: + if (match_spec := MatchSpec(spec)).get("url"): + fetch_explicit_packages.append(spec) + else: + requested_packages.append(match_spec) + + # transform explicit packages into package records + explicit_packages = [] + if fetch_explicit_packages: + if len(fetch_explicit_packages) == len(specs): + explicit_packages = get_package_records_from_explicit( + fetch_explicit_packages + ) + else: + raise CondaValueError( + "Cannot mix specifications with conda package filenames" + ) + + return Environment( + name=args.name, + prefix=context.target_prefix, + platform=context.subdir, + requested_packages=requested_packages, + explicit_packages=explicit_packages, + config=EnvironmentConfig.from_context(), + ) + + @staticmethod + def from_history(prefix: PathType) -> list[MatchSpec]: + history = History(prefix) + spec_map = history.get_requested_specs_map() + # Get MatchSpec objects from history; they'll be serialized to bracket format later + return list(spec_map.values()) + + def extrapolate(self, platform: str) -> Environment: + """ + Given the current environment, extrapolate the environment for the given platform. + """ + if platform == self.platform: + return self + + from ..cli.install import Repodatas + + solver_backend = context.plugin_manager.get_cached_solver_backend() + requested_packages = self.from_history(self.prefix) + + for repodata_manager in Repodatas(self.config.repodata_fns, {}): + with repodata_manager as repodata_fn: + solver = solver_backend( + prefix="/env/does/not/exist", + channels=context.channels, + subdirs=(platform, "noarch"), + specs_to_add=requested_packages, + repodata_fn=repodata_fn, + command="create", + ) + explicit_packages = solver.solve_final_state() + return Environment( + prefix=self.prefix, + name=self.name, + platform=platform, + config=EnvironmentConfig.from_context(), + requested_packages=requested_packages, + explicit_packages=explicit_packages, + external_packages=self.external_packages, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/match_spec.py b/miniconda3/lib/python3.13/site-packages/conda/models/match_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..cbfe3344bcb006e6c9ec47c8288e1f5ec67f8fdd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/match_spec.py @@ -0,0 +1,1210 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Implements the query language for conda packages (a.k.a, MatchSpec). + +The MatchSpec is the conda package specification (e.g. `conda==23.3`, `python<3.7`, +`cryptography * *_0`) and is used to communicate the desired packages to install. +""" + +from __future__ import annotations + +import re +import warnings +from abc import ABCMeta, abstractmethod, abstractproperty +from collections.abc import Mapping +from functools import reduce +from itertools import chain +from logging import getLogger +from operator import attrgetter +from os.path import basename + +from ..auxlib.decorators import memoizedproperty +from ..base.constants import CONDA_PACKAGE_EXTENSION_V1, CONDA_PACKAGE_EXTENSION_V2 +from ..base.context import context +from ..common.compat import isiterable +from ..common.io import dashlist +from ..common.iterators import groupby_to_dict as groupby +from ..common.path import expand, strip_pkg_extension, url_to_path +from ..common.url import is_url, path_to_url, unquote +from ..exceptions import InvalidMatchSpec, InvalidSpec +from .channel import Channel +from .version import BuildNumberMatch, VersionSpec + +try: + from frozendict import frozendict +except ImportError: + from ..auxlib.collection import frozendict + +log = getLogger(__name__) + + +class MatchSpecType(type): + def __call__(cls, spec_arg=None, **kwargs): + try: + if spec_arg: + if isinstance(spec_arg, MatchSpec) and not kwargs: + return spec_arg + elif isinstance(spec_arg, MatchSpec): + new_kwargs = dict(spec_arg._match_components) + new_kwargs.setdefault("optional", spec_arg.optional) + new_kwargs.setdefault("target", spec_arg.target) + new_kwargs["_original_spec_str"] = spec_arg.original_spec_str + new_kwargs.update(**kwargs) + return super().__call__(**new_kwargs) + elif isinstance(spec_arg, str): + parsed = _parse_spec_str(spec_arg) + if kwargs: + parsed = dict(parsed, **kwargs) + if set(kwargs) - {"optional", "target"}: + # if kwargs has anything but optional and target, + # strip out _original_spec_str from parsed + parsed.pop("_original_spec_str", None) + return super().__call__(**parsed) + elif isinstance(spec_arg, Mapping): + parsed = dict(spec_arg, **kwargs) + return super().__call__(**parsed) + elif hasattr(spec_arg, "to_match_spec"): + spec = spec_arg.to_match_spec() + if kwargs: + return MatchSpec(spec, **kwargs) + else: + return spec + else: + raise InvalidSpec( + f"Invalid MatchSpec:\n spec_arg={spec_arg}\n kwargs={kwargs}" + ) + else: + return super().__call__(**kwargs) + except InvalidSpec as e: + msg = "" + if spec_arg: + msg += f"{spec_arg}" + if kwargs: + msg += " " + ", ".join(f"{k}={v}" for k, v in kwargs.items()) + raise InvalidMatchSpec(msg, details=e) from e + + +class MatchSpec(metaclass=MatchSpecType): + """The query language for conda packages. + + Any of the fields that comprise a :class:`PackageRecord` can be used to compose a + :class:`MatchSpec`. + + :class:`MatchSpec` can be composed with keyword arguments, where keys are any of the + attributes of :class:`PackageRecord`. Values for keyword arguments are the exact values the + attribute should match against. Many fields can also be matched against non-exact values--by + including wildcard `*` and `>`/`<` ranges--where supported. Any non-specified field is + the equivalent of a full wildcard match. + + :class:`MatchSpec` can also be composed using a single positional argument, with optional + keyword arguments. Keyword arguments also override any conflicting information provided in + the positional argument. The positional argument can be either an existing :class:`MatchSpec` + instance or a string. Conda has historically supported more than one string representation + for equivalent :class:`MatchSpec` queries. This :class:`MatchSpec` should accept any existing + valid spec string, and correctly compose a :class:`MatchSpec` instance. + + A series of rules are now followed for creating the canonical string representation of a + :class:`MatchSpec` instance. The canonical string representation can generically be + represented by + + (channel(/subdir):(namespace):)name(version(build))[key1=value1,key2=value2] + + where `()` indicate optional fields. The rules for constructing a canonical string + representation are: + + 1. `name` (i.e. "package name") is required, but its value can be '*'. Its position is always + outside the key-value brackets. + 2. If `version` is an exact version, it goes outside the key-value brackets and is prepended + by `==`. If `version` is a "fuzzy" value (e.g. `1.11.*`), it goes outside the key-value + brackets with the `.*` left off and is prepended by `=`. Otherwise `version` is included + inside key-value brackets. + 3. If `version` is an exact version, and `build` is an exact value, `build` goes outside + key-value brackets prepended by a `=`. Otherwise, `build` goes inside key-value brackets. + `build_string` is an alias for `build`. + 4. The `namespace` position is being held for a future conda feature. + 5. If `channel` is included and is an exact value, a `::` separator is ued between `channel` + and `name`. `channel` can either be a canonical channel name or a channel url. In the + canonical string representation, the canonical channel name will always be used. + 6. If `channel` is an exact value and `subdir` is an exact value, `subdir` is appended to + `channel` with a `/` separator. Otherwise, `subdir` is included in the key-value brackets. + 7. Key-value brackets can be delimited by comma, space, or comma+space. Value can optionally + be wrapped in single or double quotes, but must be wrapped if `value` contains a comma, + space, or equal sign. The canonical format uses comma delimiters and single quotes. + 8. When constructing a :class:`MatchSpec` instance from a string, any key-value pair given + inside the key-value brackets overrides any matching parameter given outside the brackets. + + When :class:`MatchSpec` attribute values are simple strings, the are interpreted using the + following conventions: + + - If the string begins with `^` and ends with `$`, it is converted to a regex. + - If the string contains an asterisk (`*`), it is transformed from a glob to a regex. + - Otherwise, an exact match to the string is sought. + + + Examples: + >>> str(MatchSpec(name='foo', build='py2*', channel='conda-forge')) + 'conda-forge::foo[build=py2*]' + >>> str(MatchSpec('foo 1.0 py27_0')) + 'foo==1.0=py27_0' + >>> str(MatchSpec('foo=1.0=py27_0')) + 'foo==1.0=py27_0' + >>> str(MatchSpec('conda-forge::foo[version=1.0.*]')) + 'conda-forge::foo=1.0' + >>> str(MatchSpec('conda-forge/linux-64::foo>=1.0')) + "conda-forge/linux-64::foo[version='>=1.0']" + >>> str(MatchSpec('*/linux-64::foo>=1.0')) + "foo[subdir=linux-64,version='>=1.0']" + + To fully-specify a package with a full, exact spec, the fields + - channel + - subdir + - name + - version + - build + must be given as exact values. In the future, the namespace field will be added to this list. + Alternatively, an exact spec is given by '*[md5=12345678901234567890123456789012]' + or '*[sha256=f453db4ffe2271ec492a2913af4e61d4a6c118201f07de757df0eff769b65d2e]'. + """ + + FIELD_NAMES = ( + "channel", + "subdir", + "name", + "version", + "build", + "build_number", + "track_features", + "features", + "url", + "md5", + "sha256", + "license", + "license_family", + "fn", + ) + FIELD_NAMES_SET = frozenset(FIELD_NAMES) + _MATCHER_CACHE = {} + + def __init__(self, optional=False, target=None, **kwargs): + self._optional = optional + self._target = target + self._original_spec_str = kwargs.pop("_original_spec_str", None) + self._match_components = self._build_components(**kwargs) + + @classmethod + def from_dist_str(cls, dist_str): + parts = {} + if dist_str[-len(CONDA_PACKAGE_EXTENSION_V2) :] == CONDA_PACKAGE_EXTENSION_V2: + dist_str = dist_str[: -len(CONDA_PACKAGE_EXTENSION_V2)] + elif dist_str[-len(CONDA_PACKAGE_EXTENSION_V1) :] == CONDA_PACKAGE_EXTENSION_V1: + dist_str = dist_str[: -len(CONDA_PACKAGE_EXTENSION_V1)] + if "::" in dist_str: + channel_subdir_str, dist_str = dist_str.split("::", 1) + if "/" in channel_subdir_str: + channel_str, subdir = channel_subdir_str.rsplit("/", 1) + if subdir not in context.known_subdirs: + channel_str = channel_subdir_str + subdir = None + parts["channel"] = channel_str + if subdir: + parts["subdir"] = subdir + else: + parts["channel"] = channel_subdir_str + + name, version, build = dist_str.rsplit("-", 2) + parts.update( + { + "name": name, + "version": version, + "build": build, + } + ) + return cls(**parts) + + def get_exact_value(self, field_name): + v = self._match_components.get(field_name) + return v and v.exact_value + + def get_raw_value(self, field_name): + v = self._match_components.get(field_name) + return v and v.raw_value + + def get(self, field_name, default=None): + v = self.get_raw_value(field_name) + return default if v is None else v + + @property + def is_name_only_spec(self): + return ( + len(self._match_components) == 1 + and "name" in self._match_components + and self.name != "*" + ) + + def dist_str(self): + return self.__str__() + + @property + def optional(self): + return self._optional + + @property + def target(self): + return self._target + + @property + def original_spec_str(self): + return self._original_spec_str + + def match(self, rec): + """ + Accepts a `PackageRecord` or a dict, and matches can pull from any field + in that record. Returns True for a match, and False for no match. + """ + if isinstance(rec, dict): + # TODO: consider AttrDict instead of PackageRecord + from .records import PackageRecord + + rec = PackageRecord.from_objects(rec) + for field_name, v in self._match_components.items(): + if not self._match_individual(rec, field_name, v): + return False + return True + + def _match_individual(self, record, field_name, match_component): + val = getattr(record, field_name) + try: + return match_component.match(val) + except AttributeError: + return match_component == val + + def _is_simple(self): + return ( + len(self._match_components) == 1 + and self.get_exact_value("name") is not None + ) + + def _is_single(self): + return len(self._match_components) == 1 + + def _to_filename_do_not_use(self): + # WARNING: this is potentially unreliable and use should probably be limited + # returns None if a filename can't be constructed + fn_field = self.get_exact_value("fn") + if fn_field: + return fn_field + vals = tuple(self.get_exact_value(x) for x in ("name", "version", "build")) + if not any(x is None for x in vals): + return ("{}-{}-{}".format(*vals)) + CONDA_PACKAGE_EXTENSION_V1 + else: + return None + + def __repr__(self): + builder = [f'{self.__class__.__name__}("{self}"'] + if self.target: + builder.append(f', target="{self.target}"') + if self.optional: + builder.append(", optional=True") + builder.append(")") + return "".join(builder) + + def __str__(self): + builder = [] + brackets = [] + + channel_matcher = self._match_components.get("channel") + if channel_matcher and channel_matcher.exact_value: + builder.append(str(channel_matcher)) + elif channel_matcher and not channel_matcher.matches_all: + brackets.append(f"channel={str(channel_matcher)}") + + subdir_matcher = self._match_components.get("subdir") + if subdir_matcher: + if channel_matcher and channel_matcher.exact_value: + builder.append(f"/{subdir_matcher}") + else: + brackets.append(f"subdir={subdir_matcher}") + + name_matcher = self._match_components.get("name", "*") + builder.append(("::%s" if builder else "%s") % name_matcher) + + version = self._match_components.get("version") + build = self._match_components.get("build") + version_exact = False + if version: + version = str(version) + if any(s in version for s in "><$^|,"): + brackets.append(f"version='{version}'") + elif version[:2] in ("!=", "~="): + if build: + brackets.append(f"version='{version}'") + else: + builder.append(version) + elif version[-2:] == ".*": + builder.append("=" + version[:-2]) + # Skip wildcard-only versions, to avoid an empty "=" in the output. + # See https://github.com/conda/conda/issues/14357 for more info. + elif version == "*": + pass + elif version[-1] == "*": + builder.append("=" + version[:-1]) + elif version.startswith("=="): + builder.append(version) + version_exact = True + else: + builder.append("==" + version) + version_exact = True + + if build: + build = str(build) + if any(s in build for s in "><$^|,"): + brackets.append(f"build='{build}'") + elif "*" in build: + brackets.append(f"build={build}") + elif version_exact: + builder.append("=" + build) + else: + brackets.append(f"build={build}") + + _skip = {"channel", "subdir", "name", "version", "build"} + if "url" in self._match_components and "fn" in self._match_components: + _skip.add("fn") + for key in self.FIELD_NAMES: + if key not in _skip and key in self._match_components: + if key == "url" and channel_matcher: + # skip url in canonical str if channel already included + continue + value = str(self._match_components[key]) + if any(s in value for s in ", ="): + brackets.append(f"{key}='{value}'") + else: + brackets.append(f"{key}={value}") + + if brackets: + builder.append("[{}]".format(",".join(brackets))) + + return "".join(builder) + + def __json__(self): + return self.__str__() + + def conda_build_form(self): + builder = [] + name = self.get_exact_value("name") + if not name: + raise ValueError(".conda_build_form() requires a non-empty spec name.") + builder.append(name) + + build = self.get_raw_value("build") + version = self.get_raw_value("version") + + if build: + version = version or "*" + builder += [version, build] + elif version: + builder.append(version) + + return " ".join(builder) + + def conda_env_form(self): + """ + Return the package specification in conda environment export format. + + This produces the format used by `conda env export`: name=version=build + (single equals), without channel prefixes and without .* patterns. + + Examples: + >>> MatchSpec("numpy==1.21.0=py39h1234567_0").conda_env_form() + 'numpy=1.21.0=py39h1234567_0' + >>> MatchSpec("numpy=1.21.0").conda_env_form() # no-builds case + 'numpy=1.21.0' + >>> MatchSpec("conda-forge::numpy==1.21.0=py39h1234567_0").conda_env_form() + 'numpy=1.21.0=py39h1234567_0' # channel prefix removed + + Returns: + str: Package specification in conda env export format + """ + # Get the full string representation (avoids .* patterns) + spec_str = str(self) + + # Remove channel prefix if present (e.g., "conda-forge::package" -> "package") + if "::" in spec_str: + spec_str = spec_str.split("::", 1)[1] + + # Convert MatchSpec format (name==version=build) to conda env format (name=version=build) + if "==" in spec_str: + spec_str = spec_str.replace("==", "=", 1) # Only replace first occurrence + + return spec_str + + def __eq__(self, other): + if isinstance(other, MatchSpec): + return self._hash_key == other._hash_key + else: + return False + + def __hash__(self): + return hash(self._hash_key) + + @memoizedproperty + def _hash_key(self): + return self._match_components, self.optional, self.target + + def __contains__(self, field): + return field in self._match_components + + def _build_components(self, **kwargs): + not_fields = set(kwargs) - MatchSpec.FIELD_NAMES_SET + if not_fields: + raise InvalidMatchSpec( + self._original_spec_str, f"Cannot match on field(s): {not_fields}" + ) + _make_component = MatchSpec._make_component + return frozendict(_make_component(key, value) for key, value in kwargs.items()) + + @staticmethod + def _make_component(field_name, value): + if hasattr(value, "match"): + matcher = value + return field_name, matcher + + _MATCHER_CACHE = MatchSpec._MATCHER_CACHE + cache_key = (field_name, value) + cached_matcher = _MATCHER_CACHE.get(cache_key) + if cached_matcher: + return field_name, cached_matcher + if field_name in _implementors: + matcher = _implementors[field_name](value) + else: + matcher = ExactStrMatch(str(value)) + _MATCHER_CACHE[(field_name, value)] = matcher + return field_name, matcher + + @property + def name(self): + return self.get_exact_value("name") or "*" + + # + # Remaining methods are for back compatibility with conda-build. Do not remove + # without coordination with the conda-build team. + # + @property + def strictness(self): + # With the old MatchSpec, strictness==3 if name, version, and + # build were all specified. + s = sum(f in self._match_components for f in ("name", "version", "build")) + if s < len(self._match_components): + return 3 + elif not self.get_exact_value("name") or "build" in self._match_components: + return 3 + elif "version" in self._match_components: + return 2 + else: + return 1 + + @property + def spec(self): + return self.conda_build_form() + + @property + def version(self): + # in the old MatchSpec object, version was a VersionSpec, not a str + # so we'll keep that API here + return self._match_components.get("version") + + @property + def fn(self): + val = self.get_raw_value("fn") or self.get_raw_value("url") + if val: + val = basename(val) + if not val: + raise ValueError(".fn cannot be empty.") + return val + + @classmethod + def merge(cls, match_specs, union=False): + match_specs = sorted(tuple(cls(s) for s in match_specs if s), key=str) + name_groups = groupby(attrgetter("name"), match_specs) + unmergeable = name_groups.pop("*", []) + name_groups.pop(None, []) + + merged_specs = [] + mergeable_groups = tuple( + chain.from_iterable( + groupby(lambda s: s.optional, group).values() + for group in name_groups.values() + ) + ) + for group in mergeable_groups: + target_groups = groupby(attrgetter("target"), group) + target_groups.pop(None, None) + if len(target_groups) > 1: + raise ValueError(f"Incompatible MatchSpec merge:{dashlist(group)}") + merged_specs.append( + reduce(lambda x, y: x._merge(y, union), group) + if len(group) > 1 + else group[0] + ) + return (*merged_specs, *unmergeable) + + @classmethod + def union(cls, match_specs): + return cls.merge(match_specs, union=True) + + def _merge(self, other, union=False): + if self.optional != other.optional or self.target != other.target: + raise ValueError(f"Incompatible MatchSpec merge: - {self}\n - {other}") + + final_components = {} + component_names = set(self._match_components) | set(other._match_components) + for component_name in component_names: + this_component = self._match_components.get(component_name) + that_component = other._match_components.get(component_name) + if this_component is None and that_component is None: + continue + elif this_component is None: + final_components[component_name] = that_component + elif that_component is None: + final_components[component_name] = this_component + else: + if union: + try: + final = this_component.union(that_component) + except (AttributeError, ValueError, TypeError): + final = f"{this_component}|{that_component}" + else: + final = this_component.merge(that_component) + final_components[component_name] = final + return self.__class__( + optional=self.optional, target=self.target, **final_components + ) + + +def _parse_version_plus_build(v_plus_b): + """This should reliably pull the build string out of a version + build string combo. + Examples: + >>> _parse_version_plus_build("=1.2.3 0") + ('=1.2.3', '0') + >>> _parse_version_plus_build("1.2.3=0") + ('1.2.3', '0') + >>> _parse_version_plus_build(">=1.0 , < 2.0 py34_0") + ('>=1.0,<2.0', 'py34_0') + >>> _parse_version_plus_build(">=1.0 , < 2.0 =py34_0") + ('>=1.0,<2.0', 'py34_0') + >>> _parse_version_plus_build("=1.2.3 ") + ('=1.2.3', None) + >>> _parse_version_plus_build(">1.8,<2|==1.7") + ('>1.8,<2|==1.7', None) + >>> _parse_version_plus_build("* openblas_0") + ('*', 'openblas_0') + >>> _parse_version_plus_build("* *") + ('*', '*') + """ + parts = re.search( + r"((?:.+?)[^>~])(?:[ =])([^-=,|<>~]+?))?$", v_plus_b + ) + if parts: + version, build = parts.groups() + build = build and build.strip() + else: + version, build = v_plus_b, None + return version and version.replace(" ", ""), build + + +def _parse_legacy_dist(dist_str): + """ + Examples: + >>> _parse_legacy_dist("_license-1.1-py27_1.tar.bz2") + ('_license', '1.1', 'py27_1') + >>> _parse_legacy_dist("_license-1.1-py27_1") + ('_license', '1.1', 'py27_1') + """ + dist_str, _ = strip_pkg_extension(dist_str) + name, version, build = dist_str.rsplit("-", 2) + return name, version, build + + +def _parse_channel(channel_val): + if not channel_val: + return None, None + chn = Channel(channel_val) + channel_name = chn.name or chn.base_url + return channel_name, chn.subdir + + +_PARSE_CACHE = {} + + +def _sanitize_version_str(version: str, build: str | None) -> str: + """ + Sanitize version strings for MatchSpec parsing. + + Handles edge cases and translates version patterns for proper MatchSpec processing. + + Empty operators like "==" are passed through so existing error handling code can + treat them like other incomplete operators ("<=" or ">="). This is necessary because + downstream translation code would mangle "==" into an empty string, resulting in an + empty version field that breaks logic expecting missing versions to be represented + as operators like "==", "<=", and ">=". + + These missing version cases result from match specs like "numpy==", "numpy<=", + "numpy>=", "numpy= " (with trailing space), which should be treated as errors. + Note: "numpy=" (no trailing space) is treated as valid. + + For simple versions starting with "=", translates patterns like "=1.2.3" to "1.2.3*" + when appropriate conditions are met. + + Args: + version: The version string to sanitize + build: Optional build string that affects sanitization behavior + + Returns: + Sanitized version string + + Examples: + "==" or "=" -> passed through for error handling + "==1.2.3" -> "1.2.3" (when build is None) + "=1.2.3" -> "1.2.3*" (when build is None and no special chars) + ">=1.0" -> ">=1.0" (unchanged, doesn't start with "=") + """ + # Pass through empty operators for proper error handling downstream + if version in ("==", "="): + return version + + # We will only sanitize versions starting with "=" (e.g., "=1.2.3", "==1.2.3") + if not version.startswith("="): + return version + + version_without_equals = version.lstrip("=") + + # For exact matches like "==1.2.3", strip the "==" when no build specified + if version.startswith("==") and build is None: + return version_without_equals + + # For simple versions like "=1.2.3", add wildcard if conditions are met + if not any(char in version_without_equals for char in "=,|"): + if build is None and not version_without_equals.endswith("*"): + return version_without_equals + "*" + return version_without_equals + + return version + + +def _parse_spec_str(spec_str): + cached_result = _PARSE_CACHE.get(spec_str) + if cached_result: + return cached_result + + original_spec_str = spec_str + + # pre-step for ugly backward compat + if spec_str.endswith("@"): + feature_name = spec_str[:-1] + return { + "name": "*", + "track_features": (feature_name,), + } + + # Step 1. strip '#' comment + if "#" in spec_str: + ndx = spec_str.index("#") + spec_str, _ = spec_str[:ndx], spec_str[ndx:] + spec_str.strip() + + # Step 1.b strip ' if ' anticipating future compatibility issues + spec_split = spec_str.split(" if ", 1) + if len(spec_split) > 1: + log.debug("Ignoring conditional in spec %s", spec_str) + spec_str = spec_split[0] + + # Step 2. done if spec_str is a tarball + if context.plugin_manager.has_package_extension(spec_str): + # treat as a normal url + if not is_url(spec_str): + spec_str = unquote(path_to_url(expand(spec_str))) + + channel = Channel(spec_str) + if channel.subdir: + name, version, build = _parse_legacy_dist(channel.package_filename) + result = { + "channel": channel.canonical_name, + "subdir": channel.subdir, + "name": name, + "version": version, + "build": build, + "fn": channel.package_filename, + "url": spec_str, + } + else: + # url is not a channel + if spec_str.startswith("file://"): + # We must undo percent-encoding when generating fn. + path_or_url = url_to_path(spec_str) + else: + path_or_url = spec_str + + return { + "name": "*", + "fn": basename(path_or_url), + "url": spec_str, + } + return result + + # Step 3. strip off brackets portion + brackets = {} + m3 = re.match(r".*(?:(\[.*\]))", spec_str) + if m3: + brackets_str = m3.groups()[0] + spec_str = spec_str.replace(brackets_str, "") + brackets_str = brackets_str[1:-1] + m3b = re.finditer( + r'([a-zA-Z0-9_-]+?)=(["\']?)([^\'"]*?)(\2)(?:[, ]|$)', brackets_str + ) + for match in m3b: + key, _, value, _ = match.groups() + if not key or not value: + raise InvalidMatchSpec( + original_spec_str, "key-value mismatch in brackets" + ) + if key == "version" and value: + value = _sanitize_version_str(value, match.groupdict().get("build")) + brackets[key] = value + + # Step 4. strip off parens portion + m4 = re.match(r".*(?:(\(.*\)))", spec_str) + parens = {} + if m4: + parens_str = m4.groups()[0] + spec_str = spec_str.replace(parens_str, "") + parens_str = parens_str[1:-1] + m4b = re.finditer( + r'([a-zA-Z0-9_-]+?)=(["\']?)([^\'"]*?)(\2)(?:[, ]|$)', parens_str + ) + for match in m4b: + key, _, value, _ = match.groups() + parens[key] = value + if "optional" in parens_str: + parens["optional"] = True + + # Step 5. strip off '::' channel and namespace + m5 = spec_str.rsplit(":", 2) + m5_len = len(m5) + if m5_len == 3: + channel_str, namespace, spec_str = m5 + elif m5_len == 2: + namespace, spec_str = m5 + channel_str = None + elif m5_len: + spec_str = m5[0] + channel_str, namespace = None, None + else: + raise NotImplementedError() + channel, subdir = _parse_channel(channel_str) + if "channel" in brackets: + b_channel, b_subdir = _parse_channel(brackets.pop("channel")) + if b_channel: + channel = b_channel + if b_subdir: + subdir = b_subdir + if "subdir" in brackets: + subdir = brackets.pop("subdir") + + # Step 6. strip off package name from remaining version + build + m3 = re.match(r"([^ =<>!~]+)?([>= 2: + # name, version, build = _parse_legacy_dist(name) + if spec_str: + if "[" in spec_str: + raise InvalidMatchSpec( + original_spec_str, "multiple brackets sections not allowed" + ) + + version, build = _parse_version_plus_build(spec_str) + version = _sanitize_version_str(version, build) + else: + version, build = None, None + + # Step 8. now compile components together + components = {} + components["name"] = name or "*" + + if channel is not None: + components["channel"] = channel + if subdir is not None: + components["subdir"] = subdir + if namespace is not None: + # components['namespace'] = namespace + pass + if version is not None: + components["version"] = version + if build is not None: + components["build"] = build + + # anything in brackets will now strictly override key as set in other area of spec str + # EXCEPT FOR: name + # If we let name in brackets override a name outside of brackets it is possible to write + # MatchSpecs that appear to install one package but actually install a completely different one + # e.g. tensorflow[name=* version=* md5= ] will APPEAR to install + # tensorflow but actually install pytorch. + if "name" in components and "name" in brackets: + msg = ( + f"'name' specified both inside ({brackets['name']}) and outside " + f"({components['name']}) of brackets. The value outside of brackets " + f"({components['name']}) will be used." + ) + warnings.warn(msg, UserWarning) + del brackets["name"] + components.update(brackets) + components["_original_spec_str"] = original_spec_str + _PARSE_CACHE[original_spec_str] = components + return components + + +class MatchInterface(metaclass=ABCMeta): + def __init__(self, value): + self._raw_value = value + + @abstractmethod + def match(self, other): + raise NotImplementedError() + + def matches(self, value): + return self.match(value) + + @property + def raw_value(self): + return self._raw_value + + @abstractproperty + def exact_value(self): + """If the match value is an exact specification, returns the value. + Otherwise returns None. + """ + raise NotImplementedError() + + def merge(self, other): + if self.raw_value != other.raw_value: + raise ValueError( + f"Incompatible component merge:\n - {self.raw_value!r}\n - {other.raw_value!r}" + ) + return self.raw_value + + def union(self, other): + options = {self.raw_value, other.raw_value} + return "|".join(options) + + +class _StrMatchMixin: + def __str__(self): + return self._raw_value + + def __repr__(self): + return f"{self.__class__.__name__}('{self._raw_value}')" + + def __eq__(self, other): + return isinstance(other, self.__class__) and self._raw_value == other._raw_value + + def __hash__(self): + return hash(self._raw_value) + + @property + def exact_value(self): + return self._raw_value + + +class ExactStrMatch(_StrMatchMixin, MatchInterface): + __slots__ = ("_raw_value",) + + def __init__(self, value): + super().__init__(value) + + def match(self, other): + try: + _other_val = other._raw_value + except AttributeError: + _other_val = str(other) + return self._raw_value == _other_val + + +class ExactLowerStrMatch(ExactStrMatch): + def __init__(self, value): + super().__init__(value.lower()) + + def match(self, other): + try: + _other_val = other._raw_value + except AttributeError: + _other_val = str(other) + return self._raw_value == _other_val.lower() + + +class GlobStrMatch(_StrMatchMixin, MatchInterface): + __slots__ = "_raw_value", "_re_match" + + def __init__(self, value): + super().__init__(value) + self._re_match = None + + try: + if value.startswith("^") and value.endswith("$"): + self._re_match = re.compile(value).match + elif "*" in value: + value = re.escape(value).replace("\\*", r".*") + self._re_match = re.compile(rf"^(?:{value})$").match + except re.error as e: + raise InvalidMatchSpec( + value, f"Contains an invalid regular expression. '{e}'" + ) + + def match(self, other): + try: + _other_val = other._raw_value + except AttributeError: + _other_val = str(other) + + if self._re_match: + return self._re_match(_other_val) + else: + return self._raw_value == _other_val + + @property + def exact_value(self): + return self._raw_value if self._re_match is None else None + + @property + def matches_all(self): + return self._raw_value == "*" + + def merge(self, other): + # exact match + if self.raw_value == other.raw_value: + return self.raw_value + + if not self._re_match and isinstance(other, GlobStrMatch) and other._re_match: + # swap order, so `self` always has an actual pattern if there is only one + other, self = self, other + + # the other component might not have str 'raw_value' (e.g. Channel or MultiChannel) + other_as_str = str(other) + + if "*" not in other_as_str: + # other is an exact literal, + # check our pattern against it + # if we match, other is more strict + if self._re_match and self._re_match(other_as_str): + return other.raw_value + else: + # Raise on incompatible pattern + return super().merge(other) + + # Both are patterns! + # We distinguish four types of glob patterns + # - 'needle*' as "prefix glob" + # - '*needle*' as "infix glob" + # - '*needle' as "suffix glob" + # - '*ne*dle*' as "regex-required glob" + # The only combination of globs we can express with + # pure globs is prefix+prefix and suffix+suffix + # Every other combination requires computing their + # regular expression intersection + # Details in https://github.com/conda/conda/pull/11612#discussion_r954545863 + + # Check if we have suffix+suffix or prefix+prefix + # In these cases, we keep the longest one, since it's more restrictive + if (self.raw_value.count("*") == other_as_str.count("*") == 1) and ( + (self.raw_value[0] == other_as_str[0] == "*") # both prefixes + or (self.raw_value[-1] == other_as_str[-1] == "*") # suffixes + ): + self_stripped = self.raw_value.strip("*") + other_stripped = other_as_str.strip("*") + if self_stripped in other_stripped: + return other.raw_value + if other_stripped in self_stripped: + return self.raw_value + # They are not substrings! Guaranteed incompatibility; raise + return super().merge(other) + + # Generalized case: regular expression intersection + # We don't reject anything here! We just write the expression + # and will let the index filtering steps detect whether there's + # a package record that matches the expression + patterns = [] + for value in (self.raw_value, other_as_str): + if value.startswith("^") and value.endswith("$"): + patterns.append(value[1:-1]) + elif "*" in value: + value = re.escape(value).replace(r"\*", r".*") + patterns.append(value) + else: + patterns.append(value) + + # lookahead assertion followed by non-capture group + return rf"^(?={patterns[0]})(?:{patterns[1]})$" + + +class GlobLowerStrMatch(GlobStrMatch): + def __init__(self, value): + super().__init__(value.lower()) + + +class SplitStrMatch(MatchInterface): + __slots__ = ("_raw_value",) + + def __init__(self, value): + super().__init__(self._convert(value)) + + def _convert(self, value): + try: + return frozenset(value.replace(" ", ",").split(",")) + except AttributeError: + if isiterable(value): + return frozenset(value) + raise + + def match(self, other): + try: + return other and self._raw_value & other._raw_value + except AttributeError: + return self._raw_value & self._convert(other) + + def __repr__(self): + if self._raw_value: + return "{{{}}}".format(", ".join(f"'{s}'" for s in sorted(self._raw_value))) + else: + return "set()" + + def __str__(self): + # this space delimiting makes me nauseous + return " ".join(sorted(self._raw_value)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self._raw_value == other._raw_value + + def __hash__(self): + return hash(self._raw_value) + + @property + def exact_value(self): + return self._raw_value + + +class FeatureMatch(MatchInterface): + __slots__ = ("_raw_value",) + + def __init__(self, value): + super().__init__(self._convert(value)) + + def _convert(self, value): + if not value: + return frozenset() + elif isinstance(value, str): + return frozenset( + f + for f in (ff.strip() for ff in value.replace(" ", ",").split(",")) + if f + ) + else: + return frozenset(f for f in (ff.strip() for ff in value) if f) + + def match(self, other): + other = self._convert(other) + return self._raw_value == other + + def __repr__(self): + return "[{}]".format(", ".join(f"'{k}'" for k in sorted(self._raw_value))) + + def __str__(self): + return " ".join(sorted(self._raw_value)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self._raw_value == other._raw_value + + def __hash__(self): + return hash(self._raw_value) + + @property + def exact_value(self): + return self._raw_value + + +class ChannelMatch(GlobStrMatch): + def __init__(self, value): + self._re_match = None + + try: + if isinstance(value, str): + if value.startswith("^") and value.endswith("$"): + self._re_match = re.compile(value).match + elif "*" in value: + self._re_match = re.compile( + r"^(?:{})$".format(value.replace("*", r".*")) + ).match + else: + value = Channel(value) + except re.error as e: + raise InvalidMatchSpec( + value, f"Contains an invalid regular expression. '{e}'" + ) + + super(GlobStrMatch, self).__init__(value) + + def match(self, other): + try: + _other_val = Channel(other._raw_value) + except AttributeError: + _other_val = Channel(other) + + if self._re_match: + return self._re_match(_other_val.canonical_name) + else: + # assert ChannelMatch('pkgs/free').match('defaults') is False + # assert ChannelMatch('defaults').match('pkgs/free') is True + return self._raw_value.name in (_other_val.name, _other_val.canonical_name) + + def __str__(self): + try: + return f"{self._raw_value.name}" + except AttributeError: + return f"{self._raw_value}" + + def __repr__(self): + return f"'{self.__str__()}'" + + +class CaseInsensitiveStrMatch(GlobLowerStrMatch): + def match(self, other): + try: + _other_val = other._raw_value + except AttributeError: + _other_val = str(other) + + _other_val = _other_val.lower() + if self._re_match: + return self._re_match(_other_val) + else: + return self._raw_value == _other_val + + +_implementors = { + "channel": ChannelMatch, + "name": GlobLowerStrMatch, + "version": VersionSpec, + "build": GlobStrMatch, + "build_number": BuildNumberMatch, + "track_features": FeatureMatch, + "features": FeatureMatch, + "license": CaseInsensitiveStrMatch, + "license_family": CaseInsensitiveStrMatch, +} diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/package_info.py b/miniconda3/lib/python3.13/site-packages/conda/models/package_info.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff2faa23f4235f21d0a54a10a0870ce2ed9e93f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/package_info.py @@ -0,0 +1,80 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""(Legacy) Low-level implementation of a PackageRecord.""" + +from logging import getLogger + +from ..auxlib.entity import ( + ComposableField, + Entity, + EnumField, + ImmutableEntity, + IntegerField, + ListField, + StringField, +) +from .channel import Channel +from .enums import NoarchType +from .records import PackageRecord, PathsData + +log = getLogger(__name__) + + +class NoarchField(EnumField): + def box(self, instance, instance_type, val): + return super().box(instance, instance_type, NoarchType.coerce(val)) + + +class Noarch(Entity): + type = NoarchField(NoarchType) + entry_points = ListField( + str, required=False, nullable=True, default=None, default_in_dump=False + ) + + +class PreferredEnv(Entity): + name = StringField() + executable_paths = ListField(str, required=False, nullable=True) + softlink_paths = ListField(str, required=False, nullable=True) + + +class PackageMetadata(Entity): + # from info/package_metadata.json + package_metadata_version = IntegerField() + noarch = ComposableField(Noarch, required=False, nullable=True) + preferred_env = ComposableField( + PreferredEnv, required=False, nullable=True, default=None, default_in_dump=False + ) + + +class PackageInfo(ImmutableEntity): + # attributes external to the package tarball + extracted_package_dir = StringField() + package_tarball_full_path = StringField() + channel = ComposableField(Channel) + repodata_record = ComposableField(PackageRecord) + url = StringField() + + # attributes within the package tarball + icondata = StringField(required=False, nullable=True) + package_metadata = ComposableField(PackageMetadata, required=False, nullable=True) + paths_data = ComposableField(PathsData) + + def dist_str(self): + return f"{self.channel.canonical_name}::{self.name}-{self.version}-{self.build}" + + @property + def name(self): + return self.repodata_record.name + + @property + def version(self): + return self.repodata_record.version + + @property + def build(self): + return self.repodata_record.build + + @property + def build_number(self): + return self.repodata_record.build_number diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/prefix_graph.py b/miniconda3/lib/python3.13/site-packages/conda/models/prefix_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..27d8e263688ff4341c02d926650f1bd288be65c4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/prefix_graph.py @@ -0,0 +1,444 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Implements directed graphs to sort and manipulate packages within a prefix. + +Object inheritance: + +.. autoapi-inheritance-diagram:: PrefixGraph GeneralGraph + :top-classes: conda.models.prefix_graph.PrefixGraph + :parts: 1 +""" + +from collections import defaultdict +from logging import getLogger + +from boltons.setutils import IndexedSet + +from ..base.context import context +from ..common.compat import on_win +from ..exceptions import CyclicalDependencyError +from .enums import NoarchType +from .match_spec import MatchSpec + +log = getLogger(__name__) + + +class PrefixGraph: + """ + A directed graph structure used for sorting packages (prefix_records) in prefixes and + manipulating packages within prefixes (e.g. removing and pruning). + + The terminology used for edge direction is "parents" and "children" rather than "successors" + and "predecessors". The parent nodes of a record are those records in the graph that + match the record's "depends" field. E.g. NodeA depends on NodeB, then NodeA is a child + of NodeB, and NodeB is a parent of NodeA. Nodes can have zero parents, or more than two + parents. + + Most public methods mutate the graph. + """ + + def __init__(self, records, specs=()): + records = tuple(records) + specs = set(specs) + self.graph = graph = {} # dict[PrefixRecord, set[PrefixRecord]] + self.spec_matches = spec_matches = {} # dict[PrefixRecord, set[MatchSpec]] + for node in records: + parent_match_specs = tuple(MatchSpec(d) for d in node.depends) + parent_nodes = { + rec for rec in records if any(m.match(rec) for m in parent_match_specs) + } + graph[node] = parent_nodes + matching_specs = IndexedSet(s for s in specs if s.match(node)) + if matching_specs: + spec_matches[node] = matching_specs + + self._toposort() + + def remove_spec(self, spec): + """ + Remove all matching nodes, and any associated child nodes. + + Args: + spec (MatchSpec): + + Returns: + tuple[PrefixRecord]: The removed nodes. + + """ + node_matches = {node for node in self.graph if spec.match(node)} + + # If the spec was a track_features spec, then we need to also remove every + # package with a feature that matches the track_feature. + for feature_name in spec.get_raw_value("track_features") or (): + feature_spec = MatchSpec(features=feature_name) + node_matches.update(node for node in self.graph if feature_spec.match(node)) + + remove_these = set() + for node in node_matches: + remove_these.add(node) + remove_these.update(self.all_descendants(node)) + remove_these = tuple(filter(lambda node: node in remove_these, self.graph)) + for node in remove_these: + self._remove_node(node) + self._toposort() + return tuple(remove_these) + + def remove_youngest_descendant_nodes_with_specs(self): + """ + A specialized method used to determine only dependencies of requested specs. + + Returns: + tuple[PrefixRecord]: The removed nodes. + + """ + graph = self.graph + spec_matches = self.spec_matches + inverted_graph = { + node: {key for key in graph if node in graph[key]} for node in graph + } + youngest_nodes_with_specs = tuple( + node + for node, children in inverted_graph.items() + if not children and node in spec_matches + ) + removed_nodes = tuple( + filter(lambda node: node in youngest_nodes_with_specs, self.graph) + ) + for node in removed_nodes: + self._remove_node(node) + self._toposort() + return removed_nodes + + @property + def records(self): + return iter(self.graph) + + def prune(self): + """Prune back all packages until all child nodes are anchored by a spec. + + Returns: + tuple[PrefixRecord]: The pruned nodes. + + """ + graph = self.graph + spec_matches = self.spec_matches + original_order = tuple(self.graph) + + removed_nodes = set() + while True: + inverted_graph = { + node: {key for key in graph if node in graph[key]} for node in graph + } + prunable_nodes = tuple( + node + for node, children in inverted_graph.items() + if not children and node not in spec_matches + ) + if not prunable_nodes: + break + for node in prunable_nodes: + removed_nodes.add(node) + self._remove_node(node) + + removed_nodes = tuple( + filter(lambda node: node in removed_nodes, original_order) + ) + self._toposort() + return removed_nodes + + def get_node_by_name(self, name): + return next(rec for rec in self.graph if rec.name == name) + + def all_descendants(self, node): + graph = self.graph + inverted_graph = { + node: {key for key in graph if node in graph[key]} for node in graph + } + + nodes = [node] + nodes_seen = set() + q = 0 + while q < len(nodes): + for child_node in inverted_graph[nodes[q]]: + if child_node not in nodes_seen: + nodes_seen.add(child_node) + nodes.append(child_node) + q += 1 + return tuple(filter(lambda node: node in nodes_seen, graph)) + + def all_ancestors(self, node): + graph = self.graph + nodes = [node] + nodes_seen = set() + q = 0 + while q < len(nodes): + for parent_node in graph[nodes[q]]: + if parent_node not in nodes_seen: + nodes_seen.add(parent_node) + nodes.append(parent_node) + q += 1 + return tuple(filter(lambda node: node in nodes_seen, graph)) + + def _remove_node(self, node): + """Removes this node and all edges referencing it.""" + graph = self.graph + if node not in graph: + raise KeyError(f"node {node} does not exist") + graph.pop(node) + self.spec_matches.pop(node, None) + + for node, edges in graph.items(): + if node in edges: + edges.remove(node) + + def _toposort(self): + graph_copy = {node: IndexedSet(parents) for node, parents in self.graph.items()} + self._toposort_prepare_graph(graph_copy) + if context.allow_cycles: + sorted_nodes = tuple(self._topo_sort_handle_cycles(graph_copy)) + else: + sorted_nodes = tuple(self._toposort_raise_on_cycles(graph_copy)) + original_graph = self.graph + self.graph = {node: original_graph[node] for node in sorted_nodes} + return sorted_nodes + + @classmethod + def _toposort_raise_on_cycles(cls, graph): + if not graph: + return + + while True: + no_parent_nodes = IndexedSet( + sorted( + (node for node, parents in graph.items() if len(parents) == 0), + key=lambda x: x.name, + ) + ) + if not no_parent_nodes: + break + + for node in no_parent_nodes: + yield node + graph.pop(node, None) + + for parents in graph.values(): + parents -= no_parent_nodes + + if len(graph) != 0: + raise CyclicalDependencyError(tuple(graph)) + + @classmethod + def _topo_sort_handle_cycles(cls, graph): + # remove edges that point directly back to the node + for k, v in graph.items(): + v.discard(k) + + # disconnected nodes go first + nodes_that_are_parents = { + node for parents in graph.values() for node in parents + } + nodes_without_parents = (node for node in graph if not graph[node]) + disconnected_nodes = sorted( + ( + node + for node in nodes_without_parents + if node not in nodes_that_are_parents + ), + key=lambda x: x.name, + ) + yield from disconnected_nodes + + t = cls._toposort_raise_on_cycles(graph) + + while True: + try: + value = next(t) + yield value + except CyclicalDependencyError as e: + # TODO: Turn this into a warning, but without being too annoying with + # multiple messages. See https://github.com/conda/conda/issues/4067 + log.debug("%r", e) + + yield cls._toposort_pop_key(graph) + + t = cls._toposort_raise_on_cycles(graph) + continue + + except StopIteration: + return + + @staticmethod + def _toposort_pop_key(graph): + """ + Pop an item from the graph that has the fewest parents. + In the case of a tie, use the node with the alphabetically-first package name. + """ + node_with_fewest_parents = sorted( + (len(parents), node.dist_str(), node) for node, parents in graph.items() + )[0][2] + graph.pop(node_with_fewest_parents) + + for parents in graph.values(): + parents.discard(node_with_fewest_parents) + + return node_with_fewest_parents + + @staticmethod + def _toposort_prepare_graph(graph): + # There are currently at least three special cases to be aware of. + + # 1. Remove any circular dependency between python and pip. This typically comes about + # because of the add_pip_as_python_dependency configuration parameter. + for node in graph: + if node.name == "python": + parents = graph[node] + for parent in tuple(parents): + if parent.name == "pip": + parents.remove(parent) + + # 2. Special case code for menuinst. + # Always link/unlink menuinst first/last in case a subsequent + # package tries to import it to create/remove a shortcut. + menuinst_node = next((node for node in graph if node.name == "menuinst"), None) + python_node = next((node for node in graph if node.name == "python"), None) + if menuinst_node: + # add menuinst as a parent if python is a parent and the node + # isn't a parent of menuinst + if python_node is None: + raise RuntimeError("Found menuinst without Python in prefix graph.") + menuinst_parents = graph[menuinst_node] + for node, parents in graph.items(): + if python_node in parents and node not in menuinst_parents: + parents.add(menuinst_node) + + if on_win: + # 3. On windows, python noarch packages need an implicit dependency on conda added, if + # conda is in the list of packages for the environment. Python noarch packages + # that have entry points use conda's own conda.exe python entry point binary. If + # conda is going to be updated during an operation, the unlink / link order matters. + # See issue #6057. + conda_node = next((node for node in graph if node.name == "conda"), None) + if conda_node: + # add conda as a parent if python is a parent and node isn't a parent of conda + conda_parents = graph[conda_node] + for node, parents in graph.items(): + if ( + hasattr(node, "noarch") + and node.noarch == NoarchType.python + and node not in conda_parents + ): + parents.add(conda_node) + + +# def dot_repr(self, title=None): # pragma: no cover +# # graphviz DOT graph description language +# +# builder = ['digraph g {'] +# if title: +# builder.append(' labelloc="t";') +# builder.append(' label="%s";' % title) +# builder.append(' size="10.5,8";') +# builder.append(' rankdir=BT;') +# for node in self.get_nodes_ordered_from_roots(): +# label = "%s %s" % (node.record.name, node.record.version) +# if node.specs: +# # TODO: combine? +# spec = next(iter(node.specs)) +# label += "\\n%s" % ("?%s" if spec.optional else "%s") % spec +# if node.is_orphan: +# shape = "box" +# elif node.is_root: +# shape = "invhouse" +# elif node.is_leaf: +# shape = "house" +# else: +# shape = "ellipse" +# builder.append(' "%s" [label="%s", shape=%s];' % (node.record.name, label, shape)) +# for child in node.required_children: +# builder.append(' "%s" -> "%s";' % (child.record.name, node.record.name)) +# for child in node.optional_children: +# builder.append(' "%s -> "%s" [color=lightgray];' % (child.record.name, +# node.record.name)) +# builder.append('}') +# return '\n'.join(builder) +# +# def format_url(self): # pragma: no cover +# return "https://condaviz.glitch.me/%s" % url_quote(self.dot_repr()) +# +# def request_svg(self): # pragma: no cover +# from tempfile import NamedTemporaryFile +# import requests +# from ..common.compat import ensure_binary +# response = requests.post("https://condaviz.glitch.me/post", +# data={"digraph": self.dot_repr()}) +# response.raise_for_status() +# with NamedTemporaryFile(suffix='.svg', delete=False) as fh: +# fh.write(ensure_binary(response.text)) +# print("saved to: %s" % fh.name, file=sys.stderr) +# return fh.name +# +# def open_url(self): # pragma: no cover +# import webbrowser +# from ..common.url import path_to_url +# location = self.request_svg() +# try: +# browser = webbrowser.get("safari") +# except webbrowser.Error: +# browser = webbrowser.get() +# browser.open_new_tab(path_to_url(location)) + + +class GeneralGraph(PrefixGraph): + """ + Compared with PrefixGraph, this class takes in more than one record of a given name, + and operates on that graph from the higher view across any matching dependencies. It is + not a Prefix thing, but more like a "graph of all possible candidates" thing, and is used + for unsatisfiability analysis + """ + + def __init__(self, records, specs=()): + records = tuple(records) + super().__init__(records, specs) + self.specs_by_name = defaultdict(dict) + for node in records: + parent_dict = self.specs_by_name.get(node.name, {}) + for dep in tuple(MatchSpec(d) for d in node.depends): + deps = parent_dict.get(dep.name, set()) + deps.add(dep) + parent_dict[dep.name] = deps + self.specs_by_name[node.name] = parent_dict + + consolidated_graph = {} + # graph is toposorted, so looping over it is in dependency order + for node, parent_nodes in reversed(list(self.graph.items())): + cg = consolidated_graph.get(node.name, set()) + cg.update(_.name for _ in parent_nodes) + consolidated_graph[node.name] = cg + self.graph_by_name = consolidated_graph + + def breadth_first_search_by_name(self, root_spec, target_spec): + """Return shorted path from root_spec to spec_name""" + queue = [] + queue.append([root_spec]) + visited = [] + while queue: + path = queue.pop(0) + node = path[-1] + if node in visited: + continue + visited.append(node) + if node == target_spec: + return path + children = [] + specs = self.specs_by_name.get(node.name) + if specs is None: + continue + for _, deps in specs.items(): + children.extend(list(deps)) + for adj in children: + if adj.name == target_spec.name and adj.version != target_spec.version: + pass + else: + new_path = list(path) + new_path.append(adj) + queue.append(new_path) diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/records.py b/miniconda3/lib/python3.13/site-packages/conda/models/records.py new file mode 100644 index 0000000000000000000000000000000000000000..426e32dc44517dfe612ff183b11a0b00b7acf133 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/records.py @@ -0,0 +1,708 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Implements the data model for conda packages. + +A PackageRecord is the record of a package present in a channel. A PackageCache is the record of a +downloaded and cached package. A PrefixRecord is the record of a package installed into a conda +environment. + +Object inheritance: + +.. autoapi-inheritance-diagram:: PackageRecord PackageCacheRecord PrefixRecord + :top-classes: conda.models.records.PackageRecord + :parts: 1 +""" + +from __future__ import annotations + +from os.path import basename, join +from pathlib import Path + +from boltons.timeutils import dt_to_timestamp, isoparse + +from ..auxlib.entity import ( + BooleanField, + ComposableField, + DictSafeMixin, + Entity, + EnumField, + IntegerField, + ListField, + NumberField, + StringField, +) +from ..base.context import context +from ..common.compat import isiterable +from ..deprecations import deprecated +from ..exceptions import PathNotFoundError +from .channel import Channel +from .enums import FileMode, LinkType, NoarchType, PackageType, PathEnum, Platform +from .match_spec import MatchSpec + + +class LinkTypeField(EnumField): + def box(self, instance, instance_type, val): + if isinstance(val, str): + val = val.replace("-", "").replace("_", "").lower() + if val == "hard": + val = LinkType.hardlink + elif val == "soft": + val = LinkType.softlink + return super().box(instance, instance_type, val) + + +class NoarchField(EnumField): + def box(self, instance, instance_type, val): + return super().box(instance, instance_type, NoarchType.coerce(val)) + + +class TimestampField(NumberField): + def __init__(self): + super().__init__(default=0, required=False, default_in_dump=False) + + @staticmethod + def _make_seconds(val): + if val: + val = val + if val > 253402300799: # 9999-12-31 + val /= ( + 1000 # convert milliseconds to seconds; see conda/conda-build#1988 + ) + return val + + @staticmethod + def _make_milliseconds(val): + if val: + if val < 253402300799: # 9999-12-31 + val *= 1000 # convert seconds to milliseconds + val = val + return val + + def box(self, instance, instance_type, val): + return self._make_seconds(super().box(instance, instance_type, val)) + + def dump(self, instance, instance_type, val): + return int( + self._make_milliseconds(super().dump(instance, instance_type, val)) + ) # whether in seconds or milliseconds, type must be int (not float) for backward compat + + def __get__(self, instance, instance_type): + try: + return super().__get__(instance, instance_type) + except AttributeError: + try: + return int(dt_to_timestamp(isoparse(instance.date))) + except (AttributeError, ValueError): + return 0 + + +class Link(DictSafeMixin, Entity): + source = StringField() + type = LinkTypeField(LinkType, required=False) + + +EMPTY_LINK = Link(source="") + + +class _FeaturesField(ListField): + def __init__(self, **kwargs): + super().__init__(str, **kwargs) + + def box(self, instance, instance_type, val): + if isinstance(val, str): + val = val.replace(" ", ",").split(",") + val = tuple(f for f in (ff.strip() for ff in val) if f) + return super().box(instance, instance_type, val) + + def dump(self, instance, instance_type, val): + if isiterable(val): + return " ".join(val) + else: + return val or () # default value is (), and default_in_dump=False + + +class ChannelField(ComposableField): + def __init__(self, aliases=()): + super().__init__(Channel, required=False, aliases=aliases) + + def dump(self, instance, instance_type, val): + if val: + return str(val) + else: + val = instance.channel # call __get__ + return str(val) + + def __get__(self, instance, instance_type): + try: + return super().__get__(instance, instance_type) + except AttributeError: + url = instance.url + return self.unbox(instance, instance_type, Channel(url)) + + +class SubdirField(StringField): + def __init__(self): + super().__init__(required=False) + + def __get__(self, instance, instance_type): + try: + return super().__get__(instance, instance_type) + except AttributeError: + try: + url = instance.url + except AttributeError: + url = None + if url: + return self.unbox(instance, instance_type, Channel(url).subdir) + + try: + platform, arch = instance.platform.name, instance.arch + except AttributeError: + platform, arch = None, None + if platform and not arch: + return self.unbox(instance, instance_type, "noarch") + elif platform: + if "x86" in arch: + arch = "64" if "64" in arch else "32" + return self.unbox(instance, instance_type, f"{platform}-{arch}") + else: + return self.unbox(instance, instance_type, context.subdir) + + +class FilenameField(StringField): + def __init__(self, aliases=()): + super().__init__(required=False, aliases=aliases) + + def __get__(self, instance, instance_type): + try: + return super().__get__(instance, instance_type) + except AttributeError: + try: + url = instance.url + fn = Channel(url).package_filename + if not fn: + raise AttributeError() + except AttributeError: + fn = f"{instance.name}-{instance.version}-{instance.build}" + if not fn: + raise ValueError("Filename cannot be empty.") + return self.unbox(instance, instance_type, fn) + + +class PackageTypeField(EnumField): + def __init__(self): + super().__init__( + PackageType, + required=False, + nullable=True, + default=None, + default_in_dump=False, + ) + + def __get__(self, instance, instance_type): + val = super().__get__(instance, instance_type) + if val is None: + # look in noarch field + noarch_val = instance.noarch + if noarch_val: + type_map = { + NoarchType.generic: PackageType.NOARCH_GENERIC, + NoarchType.python: PackageType.NOARCH_PYTHON, + } + val = type_map[NoarchType.coerce(noarch_val)] + val = self.unbox(instance, instance_type, val) + return val + + +class PathData(Entity): + _path = StringField() + prefix_placeholder = StringField( + required=False, nullable=True, default=None, default_in_dump=False + ) + file_mode = EnumField(FileMode, required=False, nullable=True) + no_link = BooleanField( + required=False, nullable=True, default=None, default_in_dump=False + ) + path_type = EnumField(PathEnum) + + @property + def path(self): + # because I don't have aliases as an option for entity fields yet + return self._path + + +class PathDataV1(PathData): + # TODO: sha256 and size_in_bytes should be required for all PathEnum.hardlink, but not for softlink and directory + sha256 = StringField(required=False, nullable=True) + size_in_bytes = IntegerField(required=False, nullable=True) + inode_paths = ListField(str, required=False, nullable=True) + + sha256_in_prefix = StringField(required=False, nullable=True) + + +class PathsData(Entity): + # from info/paths.json + paths_version = IntegerField() + paths = ListField(PathDataV1) + + +class PackageRecord(DictSafeMixin, Entity): + """Representation of a concrete package archive (tarball or .conda file). + + It captures all the relevant information about a given package archive, including its source, + in the following attributes. + + Note that there are three subclasses, :class:`SolvedRecord`, :class:`PrefixRecord` and + :class:`PackageCacheRecord`. These capture the same information, but are augmented with + additional information relevant for these sources of packages. + + Further note that :class:`PackageRecord` makes use of its :attr:`_pkey` + for comparison and hash generation. + This means that for common operations, like comparisons between :class:`PackageRecord` s + and reference of :class:`PackageRecord` s in mappings, _different_ objects appear identical. + The fields taken into account are marked in the following list of attributes. + The subclasses do not add further attributes to the :attr:`_pkey`. + """ + + name = StringField() + """The name of the package. + + Part of the :attr:`_pkey`. + """ + + version = StringField() + """The version of the package. + + Part of the :attr:`_pkey`. + """ + + build = StringField(aliases=("build_string",)) + """The build string of the package. + + Part of the :attr:`_pkey`. + """ + + build_number = IntegerField() + """The build number of the package. + + Part of the :attr:`_pkey`. + """ + + # the canonical code abbreviation for PackageRef is `pref` + # fields required to uniquely identifying a package + + channel = ChannelField(aliases=("schannel",)) + """The channel where the package can be found.""" + + subdir = SubdirField() + """The subdir, i.e. ``noarch`` or a platform (``linux-64`` or similar). + + Part of the :attr:`_pkey`. + """ + + fn = FilenameField(aliases=("filename",)) + """The filename of the package. + + Only part of the :attr:`_pkey` if :ref:`separate_format_cache ` + is ``true`` (default: ``false``). + """ + + md5 = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + """The md5 checksum of the package.""" + + legacy_bz2_md5 = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + """If this is a ``.conda`` package and a corresponding ``.tar.bz2`` package exists, this may contain the md5 checksum of that package.""" + + legacy_bz2_size = IntegerField(required=False, nullable=True, default_in_dump=False) + """If this is a ``.conda`` package and a corresponding ``.tar.bz2`` package exists, this may contain the size of that package.""" + + url = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + """The download url of the package.""" + + sha256 = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + """The sha256 checksum of the package.""" + + @property + def channel_name(self) -> str | None: + """str: The canonical name of the channel of this package. + + Part of the :attr:`_pkey`. + """ + return getattr(self.channel, "canonical_name", None) + + @property + @deprecated("25.9", "26.3", addendum="Use .channel_name instead") + def schannel(self): + return self.channel_name + + @property + def _pkey(self): + """tuple: The components of the PackageRecord that are used for comparison and hashing. + + The :attr:`_pkey` is a tuple made up of the following fields of the :class:`PackageRecord`. + Two :class:`PackageRecord` s test equal if their respective :attr:`_pkey` s are equal. + The hash of the :class:`PackageRecord` (important for dictionary access) is the hash of the :attr:`_pkey`. + + The included fields are: + + * :attr:`channel_name` + * :attr:`subdir` + * :attr:`name` + * :attr:`version` + * :attr:`build_number` + * :attr:`build` + * :attr:`fn` only if :ref:`separate_format_cache ` is set to true (default: false) + """ + try: + return self.__pkey + except AttributeError: + __pkey = self.__pkey = [ + self.channel.canonical_name, + self.subdir, + self.name, + self.version, + self.build_number, + self.build, + ] + # NOTE: fn is included to distinguish between .conda and .tar.bz2 packages + if context.separate_format_cache: + __pkey.append(self.fn) + self.__pkey = tuple(__pkey) + return self.__pkey + + def __hash__(self): + try: + return self._hash + except AttributeError: + self._hash = hash(self._pkey) + return self._hash + + def __eq__(self, other): + return self._pkey == other._pkey + + def dist_str(self, canonical_name: bool = True) -> str: + return "{}{}::{}-{}-{}".format( + self.channel.canonical_name if canonical_name else self.channel.name, + ("/" + self.subdir) if self.subdir else "", + self.name, + self.version, + self.build, + ) + + def dist_fields_dump(self): + return { + "base_url": self.channel.base_url, + "build_number": self.build_number, + "build_string": self.build, + "channel": self.channel.name, + "dist_name": self.dist_str().split(":")[-1], + "name": self.name, + "platform": self.subdir, + "version": self.version, + } + + arch = StringField(required=False, nullable=True) # so legacy + platform = EnumField(Platform, required=False, nullable=True) # so legacy + + depends = ListField(str, default=()) + constrains = ListField(str, default=()) + + track_features = _FeaturesField(required=False, default=(), default_in_dump=False) + features = _FeaturesField(required=False, default=(), default_in_dump=False) + + noarch = NoarchField( + NoarchType, required=False, nullable=True, default=None, default_in_dump=False + ) # TODO: rename to package_type + preferred_env = StringField( + required=False, nullable=True, default=None, default_in_dump=False + ) + python_site_packages_path = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + license = StringField( + required=False, nullable=True, default=None, default_in_dump=False + ) + license_family = StringField( + required=False, nullable=True, default=None, default_in_dump=False + ) + package_type = PackageTypeField() + + @property + def is_unmanageable(self): + return self.package_type in PackageType.unmanageable_package_types() + + timestamp = TimestampField() + + @property + def combined_depends(self): + from .match_spec import MatchSpec + + result = {ms.name: ms for ms in MatchSpec.merge(self.depends)} + for spec in self.constrains or (): + ms = MatchSpec(spec) + result[ms.name] = MatchSpec(ms, optional=(ms.name not in result)) + return tuple(result.values()) + + # the canonical code abbreviation for PackageRecord is `prec`, not to be confused with + # PackageCacheRecord (`pcrec`) or PrefixRecord (`prefix_rec`) + # + # important for "choosing" a package (i.e. the solver), listing packages + # (like search), and for verifying downloads + # + # this is the highest level of the record inheritance model that MatchSpec is designed to + # work with + + date = StringField(required=False) + size = IntegerField(required=False) + + def __str__(self): + return f"{self.channel.canonical_name}/{self.subdir}::{self.name}=={self.version}={self.build}" + + def to_match_spec(self): + return MatchSpec( + channel=self.channel, + subdir=self.subdir, + name=self.name, + version=self.version, + build=self.build, + ) + + def to_simple_match_spec(self): + return MatchSpec( + name=self.name, + version=self.version, + ) + + @property + def namekey(self): + return "global:" + self.name + + @property + def spec(self): + """Return package spec: name=version=build""" + return f"{self.name}={self.version}={self.build}" + + @property + def spec_no_build(self): + """Return package spec without build: name=version""" + return f"{self.name}={self.version}" + + def record_id(self): + # WARNING: This is right now only used in link.py _change_report_str(). It is not + # the official record_id / uid until it gets namespace. Even then, we might + # make the format different. Probably something like + # channel_name/subdir:namespace:name-version-build_number-build_string + return f"{self.channel.name}/{self.subdir}::{self.name}-{self.version}-{self.build}" + + metadata: set[str] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.metadata = set() + + @classmethod + def feature(cls, feature_name) -> PackageRecord: + # necessary for the SAT solver to do the right thing with features + pkg_name = f"{feature_name}@" + return cls( + name=pkg_name, + version="0", + build="0", + channel="@", + subdir=context.subdir, + md5="12345678901234567890123456789012", + track_features=(feature_name,), + build_number=0, + fn=pkg_name, + ) + + @classmethod + def virtual_package( + cls, name: str, version: str | None = None, build_string: str | None = None + ) -> PackageRecord: + """ + Create a virtual package record. + + :param name: The name of the virtual package. + :param version: The version of the virtual package, defaults to "0". + :param build_string: The build string of the virtual package, defaults to "0". + :return: A PackageRecord representing the virtual package. + """ + return cls( + package_type=PackageType.VIRTUAL_SYSTEM, + name=name, + version=version or "0", + build_string=build_string or "0", + channel="@", + subdir=context.subdir, + md5="12345678901234567890123456789012", + build_number=0, + fn=name, + ) + + +class Md5Field(StringField): + def __init__(self): + super().__init__(required=False, nullable=True) + + def __get__(self, instance, instance_type): + try: + return super().__get__(instance, instance_type) + except AttributeError as e: + try: + return instance._calculate_md5sum() + except PathNotFoundError: + raise e + + +class PackageCacheRecord(PackageRecord): + """Representation of a package that has been downloaded or unpacked in the local package cache. + + Specialization of :class:`PackageRecord` that adds information for packages that exist in the + local package cache, either as the downloaded package file, or unpacked in its own package dir, + or both. + + Note that this class does not add new fields to the :attr:`PackageRecord._pkey` so that a pure + :class:`PackageRecord` object that has the same ``_pkey`` fields as a different + :class:`PackageCacheRecord` object (or, indeed, a :class:`PrefixRecord` object) will be considered + equal and will produce the same hash. + """ + + package_tarball_full_path = StringField() + """Full path to the local package file.""" + + extracted_package_dir = StringField() + """Full path to the local extracted package.""" + + md5 = Md5Field() + """The md5 checksum of the package. + + If the package file exists locally, this class can calculate a missing checksum on-the-fly. + """ + + @property + def is_fetched(self): + """bool: Whether the package file exists locally.""" + from ..gateways.disk.read import isfile + + return isfile(self.package_tarball_full_path) + + @property + def is_extracted(self): + """bool: Whether the package has been extracted locally.""" + from ..gateways.disk.read import isdir, isfile + + epd = self.extracted_package_dir + return isdir(epd) and isfile(join(epd, "info", "index.json")) + + @property + def tarball_basename(self): + """str: The basename of the local package file.""" + return basename(self.package_tarball_full_path) + + def _calculate_md5sum(self): + memoized_md5 = getattr(self, "_memoized_md5", None) + if memoized_md5: + return memoized_md5 + + from os.path import isfile + + if isfile(self.package_tarball_full_path): + from ..gateways.disk.read import compute_sum + + md5sum = compute_sum(self.package_tarball_full_path, "md5") + setattr(self, "_memoized_md5", md5sum) + return md5sum + + +class SolvedRecord(PackageRecord): + """Representation of a package that has been returned as part of a solver solution. + + This sits between :class:`PackageRecord` and :class:`PrefixRecord`, simply adding + ``requested_spec`` so it can be used in lockfiles without requiring the artifact on + disk. + """ + + requested_spec = StringField(required=False) + """The :class:`MatchSpec` that the user requested or ``None`` if the package it was installed as a dependency.""" + + +class PrefixRecord(SolvedRecord): + """Representation of a package that is installed in a local conda environmnet. + + Specialization of :class:`PackageRecord` that adds information for packages that are installed + in a local conda environment or prefix. + + Note that this class does not add new fields to the :attr:`PackageRecord._pkey` so that a pure + :class:`PackageRecord` object that has the same ``_pkey`` fields as a different + :class:`PrefixRecord` object (or, indeed, a :class:`PackageCacheRecord` object) will be considered + equal and will produce the same hash. + + Objects of this class are generally constructed from metadata in json files inside `$prefix/conda-meta`. + """ + + package_tarball_full_path = StringField(required=False) + """The path to the originating package file, usually in the local cache.""" + + extracted_package_dir = StringField(required=False) + """The path to the extracted package directory, usually in the local cache.""" + + files = ListField(str, default=(), required=False) + """The list of all files comprising the package as relative paths from the prefix root.""" + + paths_data = ComposableField( + PathsData, required=False, nullable=True, default_in_dump=False + ) + """List with additional information about the files, e.g. checksums and link type.""" + + link = ComposableField(Link, required=False) + """Information about how the package was linked into the prefix.""" + + # app = ComposableField(App, required=False) + + # There have been requests in the past to save remote server auth + # information with the package. Open to rethinking that though. + auth = StringField(required=False, nullable=True) + """Authentication information.""" + + def package_size(self, prefix_path: Path) -> int: + """ + Compute the installed size of this package within a prefix. + + This sums up the size_in_bytes of all non-softlink paths in paths_data, + and stats the files on disk if size_in_bytes is missing. + + :returns: Total size in bytes of all files installed by this package, or + 0 if paths_data is missing or empty. + """ + total_size = 0 + + if not self.paths_data.paths: + return total_size + + for path_data in self.paths_data.paths: + if path_data.path_type in (PathEnum.softlink, PathEnum.directory): + continue + if getattr(path_data, "size_in_bytes", None) is not None: + total_size += path_data.size_in_bytes + continue + + file_path = Path(prefix_path) / path_data._path + try: + total_size += file_path.stat().st_size + except OSError: + pass + + return total_size + + # @classmethod + # def load(cls, conda_meta_json_path): + # return cls() diff --git a/miniconda3/lib/python3.13/site-packages/conda/models/version.py b/miniconda3/lib/python3.13/site-packages/conda/models/version.py new file mode 100644 index 0000000000000000000000000000000000000000..e8feac91fefaf38927daa43f1b23ac9c2b16bd67 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/models/version.py @@ -0,0 +1,713 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Implements the version spec with parsing and comparison logic. + +Object inheritance: + +.. autoapi-inheritance-diagram:: BaseSpec VersionSpec BuildNumberMatch + :top-classes: conda.models.version.BaseSpec + :parts: 1 +""" + +from __future__ import annotations + +import operator as op +import re +from itertools import zip_longest +from logging import getLogger + +from ..exceptions import InvalidVersionSpec + +log = getLogger(__name__) + + +def normalized_version(version: str) -> VersionOrder: + """Parse a version string and return VersionOrder object.""" + return VersionOrder(version) + + +def ver_eval(vtest, spec): + return VersionSpec(spec).match(vtest) + + +version_check_re = re.compile(r"^[\*\.\+!_0-9a-z]+$") +version_split_re = re.compile("([0-9]+|[*]+|[^0-9*]+)") +version_cache = {} + + +class SingleStrArgCachingType(type): + def __call__(cls, arg): + if isinstance(arg, cls): + return arg + elif isinstance(arg, str): + try: + return cls._cache_[arg] + except KeyError: + val = cls._cache_[arg] = super().__call__(arg) + return val + else: + return super().__call__(arg) + + +class VersionOrder(metaclass=SingleStrArgCachingType): + """Implement an order relation between version strings. + + Version strings can contain the usual alphanumeric characters + (A-Za-z0-9), separated into components by dots and underscores. Empty + segments (i.e. two consecutive dots, a leading/trailing underscore) + are not permitted. An optional epoch number - an integer + followed by '!' - can proceed the actual version string + (this is useful to indicate a change in the versioning + scheme itself). Version comparison is case-insensitive. + + Conda supports six types of version strings: + * Release versions contain only integers, e.g. '1.0', '2.3.5'. + * Pre-release versions use additional letters such as 'a' or 'rc', + for example '1.0a1', '1.2.beta3', '2.3.5rc3'. + * Development versions are indicated by the string 'dev', + for example '1.0dev42', '2.3.5.dev12'. + * Post-release versions are indicated by the string 'post', + for example '1.0post1', '2.3.5.post2'. + * Tagged versions have a suffix that specifies a particular + property of interest, e.g. '1.1.parallel'. Tags can be added + to any of the preceding four types. As far as sorting is concerned, + tags are treated like strings in pre-release versions. + * An optional local version string separated by '+' can be appended + to the main (upstream) version string. It is only considered + in comparisons when the main versions are equal, but otherwise + handled in exactly the same manner. + + To obtain a predictable version ordering, it is crucial to keep the + version number scheme of a given package consistent over time. + Specifically, + * version strings should always have the same number of components + (except for an optional tag suffix or local version string), + * letters/strings indicating non-release versions should always + occur at the same position. + + Before comparison, version strings are parsed as follows: + * They are first split into epoch, version number, and local version + number at '!' and '+' respectively. If there is no '!', the epoch is + set to 0. If there is no '+', the local version is empty. + * The version part is then split into components at '.' and '_'. + * Each component is split again into runs of numerals and non-numerals + * Subcomponents containing only numerals are converted to integers. + * Strings are converted to lower case, with special treatment for 'dev' + and 'post'. + * When a component starts with a letter, the fillvalue 0 is inserted + to keep numbers and strings in phase, resulting in '1.1.a1' == 1.1.0a1'. + * The same is repeated for the local version part. + + Examples: + 1.2g.beta15.rc => [[0], [1], [2, 'g'], [0, 'beta', 15], [0, 'rc']] + 1!2.15.1_ALPHA => [[1], [2], [15], [1, '_alpha']] + + The resulting lists are compared lexicographically, where the following + rules are applied to each pair of corresponding subcomponents: + * integers are compared numerically + * strings are compared lexicographically, case-insensitive + * strings are smaller than integers, except + * 'dev' versions are smaller than all corresponding versions of other types + * 'post' versions are greater than all corresponding versions of other types + * if a subcomponent has no correspondent, the missing correspondent is + treated as integer 0 to ensure '1.1' == '1.1.0'. + + The resulting order is: + 0.4 + < 0.4.0 + < 0.4.1.rc + == 0.4.1.RC # case-insensitive comparison + < 0.4.1 + < 0.5a1 + < 0.5b3 + < 0.5C1 # case-insensitive comparison + < 0.5 + < 0.9.6 + < 0.960923 + < 1.0 + < 1.1dev1 # special case 'dev' + < 1.1_ # appended underscore is special case for openssl-like versions + < 1.1a1 + < 1.1.0dev1 # special case 'dev' + == 1.1.dev1 # 0 is inserted before string + < 1.1.a1 + < 1.1.0rc1 + < 1.1.0 + == 1.1 + < 1.1.0post1 # special case 'post' + == 1.1.post1 # 0 is inserted before string + < 1.1post1 # special case 'post' + < 1996.07.12 + < 1!0.4.1 # epoch increased + < 1!3.1.1.6 + < 2!0.4.1 # epoch increased again + + Some packages (most notably openssl) have incompatible version conventions. + In particular, openssl interprets letters as version counters rather than + pre-release identifiers. For openssl, the relation + + 1.0.1 < 1.0.1a => False # should be true for openssl + + holds, whereas conda packages use the opposite ordering. You can work-around + this problem by appending an underscore to plain version numbers: + + 1.0.1_ < 1.0.1a => True # ensure correct ordering for openssl + """ + + _cache_ = {} + + def __init__(self, vstr: str): + # version comparison is case-insensitive + version = vstr.strip().rstrip().lower() + # basic validity checks + if version == "": + raise InvalidVersionSpec(vstr, "empty version string") + invalid = not version_check_re.match(version) + if invalid and "-" in version and "_" not in version: + # Allow for dashes as long as there are no underscores + # as well, by converting the former to the latter. + version = version.replace("-", "_") + invalid = not version_check_re.match(version) + if invalid: + raise InvalidVersionSpec(vstr, "invalid character(s)") + + # when fillvalue == 0 => 1.1 == 1.1.0 + # when fillvalue == -1 => 1.1 < 1.1.0 + self.norm_version = version + self.fillvalue = 0 + + # find epoch + version = version.split("!") + if len(version) == 1: + # epoch not given => set it to '0' + epoch = ["0"] + elif len(version) == 2: + # epoch given, must be an integer + if not version[0].isdigit(): + raise InvalidVersionSpec(vstr, "epoch must be an integer") + epoch = [version[0]] + else: + raise InvalidVersionSpec(vstr, "duplicated epoch separator '!'") + + # find local version string + version = version[-1].split("+") + if len(version) == 1: + # no local version + self.local = [] + # Case 2: We have a local version component in version[1] + elif len(version) == 2: + # local version given + self.local = version[1].replace("_", ".").split(".") + else: + raise InvalidVersionSpec(vstr, "duplicated local version separator '+'") + + # Error Case: Version is empty because the version string started with +. + # e.g. "+", "1.2", "+a", "+1". + # This is an error because specifying only a local version is invalid. + # version[0] is empty because vstr.split("+") returns something like ['', '1.2'] + if version[0] == "": + raise InvalidVersionSpec( + vstr, "Missing version before local version separator '+'" + ) + + if version[0][-1] == "_": + # If the last character of version is "-" or "_", don't split that out + # individually. Implements the instructions for openssl-like versions + # > You can work-around this problem by appending a dash to plain version numbers + split_version = version[0][:-1].replace("_", ".").split(".") + split_version[-1] += "_" + else: + split_version = version[0].replace("_", ".").split(".") + self.version = epoch + split_version + + # split components into runs of numerals and non-numerals, + # convert numerals to int, handle special strings + for v in (self.version, self.local): + for k in range(len(v)): + c = version_split_re.findall(v[k]) + if not c: + raise InvalidVersionSpec(vstr, "empty version component") + for j in range(len(c)): + if c[j].isdigit(): + c[j] = int(c[j]) + elif c[j] == "post": + # ensure number < 'post' == infinity + c[j] = float("inf") + elif c[j] == "dev": + # ensure '*' < 'DEV' < '_' < 'a' < number + # by upper-casing (all other strings are lower case) + c[j] = "DEV" + if v[k][0].isdigit(): + v[k] = c + else: + # components shall start with a number to keep numbers and + # strings in phase => prepend fillvalue + v[k] = [self.fillvalue] + c + + def __str__(self) -> str: + return self.norm_version + + def __repr__(self) -> str: + return f'{self.__class__.__name__}("{self}")' + + def _eq(self, t1: list[str], t2: list[str]) -> bool: + for v1, v2 in zip_longest(t1, t2, fillvalue=[]): + for c1, c2 in zip_longest(v1, v2, fillvalue=self.fillvalue): + if c1 != c2: + return False + return True + + def __eq__(self, other: object) -> bool: + if not isinstance(other, VersionOrder): + return False + return self._eq(self.version, other.version) and self._eq( + self.local, other.local + ) + + def startswith(self, other: object) -> bool: + if not isinstance(other, VersionOrder): + return False + # Tests if the version lists match up to the last element in "other". + if other.local: + if not self._eq(self.version, other.version): + return False + t1 = self.local + t2 = other.local + else: + t1 = self.version + t2 = other.version + nt = len(t2) - 1 + if not self._eq(t1[:nt], t2[:nt]): + return False + v1 = [] if len(t1) <= nt else t1[nt] + v2 = t2[nt] + nt = len(v2) - 1 + if not self._eq([v1[:nt]], [v2[:nt]]): + return False + c1 = self.fillvalue if len(v1) <= nt else v1[nt] + c2 = v2[nt] + if isinstance(c2, str): + return isinstance(c1, str) and c1.startswith(c2) + return c1 == c2 + + def __ne__(self, other: object) -> bool: + return not (self == other) + + def __lt__(self, other: object) -> bool: + if not isinstance(other, VersionOrder): + return False + for t1, t2 in zip([self.version, self.local], [other.version, other.local]): + for v1, v2 in zip_longest(t1, t2, fillvalue=[]): + for c1, c2 in zip_longest(v1, v2, fillvalue=self.fillvalue): + if c1 == c2: + continue + elif isinstance(c1, str): + if not isinstance(c2, str): + # str < int + return True + elif isinstance(c2, str): + # not (int < str) + return False + # c1 and c2 have the same type + return c1 < c2 + # self == other + return False + + def __gt__(self, other: object) -> bool: + return other < self + + def __le__(self, other: object) -> bool: + return not (other < self) + + def __ge__(self, other: object) -> bool: + return not (self < other) + + +# each token slurps up leading whitespace, which we strip out. +VSPEC_TOKENS = ( + r"\s*\^[^$]*[$]|" # regexes + r"\s*[()|,]|" # parentheses, logical and, logical or + r"[^()|,]+" +) # everything else + + +def treeify(spec_str): + """ + Examples: + >>> treeify("1.2.3") + '1.2.3' + >>> treeify("1.2.3,>4.5.6") + (',', '1.2.3', '>4.5.6') + >>> treeify("1.2.3,4.5.6|<=7.8.9") + ('|', (',', '1.2.3', '4.5.6'), '<=7.8.9') + >>> treeify("(1.2.3|4.5.6),<=7.8.9") + (',', ('|', '1.2.3', '4.5.6'), '<=7.8.9') + >>> treeify("((1.5|((1.6|1.7), 1.8), 1.9 |2.0))|2.1") + ('|', '1.5', (',', ('|', '1.6', '1.7'), '1.8', '1.9'), '2.0', '2.1') + >>> treeify("1.5|(1.6|1.7),1.8,1.9|2.0|2.1") + ('|', '1.5', (',', ('|', '1.6', '1.7'), '1.8', '1.9'), '2.0', '2.1') + """ + # Converts a VersionSpec expression string into a tuple-based + # expression tree. + if not isinstance(spec_str, str): + raise TypeError("`spec_str` must be a string.") + tokens = re.findall(VSPEC_TOKENS, f"({spec_str})") + output = [] + stack = [] + + def apply_ops(cstop): + # cstop: operators with lower precedence + while stack and stack[-1] not in cstop: + if len(output) < 2: + raise InvalidVersionSpec(spec_str, "cannot join single expression") + c = stack.pop() + r = output.pop() + # Fuse expressions with the same operator; e.g., + # ('|', ('|', a, b), ('|', c, d))becomes + # ('|', a, b, c d) + # We're playing a bit of a trick here. Instead of checking + # if the left or right entries are tuples, we're counting + # on the fact that if we _do_ see a string instead, its + # first character cannot possibly be equal to the operator. + r = r[1:] if r[0] == c else (r,) + left = output.pop() + left = left[1:] if left[0] == c else (left,) + output.append((c,) + left + r) + + for item in tokens: + item = item.strip() + if item == "|": + apply_ops("(") + stack.append("|") + elif item == ",": + apply_ops("|(") + stack.append(",") + elif item == "(": + stack.append("(") + elif item == ")": + apply_ops("(") + if not stack or stack[-1] != "(": + raise InvalidVersionSpec(spec_str, "expression must start with '('") + stack.pop() + else: + output.append(item) + if stack: + raise InvalidVersionSpec( + spec_str, f"unable to convert to expression tree: {stack}" + ) + if not output: + raise InvalidVersionSpec(spec_str, "unable to determine version from spec") + return output[0] + + +def untreeify(spec, _inand=False, depth=0): + """ + Examples: + >>> untreeify('1.2.3') + '1.2.3' + >>> untreeify((',', '1.2.3', '>4.5.6')) + '1.2.3,>4.5.6' + >>> untreeify(('|', (',', '1.2.3', '4.5.6'), '<=7.8.9')) + '(1.2.3,4.5.6)|<=7.8.9' + >>> untreeify((',', ('|', '1.2.3', '4.5.6'), '<=7.8.9')) + '(1.2.3|4.5.6),<=7.8.9' + >>> untreeify(('|', '1.5', (',', ('|', '1.6', '1.7'), '1.8', '1.9'), '2.0', '2.1')) + '1.5|((1.6|1.7),1.8,1.9)|2.0|2.1' + """ + if isinstance(spec, tuple): + if spec[0] == "|": + res = "|".join(map(lambda x: untreeify(x, depth=depth + 1), spec[1:])) + if _inand or depth > 0: + res = f"({res})" + else: + res = ",".join( + map(lambda x: untreeify(x, _inand=True, depth=depth + 1), spec[1:]) + ) + if depth > 0: + res = f"({res})" + return res + return spec + + +def compatible_release_operator(x, y): + return op.__ge__(x, y) and x.startswith( + VersionOrder(".".join(str(y).split(".")[:-1])) + ) + + +# This RE matches the operators '==', '!=', '<=', '>=', '<', '>' +# followed by a version string. It rejects expressions like +# '<= 1.2' (space after operator), '<>1.2' (unknown operator), +# and '<=!1.2' (nonsensical operator). +version_relation_re = re.compile(r"^(=|==|!=|<=|>=|<|>|~=)(?![=<>!~])(\S+)$") +regex_split_re = re.compile(r".*[()|,^$]") +OPERATOR_MAP = { + "==": op.__eq__, + "!=": op.__ne__, + "<=": op.__le__, + ">=": op.__ge__, + "<": op.__lt__, + ">": op.__gt__, + "=": lambda x, y: x.startswith(y), + "!=startswith": lambda x, y: not x.startswith(y), + "~=": compatible_release_operator, +} +OPERATOR_START = frozenset(("=", "<", ">", "!", "~")) + + +class BaseSpec: + def __init__(self, spec_str, matcher, is_exact): + self.spec_str = spec_str + self._is_exact = is_exact + self.match = matcher + + @property + def spec(self): + return self.spec_str + + def is_exact(self): + return self._is_exact + + def __eq__(self, other): + try: + other_spec = other.spec + except AttributeError: + other_spec = self.__class__(other).spec + return self.spec == other_spec + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash(self.spec) + + def __str__(self): + return self.spec + + def __repr__(self): + return f"{self.__class__.__name__}('{self.spec}')" + + @property + def raw_value(self): + return self.spec + + @property + def exact_value(self): + return self.is_exact() and self.spec or None + + def merge(self, other): + raise NotImplementedError() + + def regex_match(self, spec_str): + return bool(self.regex.match(spec_str)) + + def operator_match(self, spec_str): + return self.operator_func(VersionOrder(str(spec_str)), self.matcher_vo) + + def any_match(self, spec_str): + return any(s.match(spec_str) for s in self.tup) + + def all_match(self, spec_str): + return all(s.match(spec_str) for s in self.tup) + + def exact_match(self, spec_str): + return self.spec == spec_str + + def always_true_match(self, spec_str): + return True + + +class VersionSpec(BaseSpec, metaclass=SingleStrArgCachingType): + _cache_ = {} + + def __init__(self, vspec): + vspec_str, matcher, is_exact = self.get_matcher(vspec) + super().__init__(vspec_str, matcher, is_exact) + + def get_matcher(self, vspec): + if isinstance(vspec, str) and regex_split_re.match(vspec): + vspec = treeify(vspec) + + if isinstance(vspec, tuple): + vspec_tree = vspec + _matcher = self.any_match if vspec_tree[0] == "|" else self.all_match + tup = tuple(VersionSpec(s) for s in vspec_tree[1:]) + vspec_str = untreeify((vspec_tree[0],) + tuple(t.spec for t in tup)) + self.tup = tup + matcher = _matcher + is_exact = False + return vspec_str, matcher, is_exact + + vspec_str = str(vspec).strip() + if vspec_str[0] == "^" or vspec_str[-1] == "$": + if vspec_str[0] != "^" or vspec_str[-1] != "$": + raise InvalidVersionSpec( + vspec_str, "regex specs must start with '^' and end with '$'" + ) + self.regex = re.compile(vspec_str) + matcher = self.regex_match + is_exact = False + elif vspec_str[0] in OPERATOR_START: + m = version_relation_re.match(vspec_str) + if m is None: + raise InvalidVersionSpec(vspec_str, "invalid operator") + operator_str, vo_str = m.groups() + if vo_str[-2:] == ".*": + if operator_str in ("=", ">="): + vo_str = vo_str[:-2] + elif operator_str == "!=": + vo_str = vo_str[:-2] + operator_str = "!=startswith" + elif operator_str == "~=": + raise InvalidVersionSpec(vspec_str, "invalid operator with '.*'") + else: + log.warning( + "Using .* with relational operator is superfluous and deprecated " + "and will be removed in a future version of conda. Your spec was " + f"{vo_str}, but conda is ignoring the .* and treating it as {vo_str[:-2]}" + ) + vo_str = vo_str[:-2] + try: + self.operator_func = OPERATOR_MAP[operator_str] + except KeyError: + raise InvalidVersionSpec(vspec_str, f"invalid operator: {operator_str}") + self.matcher_vo = VersionOrder(vo_str) + matcher = self.operator_match + is_exact = operator_str == "==" + elif vspec_str == "*": + matcher = self.always_true_match + is_exact = False + elif "*" in vspec_str.rstrip("*"): + rx = vspec_str.replace(".", r"\.").replace("+", r"\+").replace("*", r".*") + rx = rf"^(?:{rx})$" + + self.regex = re.compile(rx) + matcher = self.regex_match + is_exact = False + elif vspec_str[-1] == "*": + if vspec_str[-2:] != ".*": + vspec_str = vspec_str[:-1] + ".*" + + # if vspec_str[-1] in OPERATOR_START: + # m = version_relation_re.match(vspec_str) + # if m is None: + # raise InvalidVersionSpecError(vspec_str) + # operator_str, vo_str = m.groups() + # + # + # else: + # pass + + vo_str = vspec_str.rstrip("*").rstrip(".") + self.operator_func = VersionOrder.startswith + self.matcher_vo = VersionOrder(vo_str) + matcher = self.operator_match + is_exact = False + elif "@" not in vspec_str: + self.operator_func = OPERATOR_MAP["=="] + self.matcher_vo = VersionOrder(vspec_str) + matcher = self.operator_match + is_exact = True + else: + matcher = self.exact_match + is_exact = True + return vspec_str, matcher, is_exact + + def merge(self, other): + if not isinstance(other, self.__class__): + raise TypeError( + f"Can only combine objects of the same type. Received {type(other)}." + ) + if self.raw_value == other.raw_value: + return self + return self.__class__(",".join(sorted((self.raw_value, other.raw_value)))) + + def union(self, other): + if not isinstance(other, self.__class__): + raise TypeError( + f"Can only combine objects of the same type. Received {type(other)}." + ) + options = {self.raw_value, other.raw_value} + # important: we only return a string here because the parens get gobbled otherwise + # this info is for visual display only, not for feeding into actual matches + return "|".join(sorted(options)) + + +# TODO: someday switch out these class names for consistency +VersionMatch = VersionSpec + + +class BuildNumberMatch(BaseSpec, metaclass=SingleStrArgCachingType): + _cache_ = {} + + def __init__(self, vspec): + vspec_str, matcher, is_exact = self.get_matcher(vspec) + super().__init__(vspec_str, matcher, is_exact) + + def get_matcher(self, vspec): + try: + vspec = int(vspec) + except ValueError: + pass + else: + matcher = self.exact_match + is_exact = True + return vspec, matcher, is_exact + + vspec_str = str(vspec).strip() + if vspec_str == "*": + matcher = self.always_true_match + is_exact = False + elif vspec_str.startswith(("=", "<", ">", "!")): + m = version_relation_re.match(vspec_str) + if m is None: + raise InvalidVersionSpec(vspec_str, "invalid operator") + operator_str, vo_str = m.groups() + try: + self.operator_func = OPERATOR_MAP[operator_str] + except KeyError: + raise InvalidVersionSpec(vspec_str, f"invalid operator: {operator_str}") + self.matcher_vo = VersionOrder(vo_str) + matcher = self.operator_match + + is_exact = operator_str == "==" + elif vspec_str[0] == "^" or vspec_str[-1] == "$": + if vspec_str[0] != "^" or vspec_str[-1] != "$": + raise InvalidVersionSpec( + vspec_str, "regex specs must start with '^' and end with '$'" + ) + self.regex = re.compile(vspec_str) + + matcher = self.regex_match + is_exact = False + # if hasattr(spec, 'match'): + # self.spec = _spec + # self.match = spec.match + else: + matcher = self.exact_match + is_exact = True + return vspec_str, matcher, is_exact + + def merge(self, other): + if self.raw_value != other.raw_value: + raise ValueError( + f"Incompatible component merge:\n - {self.raw_value!r}\n - {other.raw_value!r}" + ) + return self.raw_value + + def union(self, other): + options = {self.raw_value, other.raw_value} + return "|".join(options) + + @property + def exact_value(self) -> int | None: + try: + return int(self.raw_value) + except ValueError: + return None + + def __str__(self): + return str(self.spec) + + def __repr__(self): + return str(self.spec) diff --git a/miniconda3/lib/python3.13/site-packages/conda/notices/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/notices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c1517621a9bb248d79269264697839e0af1a88 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/notices/__init__.py @@ -0,0 +1,3 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from .core import notices # noqa: F401 diff --git a/miniconda3/lib/python3.13/site-packages/conda/notices/cache.py b/miniconda3/lib/python3.13/site-packages/conda/notices/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..76f5eb1ff1f9e1eac44fc9f8837824c85b25723b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/notices/cache.py @@ -0,0 +1,178 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Handles all caching logic including: + - Retrieving from cache + - Saving to cache + - Determining whether not certain items have expired and need to be refreshed +""" + +from __future__ import annotations + +import logging +import os +from datetime import datetime, timezone +from functools import wraps +from pathlib import Path +from typing import TYPE_CHECKING + +from platformdirs import user_cache_dir + +from ..base.constants import ( + APP_NAME, + NOTICES_CACHE_FN, + NOTICES_CACHE_SUBDIR, + NOTICES_DECORATOR_DISPLAY_INTERVAL, +) +from ..common.serialize import json +from ..utils import ensure_dir_exists +from .types import ChannelNoticeResponse + +if TYPE_CHECKING: + from collections.abc import Sequence + + from .types import ChannelNotice + +logger = logging.getLogger(__name__) + + +def cached_response(func): + @wraps(func) + def wrapper(url: str, name: str): + cache_dir = get_notices_cache_dir() + cache_val = get_notice_response_from_cache(url, name, cache_dir) + + if cache_val: + return cache_val + + return_value = func(url, name) + if return_value is not None: + write_notice_response_to_cache(return_value, cache_dir) + + return return_value + + return wrapper + + +def is_notice_response_cache_expired( + channel_notice_response: ChannelNoticeResponse, +) -> bool: + """ + This checks the contents of the cache response to see if it is expired. + + If for whatever reason we encounter an exception while parsing the individual + messages, we assume an invalid cache and return true. + """ + now = datetime.now(timezone.utc) + + def is_channel_notice_expired(expired_at: datetime | None) -> bool: + """If there is no "expired_at" field present assume it is expired.""" + if expired_at is None: + return True + return expired_at < now + + return any( + is_channel_notice_expired(chn.expired_at) + for chn in channel_notice_response.notices + ) + + +@ensure_dir_exists +def get_notices_cache_dir() -> Path: + """Returns the location of the notices cache directory as a Path object""" + cache_dir = user_cache_dir(APP_NAME, appauthor=APP_NAME) + + return Path(cache_dir).joinpath(NOTICES_CACHE_SUBDIR) + + +def get_notices_cache_file() -> Path: + """ + Return path of notices cache + + If the file does not exist, we create it with natural filesystem timestamps, + then set only the modification time to be in the past. This ensures notices + are checked and displayed immediately rather than waiting for the full + display interval. + """ + cache_dir = get_notices_cache_dir() + cache_file = cache_dir.joinpath(NOTICES_CACHE_FN) + + if not cache_file.is_file(): + with open(cache_file, "w") as fp: + fp.write("") + + # Keep natural access time, set only mtime to past for immediate notice display + stat = cache_file.stat() + past_mtime = stat.st_mtime - NOTICES_DECORATOR_DISPLAY_INTERVAL + os.utime(cache_file, (stat.st_atime, past_mtime)) + + return cache_file + + +def get_notice_response_from_cache( + url: str, name: str, cache_dir: Path +) -> ChannelNoticeResponse | None: + """Retrieves a notice response object from cache if it exists.""" + cache_key = ChannelNoticeResponse.get_cache_key(url, cache_dir) + + if os.path.isfile(cache_key): + with open(cache_key) as fp: + data = json.load(fp) + chn_ntc_resp = ChannelNoticeResponse(url, name, data) + + if not is_notice_response_cache_expired(chn_ntc_resp): + return chn_ntc_resp + + +def write_notice_response_to_cache( + channel_notice_response: ChannelNoticeResponse, cache_dir: Path +) -> None: + """Writes our notice data to our local cache location.""" + cache_key = ChannelNoticeResponse.get_cache_key( + channel_notice_response.url, cache_dir + ) + + with open(cache_key, "w") as fp: + json.dump(channel_notice_response.json_data, fp) + + +def mark_channel_notices_as_viewed( + cache_file: Path, channel_notices: Sequence[ChannelNotice] +) -> None: + """Insert channel notice into our database marking it as read.""" + notice_ids = {chn.id for chn in channel_notices} + + with open(cache_file) as fp: + contents: str = fp.read() + + contents_unique = set(filter(None, set(contents.splitlines()))) + contents_new = contents_unique.union(notice_ids) + + # Save new version of cache file + with open(cache_file, "w") as fp: + fp.write("\n".join(contents_new)) + + +def get_viewed_channel_notice_ids( + cache_file: Path, channel_notices: Sequence[ChannelNotice] +) -> set[str]: + """Return the ids of the channel notices which have already been seen.""" + notice_ids = {chn.id for chn in channel_notices} + + with open(cache_file) as fp: + contents: str = fp.read() + + contents_unique = set(filter(None, set(contents.splitlines()))) + + return notice_ids.intersection(contents_unique) + + +def clear_cache() -> None: + """ + Removes all files in notices cache + """ + cache_dir = Path(get_notices_cache_dir()) + + for cache_file in cache_dir.iterdir(): + if cache_file.is_file(): + cache_file.unlink() diff --git a/miniconda3/lib/python3.13/site-packages/conda/notices/core.py b/miniconda3/lib/python3.13/site-packages/conda/notices/core.py new file mode 100644 index 0000000000000000000000000000000000000000..913675fd2f9393ccd9430f094112264d8c893bfa --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/notices/core.py @@ -0,0 +1,224 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Core conda notices logic.""" + +from __future__ import annotations + +import logging +import time +from functools import wraps +from typing import TYPE_CHECKING + +from ..base.constants import NOTICES_DECORATOR_DISPLAY_INTERVAL, NOTICES_FN +from ..base.context import context +from ..models.channel import get_channel_objs +from . import cache, fetch, views +from .types import ChannelNoticeResultSet + +if TYPE_CHECKING: + from collections.abc import Sequence + + from ..base.context import Context + from ..models.channel import Channel, MultiChannel + from .types import ChannelNotice, ChannelNoticeResponse + +# Used below in type hints +ChannelName = str +ChannelUrl = str + +logger = logging.getLogger(__name__) + + +def retrieve_notices( + limit: int | None = None, + always_show_viewed: bool = True, + silent: bool = False, +) -> ChannelNoticeResultSet: + """ + Function used for retrieving notices. This is called by the "notices" decorator as well + as the sub-command "notices" + + Args: + limit: Limit the number of notices to show (defaults to None). + always_show_viewed: Whether all notices should be shown, not only the unread ones + (defaults to True). + silent: Whether to use a spinner when fetching and caching notices. + """ + channel_name_urls = get_channel_name_and_urls(get_channel_objs(context)) + channel_notice_responses = fetch.get_notice_responses( + channel_name_urls, silent=silent + ) + channel_notices = flatten_notice_responses(channel_notice_responses) + total_number_channel_notices = len(channel_notices) + + cache_file = cache.get_notices_cache_file() + + # We always want to modify the mtime attribute of the file if we are trying to retrieve notices + # This is used later in "is_channel_notices_cache_expired" + cache_file.touch() + + viewed_notices = None + viewed_channel_notices = 0 + if not always_show_viewed: + viewed_notices = cache.get_viewed_channel_notice_ids( + cache_file, channel_notices + ) + viewed_channel_notices = len(viewed_notices) + + channel_notices = filter_notices( + channel_notices, limit=limit, exclude=viewed_notices + ) + + return ChannelNoticeResultSet( + channel_notices=channel_notices, + viewed_channel_notices=viewed_channel_notices, + total_number_channel_notices=total_number_channel_notices, + ) + + +def display_notices(channel_notice_set: ChannelNoticeResultSet) -> None: + """Prints the channel notices to std out.""" + views.print_notices(channel_notice_set.channel_notices) + + # Updates cache database, marking displayed notices as "viewed" + cache_file = cache.get_notices_cache_file() + cache.mark_channel_notices_as_viewed(cache_file, channel_notice_set.channel_notices) + + views.print_more_notices_message( + channel_notice_set.total_number_channel_notices, + len(channel_notice_set.channel_notices), + channel_notice_set.viewed_channel_notices, + ) + + +def notices(func): + """ + Wrapper for "execute" entry points for subcommands. + + If channel notices need to be fetched, we do that first and then + run the command normally. We then display these notices at the very + end of the command output so that the user is more likely to see them. + + This ordering was specifically done to address the following bug report: + - https://github.com/conda/conda/issues/11847 + + Args: + func: Function to be decorated + """ + + @wraps(func) + def wrapper(*args, **kwargs): + if is_channel_notices_enabled(context): + channel_notice_set = None + + try: + if is_channel_notices_cache_expired(): + channel_notice_set = retrieve_notices( + limit=context.number_channel_notices, + always_show_viewed=False, + silent=True, + ) + except OSError as exc: + # If we encounter any OSError related error, we simply abandon + # fetching notices + logger.error(f"Unable to open cache file: {str(exc)}") + + if channel_notice_set is not None: + try: + return_value = func(*args, **kwargs) + display_notices(channel_notice_set) + + return return_value + + except Exception: + try: + # Remove the notices cache file if we encounter an exception + cache.clear_cache() + except OSError: + pass + raise + + return func(*args, **kwargs) + + return wrapper + + +def get_channel_name_and_urls( + channels: Sequence[Channel | MultiChannel], +) -> list[tuple[ChannelUrl, ChannelName]]: + """ + Return a sequence of Channel URL and name tuples. + + This function handles both Channel and MultiChannel object types. + """ + channel_name_and_urls = [] + + for channel in channels: + name = channel.name or channel.location + + for url in channel.base_urls: + full_url = url.rstrip("/") + channel_name_and_urls.append((f"{full_url}/{NOTICES_FN}", name)) + + return channel_name_and_urls + + +def flatten_notice_responses( + channel_notice_responses: Sequence[ChannelNoticeResponse], +) -> Sequence[ChannelNotice]: + return tuple( + notice + for channel in channel_notice_responses + if channel.notices + for notice in channel.notices + ) + + +def filter_notices( + channel_notices: Sequence[ChannelNotice], + limit: int | None = None, + exclude: set[str] | None = None, +) -> Sequence[ChannelNotice]: + """Perform filtering actions for the provided sequence of ChannelNotice objects.""" + if exclude: + channel_notices = tuple( + channel_notice + for channel_notice in channel_notices + if channel_notice.id not in exclude + ) + + if limit is not None: + channel_notices = channel_notices[:limit] + + return channel_notices + + +def is_channel_notices_enabled(ctx: Context) -> bool: + """ + Determines whether channel notices are enabled and therefore displayed when + invoking the `notices` command decorator. + + This only happens when: + - offline is False + - number_channel_notices is greater than 0 + + Args: + ctx: The conda context object + """ + return ctx.number_channel_notices > 0 and not ctx.offline and not ctx.json + + +def is_channel_notices_cache_expired() -> bool: + """ + Checks to see if the notices cache file we use to keep track of + displayed notices is expired. This involves checking the mtime + attribute of the file. Anything older than what is specified as + the NOTICES_DECORATOR_DISPLAY_INTERVAL is considered expired. + """ + cache_file = cache.get_notices_cache_file() + + cache_file_stat = cache_file.stat() + now = time.time() + seconds_since_checked = now - cache_file_stat.st_mtime + + return seconds_since_checked >= NOTICES_DECORATOR_DISPLAY_INTERVAL diff --git a/miniconda3/lib/python3.13/site-packages/conda/notices/fetch.py b/miniconda3/lib/python3.13/site-packages/conda/notices/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1421e4d3db1671df2827b856fb717d97bc1b35 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/notices/fetch.py @@ -0,0 +1,82 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Notices network fetch logic.""" + +from __future__ import annotations + +import logging +from concurrent.futures import ThreadPoolExecutor +from typing import TYPE_CHECKING + +import requests + +from ..gateways.connection.session import get_session +from ..reporters import get_spinner +from .cache import cached_response +from .types import ChannelNoticeResponse + +if TYPE_CHECKING: + from collections.abc import Sequence + +logger = logging.getLogger(__name__) + + +def get_notice_responses( + url_and_names: Sequence[tuple[str, str]], + silent: bool = False, + max_workers: int = 10, +) -> Sequence[ChannelNoticeResponse]: + """ + Provided a list of channel notification url/name tuples, return a sequence of + ChannelNoticeResponse objects. + + Args: + url_and_names: channel url and the channel name + silent: turn off "loading animation" (defaults to False) + max_workers: increase worker number in thread executor (defaults to 10) + Returns: + Sequence[ChannelNoticeResponse] + """ + executor = ThreadPoolExecutor(max_workers=max_workers) + + with get_spinner("Retrieving notices"): + return tuple( + filter( + None, + ( + chn_info + for chn_info in executor.map( + lambda args: get_channel_notice_response(*args), url_and_names + ) + ), + ) + ) + + +@cached_response +def get_channel_notice_response(url: str, name: str) -> ChannelNoticeResponse | None: + """ + Return a channel response object. We use this to wrap the response with + additional channel information to use. If the response was invalid we suppress/log + and error message. + """ + session = get_session(url) + try: + resp = session.get( + url, allow_redirects=False, timeout=5 + ) # timeout: connect, read + except requests.exceptions.Timeout: + logger.info(f"Request timed out for channel: {name} url: {url}") + return + except requests.exceptions.RequestException as exc: + logger.error(f"Request error <{exc}> for channel: {name} url: {url}") + return + + try: + if resp.status_code < 300: + return ChannelNoticeResponse(url, name, json_data=resp.json()) + else: + logger.info(f"Received {resp.status_code} when trying to GET {url}") + except ValueError: + logger.info(f"Unable to parse JSON data for {url}") + return ChannelNoticeResponse(url, name, json_data=None) diff --git a/miniconda3/lib/python3.13/site-packages/conda/notices/types.py b/miniconda3/lib/python3.13/site-packages/conda/notices/types.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e41ee0b177df750aee965c2580c21acb1590b4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/notices/types.py @@ -0,0 +1,115 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Implements all conda.notices types.""" + +from __future__ import annotations + +import hashlib +from datetime import datetime +from typing import TYPE_CHECKING, NamedTuple + +from ..base.constants import NoticeLevel + +if TYPE_CHECKING: + from collections.abc import Sequence + from pathlib import Path + +UNDEFINED_MESSAGE_ID = "undefined" +"""Value to use for message ID when it is not provided.""" + + +class ChannelNotice(NamedTuple): + """Represents an individual channel notice.""" + + id: str + channel_name: str | None + message: str | None + level: NoticeLevel + created_at: datetime | None + expired_at: datetime | None + interval: int | None + + def to_dict(self): + return { + "id": self.id, + "channel_name": self.channel_name, + "message": self.message, + "level": self.level.name.lower(), + "created_at": self.created_at.isoformat(), + "expired_at": self.expired_at.isoformat(), + "interval": self.interval, + } + + +class ChannelNoticeResultSet(NamedTuple): + """ + Represents a list of a channel notices, plus some accompanying + metadata such as `viewed_channel_notices`. + """ + + channel_notices: Sequence[ChannelNotice] + """Channel notices that are included in this particular set.""" + + total_number_channel_notices: int + """Total number of channel notices; not just the ones that will be displayed.""" + + viewed_channel_notices: int + """The number of channel notices that have already been viewed.""" + + +class ChannelNoticeResponse(NamedTuple): + url: str + name: str + json_data: dict | None + + @property + def notices(self) -> Sequence[ChannelNotice]: + if self.json_data: + notices = self.json_data.get("notices", ()) + + return tuple( + ChannelNotice( + id=str(notice.get("id", UNDEFINED_MESSAGE_ID)), + channel_name=self.name, + message=notice.get("message"), + level=self._parse_notice_level(notice.get("level")), + created_at=self._parse_iso_timestamp(notice.get("created_at")), + expired_at=self._parse_iso_timestamp(notice.get("expired_at")), + interval=notice.get("interval"), + ) + for notice in notices + ) + + # Default value + return () + + @staticmethod + def _parse_notice_level(level: str | None) -> NoticeLevel: + """ + We use this to validate notice levels and provide reasonable defaults + if any are invalid. + """ + try: + return NoticeLevel(level) + except ValueError: + # If we get an invalid value, rather than fail, we simply use a reasonable default + return NoticeLevel(NoticeLevel.INFO) + + @staticmethod + def _parse_iso_timestamp(iso_timestamp: str | None) -> datetime | None: + """Parse ISO timestamp and fail over to a default value of none.""" + if iso_timestamp is None: + return None + try: + return datetime.fromisoformat(iso_timestamp) + except ValueError: + return None + + @classmethod + def get_cache_key(cls, url: str, cache_dir: Path) -> Path: + """Returns where this channel response will be cached by hashing the URL.""" + bytes_filename = url.encode() + sha256_hash = hashlib.sha256(bytes_filename) + cache_filename = f"{sha256_hash.hexdigest()}.json" + + return cache_dir.joinpath(cache_filename) diff --git a/miniconda3/lib/python3.13/site-packages/conda/notices/views.py b/miniconda3/lib/python3.13/site-packages/conda/notices/views.py new file mode 100644 index 0000000000000000000000000000000000000000..e67d1a5c3a297345aa0d12664695154989ba6a66 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/notices/views.py @@ -0,0 +1,61 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Handles all display/view logic.""" + +from collections.abc import Sequence + +from ..base.context import context +from ..common.serialize import json +from .types import ChannelNotice + + +def print_notices(channel_notices: Sequence[ChannelNotice]): + """ + Accepts a list of channel notice responses and prints a display. + + Args: + channel_notices: A sequence of ChannelNotice objects. + """ + current_channel = None + + if context.json: + json_output = json.dumps( + [channel_notice.to_dict() for channel_notice in channel_notices] + ) + print(json_output) + + else: + for channel_notice in channel_notices: + if current_channel != channel_notice.channel_name: + print() + channel_header = "Channel" + channel_header += ( + f' "{channel_notice.channel_name}" has the following notices:' + ) + print(channel_header) + current_channel = channel_notice.channel_name + print_notice_message(channel_notice) + print() + + +def print_notice_message(notice: ChannelNotice, indent: str = " ") -> None: + """Prints a single channel notice.""" + timestamp = f"{notice.created_at:%c}" if notice.created_at else "" + + level = f"[{notice.level}] -- {timestamp}" + + print(f"{indent}{level}\n{indent}{notice.message}") + + +def print_more_notices_message( + total_notices: int, displayed_notices: int, viewed_notices: int +) -> None: + """Conditionally shows a message informing users how many more message there are.""" + notices_not_shown = total_notices - viewed_notices - displayed_notices + + if notices_not_shown > 0: + if notices_not_shown > 1: + msg = f"There are {notices_not_shown} more messages. To retrieve them run:\n\n" + else: + msg = f"There is {notices_not_shown} more message. To retrieve it run:\n\n" + print(f"{msg}conda notices\n") diff --git a/miniconda3/lib/python3.13/site-packages/conda/plan.py b/miniconda3/lib/python3.13/site-packages/conda/plan.py new file mode 100644 index 0000000000000000000000000000000000000000..ce02d3e6e01468409ad30760cbf602a91057548c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plan.py @@ -0,0 +1,250 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Handle the planning of installs and their execution. + +NOTE: + conda.install uses canonical package names in its interface functions, + whereas conda.resolve uses package filenames, as those are used as index + keys. We try to keep fixes to this "impedance mismatch" local to this + module. +""" + +import sys +from collections import defaultdict +from logging import getLogger + +from boltons.setutils import IndexedSet + +from .base.constants import DEFAULTS_CHANNEL_NAME, UNKNOWN_CHANNEL +from .base.context import context, reset_context +from .common.constants import TRACE +from .common.io import dashlist, env_vars, time_recorder +from .common.iterators import groupby_to_dict as groupby +from .core.index import LAST_CHANNEL_URLS +from .core.link import PrefixSetup, UnlinkLinkTransaction +from .deprecations import deprecated +from .instructions import FETCH, LINK, SYMLINK_CONDA, UNLINK +from .models.channel import Channel, prioritize_channels +from .models.dist import Dist +from .models.enums import LinkType +from .models.match_spec import MatchSpec +from .models.records import PackageRecord +from .models.version import normalized_version +from .utils import human_bytes + +deprecated.module("25.9", "26.3") + +deprecated.constant( + "25.9", + "26.3", + "log", + getLogger(__name__), + addendum="Use builtin `logging` instead.", +) +deprecated.constant("25.9", "26.3", "sys", sys, addendum="Use builtin `sys` instead.") +del sys +deprecated.constant( + "25.9", + "26.3", + "defaultdict", + defaultdict, + addendum="Use builtin `collections.defaultdict` instead.", +) +del defaultdict +deprecated.constant( + "25.9", + "26.3", + "IndexedSet", + IndexedSet, + addendum="Use `boltons.setutils.IndexedSet` instead.", +) +del IndexedSet +deprecated.constant( + "25.9", + "26.3", + "DEFAULTS_CHANNEL_NAME", + DEFAULTS_CHANNEL_NAME, + addendum="Use `conda.base.constants.DEFAULTS_CHANNEL_NAME` instead.", +) +del DEFAULTS_CHANNEL_NAME +deprecated.constant( + "25.9", + "26.3", + "UNKNOWN_CHANNEL", + UNKNOWN_CHANNEL, + addendum="Use `conda.base.constants.UNKNOWN_CHANNEL` instead.", +) +del UNKNOWN_CHANNEL +deprecated.constant( + "25.9", + "26.3", + "context", + context, + addendum="Use `conda.base.context.context` instead.", +) +del context +deprecated.constant( + "25.9", + "26.3", + "reset_context", + reset_context, + addendum="Use `conda.base.context.reset_context` instead.", +) +del reset_context +deprecated.constant( + "25.9", + "26.3", + "TRACE", + TRACE, + addendum="Use `conda.common.constants.TRACE` instead.", +) +del TRACE +deprecated.constant( + "25.9", + "26.3", + "dashlist", + dashlist, + addendum="Use `conda.common.io.dashlist` instead.", +) +del dashlist +deprecated.constant( + "25.9", + "26.3", + "env_vars", + env_vars, + addendum="Use `conda.common.io.env_vars` instead.", +) +del env_vars +deprecated.constant( + "25.9", + "26.3", + "time_recorder", + time_recorder, + addendum="Use `conda.common.io.time_recorder` instead.", +) +del time_recorder +deprecated.constant( + "25.9", + "26.3", + "groupby", + groupby, + addendum="Use `conda.common.iterators.groupby_to_dict` instead.", +) +del groupby +deprecated.constant( + "25.9", + "26.3", + "LAST_CHANNEL_URLS", + LAST_CHANNEL_URLS, + addendum="Use `conda.core.index.LAST_CHANNEL_URLS` instead.", +) +del LAST_CHANNEL_URLS +deprecated.constant( + "25.9", + "26.3", + "PrefixSetup", + PrefixSetup, + addendum="Use `conda.core.link.PrefixSetup` instead.", +) +del PrefixSetup +deprecated.constant( + "25.9", + "26.3", + "UnlinkLinkTransaction", + UnlinkLinkTransaction, + addendum="Use `conda.core.link.UnlinkLinkTransaction` instead.", +) +del UnlinkLinkTransaction +deprecated.constant( + "25.9", + "26.3", + "FETCH", + FETCH, + addendum="Use `conda.instructions.FETCH` instead.", +) +del FETCH +deprecated.constant( + "25.9", "26.3", "LINK", LINK, addendum="Use `conda.instructions.LINK` instead." +) +del LINK +deprecated.constant( + "25.9", + "26.3", + "SYMLINK_CONDA", + SYMLINK_CONDA, + addendum="Use `conda.instructions.SYMLINK_CONDA` instead.", +) +del SYMLINK_CONDA +deprecated.constant( + "25.9", + "26.3", + "UNLINK", + UNLINK, + addendum="Use `conda.instructions.UNLINK` instead.", +) +del UNLINK +deprecated.constant( + "25.9", + "26.3", + "Channel", + Channel, + addendum="Use `conda.models.channel.Channel` instead.", +) +del Channel +deprecated.constant( + "25.9", + "26.3", + "prioritize_channels", + prioritize_channels, + addendum="Use `conda.models.channel.prioritize_channels` instead.", +) +del prioritize_channels +deprecated.constant( + "25.9", + "26.3", + "Dist", + Dist, + addendum="Use `conda.models.dist.Dist` instead.", +) +del Dist +deprecated.constant( + "25.9", + "26.3", + "LinkType", + LinkType, + addendum="Use `conda.models.enums.LinkType` instead.", +) +del LinkType +deprecated.constant( + "25.9", + "26.3", + "MatchSpec", + MatchSpec, + addendum="Use `conda.models.match_spec.MatchSpec` instead.", +) +del MatchSpec +deprecated.constant( + "25.9", + "26.3", + "PackageRecord", + PackageRecord, + addendum="Use `conda.models.records.PackageRecord` instead.", +) +del PackageRecord +deprecated.constant( + "25.9", + "26.3", + "normalized_version", + normalized_version, + addendum="Use `conda.models.version.normalized_version` instead.", +) +del normalized_version +deprecated.constant( + "25.9", + "26.3", + "human_bytes", + human_bytes, + addendum="Use `conda.utils.human_bytes` instead.", +) +del human_bytes diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2008c2ce6a40cac11d5a50ad9c483b334e2f45fc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/__init__.py @@ -0,0 +1,144 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +In this module, you will find everything relevant to conda's plugin system. +It contains all of the code that plugin authors will use to write plugins, +as well as conda's internal implementations of plugins. + +**Modules relevant for plugin authors** + +- :mod:`conda.plugins.hookspec`: all available hook specifications are listed here, including + examples of how to use them +- :mod:`conda.plugins.types`: important types to use when defining plugin hooks + +**Modules relevant for internal development** + +- :mod:`conda.plugins.manager`: includes our custom subclass of pluggy's + `PluginManager `_ class + +**Modules with internal plugin implementations** + +- :mod:`conda.plugins.solvers`: implementation of the "classic" solver +- :mod:`conda.plugins.subcommands.doctor`: ``conda doctor`` and ``conda check`` subcommands (with ``--fix`` support) +- :mod:`conda.plugins.virtual_packages`: registers virtual packages in conda + +""" + +from ..deprecations import deprecated +from . import types +from .hookspec import hookimpl + +__all__ = ["hookimpl", "types"] + +deprecated.constant( + "26.3", + "26.9", + "CondaAuthHandler", + types.CondaAuthHandler, + addendum="Use `conda.plugins.types.CondaAuthHandler` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaEnvironmentSpecifier", + types.CondaEnvironmentSpecifier, + addendum="Use `conda.plugins.types.CondaEnvironmentSpecifier` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaHealthCheck", + types.CondaHealthCheck, + addendum="Use `conda.plugins.types.CondaHealthCheck` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaPostCommand", + types.CondaPostCommand, + addendum="Use `conda.plugins.types.CondaPostCommand` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaPostSolve", + types.CondaPostSolve, + addendum="Use `conda.plugins.types.CondaPostSolve` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaPostTransactionAction", + types.CondaPostTransactionAction, + addendum="Use `conda.plugins.types.CondaPostTransactionAction` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaPreCommand", + types.CondaPreCommand, + addendum="Use `conda.plugins.types.CondaPreCommand` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaPrefixDataLoader", + types.CondaPrefixDataLoader, + addendum="Use `conda.plugins.types.CondaPrefixDataLoader` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaPreSolve", + types.CondaPreSolve, + addendum="Use `conda.plugins.types.CondaPreSolve` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaPreTransactionAction", + types.CondaPreTransactionAction, + addendum="Use `conda.plugins.types.CondaPreTransactionAction` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaReporterBackend", + types.CondaReporterBackend, + addendum="Use `conda.plugins.types.CondaReporterBackend` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaRequestHeader", + types.CondaRequestHeader, + addendum="Use `conda.plugins.types.CondaRequestHeader` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaSetting", + types.CondaSetting, + addendum="Use `conda.plugins.types.CondaSetting` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaSolver", + types.CondaSolver, + addendum="Use `conda.plugins.types.CondaSolver` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaSubcommand", + types.CondaSubcommand, + addendum="Use `conda.plugins.types.CondaSubcommand` instead.", +) +deprecated.constant( + "26.3", + "26.9", + "CondaVirtualPackage", + types.CondaVirtualPackage, + addendum="Use `conda.plugins.types.CondaVirtualPackage` instead.", +) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/config.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/config.py new file mode 100644 index 0000000000000000000000000000000000000000..24c99235da1a575aea45ad1cc0b82eae79c55e15 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/config.py @@ -0,0 +1,130 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Handles plugin configuration functionality including: + - Managing plugin-specific settings + - Processing configuration data from various sources + - Dynamically adding and removing plugin settings + - Providing a standardized interface for plugins to access their configurations +""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Mapping +from typing import TYPE_CHECKING + +from ..common.configuration import ( + Configuration, + EnvRawParameter, + ParameterLoader, +) + +if TYPE_CHECKING: + from pathlib import Path + from typing import Any + + from ..common.configuration import Parameter, RawParameter + + +class PluginConfig(Configuration): + """ + Class used to hold settings for conda plugins. + + The object created by this class should only be accessed via + :class:`conda.base.context.Context.plugins`. + + When this class is updated via the :func:`add_plugin_setting` function it adds new setting + properties which can be accessed later via the context object. + + We currently call that function in + :meth:`conda.plugins.manager.CondaPluginManager.load_settings`. + because ``CondaPluginManager`` has access to all registered plugin settings via the settings + plugin hook. + """ + + parameter_names: tuple[str, ...] = () + parameter_names_and_aliases: tuple[str, ...] = () + + @classmethod + def add_plugin_setting( + cls, name: str, parameter: Parameter, aliases: tuple[str, ...] = () + ): + """ + Adds a setting to the :class:`PluginConfig` class + """ + cls.parameter_names = (*cls.parameter_names, name) + loader = ParameterLoader(parameter, aliases=aliases) + name = loader._set_name(name) + setattr(cls, name, loader) + + # Rebuild parameter_names_and_aliases to include the new parameter + cls._set_parameter_names_and_aliases() + + @classmethod + def remove_all_plugin_settings(cls) -> None: + """ + Removes all attached settings from the :class:`PluginConfig` class + """ + for name in cls.parameter_names: + try: + delattr(cls, name) + except AttributeError: + continue + + cls.parameter_names = tuple() + + def __init__(self, data): + self._cache_ = {} + self._data = data + + @property + def raw_data(self) -> dict[Path, dict[str, RawParameter]]: + """ + This is used to move everything under the key "plugins" from the provided dictionary + to the top level of the returned dictionary. The returned dictionary is then passed + to :class:`PluginConfig`. + """ + new_data = defaultdict(dict) + + for source, config in self._data.items(): + if plugin_data := config.get("plugins"): + plugin_data_value = plugin_data.value(None) + + if not isinstance(plugin_data_value, Mapping): + continue + + for param_name, raw_param in plugin_data_value.items(): + new_data[source][param_name] = raw_param + + elif source == EnvRawParameter.source: + for env_var, raw_param in config.items(): + if env_var.startswith("plugins_"): + _, param_name = env_var.split("plugins_") + new_data[source][param_name] = raw_param + + return new_data + + @property + def category_map(self) -> dict[str, tuple[str, ...]]: + return {"Additional settings provided by plugins": self.parameter_names} + + def get_descriptions(self) -> dict[str, str]: + from ..base.context import context + + return { + name: setting.description + for name, setting in context.plugin_manager.get_settings().items() + } + + def describe_parameter(self, parameter_name) -> dict[str, Any]: + """ + Returns the description of a parameter. + + We add to this method in order to change the "name" key that is returned to prepend "plugins." + to it. + """ + description = super().describe_parameter(parameter_name) + description["name"] = f"plugins.{description['name']}" + + return description diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..650cb6a186da5cb3d0ba2b82e30dd633bc5e9606 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/__init__.py @@ -0,0 +1,8 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Built-in conda environment exporter plugins.""" + +from . import environment_yml, explicit, requirements_txt + +plugins = [environment_yml, explicit, requirements_txt] +"""The list of environment exporter plugins for easier registration with pluggy.""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/environment_yml.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/environment_yml.py new file mode 100644 index 0000000000000000000000000000000000000000..64701f1bb3ed4a6a6c65a765967c1f51faf4c11f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/environment_yml.py @@ -0,0 +1,112 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Built-in conda standard environment exporter plugins (YAML and JSON).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal + +from ...common.serialize import json, yaml +from ...exceptions import CondaValueError +from ..hookspec import hookimpl +from ..types import CondaEnvironmentExporter + +if TYPE_CHECKING: + from typing import Any, Final + + from ...models.environment import Environment + +ENVIRONMENT_JSON_FORMAT: Final = "environment-json" +"""The name of the environment-json format.""" + +ENVIRONMENT_YAML_FORMAT: Final = "environment-yaml" +"""The name of the environment-yaml format.""" + +EnvironmentFormatType = Literal["environment-json", "environment-yaml"] +"""Type alias for format validation.""" + + +def to_dict(env: Environment) -> dict[str, Any]: + """ + Convert Environment to standard dictionary format used by YAML and JSON exporters. + + This represents the common dictionary structure that both YAML and JSON + environment formats use. + + :param env: Environment model to convert + :return: Dictionary with standard environment fields + """ + env_dict = {"name": env.name} + + # Add channels if present + if env.config and env.config.channels: + env_dict["channels"] = list(env.config.channels) + + # Convert requested_packages to dependencies list + if env.requested_packages: + dependencies = [] + for item in env.requested_packages: + if isinstance(item, dict): + # Handle pip dependencies (dict format: {"pip": [...]}) + dependencies.append(item) + else: + # Handle conda packages (MatchSpec objects) + # Use the conda_env_form() method for proper conda env export format + dependencies.append(item.conda_env_form()) + + # Add external packages (e.g. Python packages) if present + if env.external_packages: + dependencies.append(env.external_packages) + + env_dict["dependencies"] = dependencies + elif env.explicit_packages: + # Fall back to explicit packages if no requested packages + env_dict["dependencies"] = [ + explicit_package.spec for explicit_package in env.explicit_packages + ] + + # Add variables if present + if env.variables: + env_dict["variables"] = env.variables + + # Add prefix if present (though this is less common in standard formats) + if env.prefix: + env_dict["prefix"] = env.prefix + + return env_dict + + +def export_yaml(env: Environment) -> str: + """Export Environment to YAML format.""" + env_dict = to_dict(env) + try: + return yaml.dumps(env_dict) + except yaml.YAMLError as e: + raise CondaValueError(f"Failed to export environment to YAML: {e}") + + +def export_json(env: Environment) -> str: + """Export Environment to JSON format.""" + env_dict = to_dict(env) + try: + return json.dumps(env_dict, indent=2, ensure_ascii=False) + except (TypeError, ValueError, RecursionError) as e: + raise CondaValueError(f"Failed to export environment to JSON: {e}") + + +@hookimpl(tryfirst=True) # Ensure built-in YAML exporter loads first and has priority +def conda_environment_exporters(): + """Register the built-in YAML and JSON environment exporters.""" + yield CondaEnvironmentExporter( + name=ENVIRONMENT_YAML_FORMAT, + aliases=("yaml", "yml"), + default_filenames=("environment.yaml", "environment.yml"), + export=export_yaml, + ) + + yield CondaEnvironmentExporter( + name=ENVIRONMENT_JSON_FORMAT, + aliases=("json",), + default_filenames=("environment.json",), + export=export_json, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/explicit.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/explicit.py new file mode 100644 index 0000000000000000000000000000000000000000..66af61a9cfa452fd1a406cde53703e0cef993a60 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/explicit.py @@ -0,0 +1,94 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Built-in conda explicit environment exporter plugin. + +This module implements the explicit format defined in CEP 23: +Files with @EXPLICIT marker and package URLs for reproducible installs. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ... import __version__ +from ...common.url import join_url +from ...exceptions import CondaValueError +from ..hookspec import hookimpl +from ..types import CondaEnvironmentExporter + +if TYPE_CHECKING: + from typing import Final + + from ...models.environment import Environment + + +EXPLICIT_FORMAT: Final = "explicit" +"""The name of the explicit format.""" + + +def export_explicit(env: Environment) -> str: + """Export Environment to explicit format with @EXPLICIT and URLs (CEP 23 compliant).""" + lines = ["# This file may be used to create an environment using:"] + lines.append("# $ conda create --name --file ") + lines.append(f"# platform: {env.platform}") + lines.append(f"# created-by: conda {__version__}") + + # Only create true explicit files if we have explicit packages with URLs + if not env.explicit_packages: + raise CondaValueError( + "Cannot export explicit format: no explicit packages with installation metadata found. " + "Use 'requirements' format for environments with only requested packages, " + "or ensure the environment has been solved and installed." + ) + # Error if external packages (pip) are present - explicit format can't represent them + elif env.external_packages: + raise CondaValueError( + "Cannot export explicit format: environment contains external packages that cannot be represented in explicit format. " + "Use a different format to include external packages." + ) + # Error if requested packages exist but aren't fully represented in explicit packages + elif env.requested_packages: + explicit_names = {pkg.name for pkg in env.explicit_packages} + requested_names = {pkg.name for pkg in env.requested_packages} + missing_explicit = requested_names - explicit_names + if missing_explicit: + raise CondaValueError( + f"Cannot export explicit format: some requested packages lack installation metadata: " + f"{', '.join(sorted(missing_explicit))}. " + "Use 'requirements' format or ensure all packages are properly installed." + ) + + # Create CEP 23 compliant explicit file with @EXPLICIT and URLs + lines.append("@EXPLICIT") + + for pkg in env.explicit_packages: + # Use existing URL or construct from channel metadata + url = getattr(pkg, "url", None) + if ( + not url + and (channel := getattr(pkg, "channel", None)) + and (base_url := getattr(channel, "base_url", None)) + and (subdir := getattr(pkg, "subdir", None)) + and (fn := getattr(pkg, "fn", None)) + ): + url = join_url(base_url, subdir, fn) + + if url: + lines.append(url) + else: + raise CondaValueError( + f"Cannot export '{pkg.name}': explicit format requires package URLs" + ) + + return "\n".join(lines) + + +@hookimpl +def conda_environment_exporters(): + """Environment exporter plugin for explicit format.""" + yield CondaEnvironmentExporter( + name=EXPLICIT_FORMAT, + aliases=(), + export=export_explicit, + default_filenames=("explicit.txt",), + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/requirements_txt.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/requirements_txt.py new file mode 100644 index 0000000000000000000000000000000000000000..998d0dbdb12eb99fff08dd6b218b37a24211de7e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_exporters/requirements_txt.py @@ -0,0 +1,63 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Built-in conda requirements environment exporter plugin. + +This module implements the requirements format defined in CEP 23: +Files with MatchSpec strings (no @EXPLICIT marker) for flexible package specifications. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ... import __version__ +from ...exceptions import CondaValueError +from ..hookspec import hookimpl +from ..types import CondaEnvironmentExporter + +if TYPE_CHECKING: + from typing import Final + + from ...models.environment import Environment + + +REQUIREMENTS_FORMAT: Final = "requirements" +"""The name of the requirements format.""" + + +def export_requirements(env: Environment) -> str: + """Export Environment to requirements format with MatchSpecs (CEP 23 compliant).""" + lines = ["# This file may be used to create an environment using:"] + lines.append("# $ conda create --name --file ") + lines.append(f"# platform: {env.platform}") + lines.append(f"# created-by: conda {__version__}") + + # Only create requirements files if we have requested packages + if not env.requested_packages: + raise CondaValueError( + "Cannot export requirements format: no requested packages found. " + "Use 'explicit' format for environments with installed packages, " + "or ensure the environment has package specifications." + ) + + # Create CEP 23 compliant non-explicit requirements file (no @EXPLICIT) + lines.append("# Note: This is a conda requirements file (MatchSpec format)") + lines.append("# Contains conda package specifications, not pip requirements") + lines.append("") + + for spec in env.requested_packages: + # Use MatchSpec string representation (CEP 23 compliant) + lines.append(str(spec)) + + return "\n".join(lines) + + +@hookimpl +def conda_environment_exporters(): + """Environment exporter plugin for requirements format.""" + yield CondaEnvironmentExporter( + name=REQUIREMENTS_FORMAT, + aliases=("reqs", "txt"), + export=export_requirements, + default_filenames=("requirements.txt", "spec.txt"), + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10c4da86e18feb441143c0d3c24e92121dcaa38c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__init__.py @@ -0,0 +1,8 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Register the built-in environment specifier hook implementations.""" + +from . import cep_24, environment_yml, explicit, requirements_txt + +plugins = [cep_24, requirements_txt, environment_yml, explicit] +"""The list of environment specifier plugins for easier registration with pluggy.""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/cep_24.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/cep_24.py new file mode 100644 index 0000000000000000000000000000000000000000..78a347e8b41ba2c3a11f4971ac8c20a6a458235b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/cep_24.py @@ -0,0 +1,19 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +**EXPERIMENTAL** +Register the conda env spec for environment.yml files. +""" + +from .. import hookimpl +from ..types import CondaEnvironmentSpecifier + + +@hookimpl(tryfirst=True) +def conda_environment_specifiers(): + from ...env.specs.cep_24 import Cep24YamlFileSpec + + yield CondaEnvironmentSpecifier( + name="cep-24", + environment_spec=Cep24YamlFileSpec, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/environment_yml.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/environment_yml.py new file mode 100644 index 0000000000000000000000000000000000000000..badb66137bec679476372ab9b4b6c0e349055837 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/environment_yml.py @@ -0,0 +1,19 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +**EXPERIMENTAL** +Register the conda env spec for environment.yml files. +""" + +from .. import hookimpl +from ..types import CondaEnvironmentSpecifier + + +@hookimpl(tryfirst=True) +def conda_environment_specifiers(): + from ...env.specs.yaml_file import YamlFileSpec + + yield CondaEnvironmentSpecifier( + name="environment.yml", + environment_spec=YamlFileSpec, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/explicit.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/explicit.py new file mode 100644 index 0000000000000000000000000000000000000000..d818e96ba4abe7ccfd9238eff3a3c1b2110d00eb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/explicit.py @@ -0,0 +1,19 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +**EXPERIMENTAL** +Register the conda env spec for explicit files. +""" + +from .. import hookimpl +from ..types import CondaEnvironmentSpecifier + + +@hookimpl +def conda_environment_specifiers(): + from ...env.specs.explicit import ExplicitSpec + + yield CondaEnvironmentSpecifier( + name="explicit", + environment_spec=ExplicitSpec, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/requirements_txt.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/requirements_txt.py new file mode 100644 index 0000000000000000000000000000000000000000..962aedee715535faf7567e8992cb15f1f9cc91f6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/environment_specifiers/requirements_txt.py @@ -0,0 +1,19 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +**EXPERIMENTAL** +Register the conda env spec for requirements.txt files. +""" + +from .. import hookimpl +from ..types import CondaEnvironmentSpecifier + + +@hookimpl +def conda_environment_specifiers(): + from ...env.specs.requirements import RequirementsSpec + + yield CondaEnvironmentSpecifier( + name="requirements.txt", + environment_spec=RequirementsSpec, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/hookspec.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/hookspec.py new file mode 100644 index 0000000000000000000000000000000000000000..330f738d5c115aacf385677dea3c5dedfc6f1a9a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/hookspec.py @@ -0,0 +1,807 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Pluggy hook specifications ("hookspecs") to register conda plugins. + +Each hookspec defined in :class:`~conda.plugins.hookspec.CondaSpecs` contains +an example of how to use it. + +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pluggy + +from ..base.constants import APP_NAME +from ..deprecations import deprecated + +if TYPE_CHECKING: + from collections.abc import Iterable + + from .types import ( + CondaAuthHandler, + CondaEnvironmentExporter, + CondaEnvironmentSpecifier, + CondaHealthCheck, + CondaPackageExtractor, + CondaPostCommand, + CondaPostSolve, + CondaPostTransactionAction, + CondaPreCommand, + CondaPrefixDataLoader, + CondaPreSolve, + CondaPreTransactionAction, + CondaReporterBackend, + CondaRequestHeader, + CondaSetting, + CondaSolver, + CondaSubcommand, + CondaVirtualPackage, + ) + +deprecated.constant( + "26.3", + "26.9", + "spec_name", + APP_NAME, + addendum="Use `conda.base.constants.APP_NAME` instead.", +) + +_hookspec = pluggy.HookspecMarker(APP_NAME) +"""Decorator to mark conda plugin hook specifications, used to register plugin hook types.""" + +hookimpl = pluggy.HookimplMarker(APP_NAME) +"""Decorator to mark plugin hook implementations, used to register plugins.""" + + +class CondaSpecs: + """Collection of all supported conda plugin hookspecs.""" + + @_hookspec + def conda_solvers(self) -> Iterable[CondaSolver]: + """ + Register solvers in conda. + + **Example:** + + .. code-block:: python + + import logging + + from conda import plugins + from conda.core import solve + + log = logging.getLogger(__name__) + + + class VerboseSolver(solve.Solver): + def solve_final_state(self, *args, **kwargs): + log.info("My verbose solver!") + return super().solve_final_state(*args, **kwargs) + + + @plugins.hookimpl + def conda_solvers(): + yield plugins.types.CondaSolver( + name="verbose-classic", + backend=VerboseSolver, + ) + + :return: An iterable of solver entries. + """ + yield from () + + @_hookspec + def conda_subcommands(self) -> Iterable[CondaSubcommand]: + """ + Register external subcommands in conda. + + **Example:** + + .. code-block:: python + + from conda import plugins + + + def example_command(args): + print("This is an example command!") + + + @plugins.hookimpl + def conda_subcommands(): + yield plugins.types.CondaSubcommand( + name="example", + summary="example command", + action=example_command, + ) + + :return: An iterable of subcommand entries. + """ + yield from () + + @_hookspec + def conda_virtual_packages(self) -> Iterable[CondaVirtualPackage]: + """ + Register virtual packages in Conda. + + **Example:** + + .. code-block:: python + + from conda import plugins + + + @plugins.hookimpl + def conda_virtual_packages(): + yield plugins.types.CondaVirtualPackage( + name="my_custom_os", + version="1.2.3", + build="x86_64", + ) + + :return: An iterable of virtual package entries. + """ + yield from () + + @_hookspec + def conda_pre_commands(self) -> Iterable[CondaPreCommand]: + """ + Register pre-command functions in conda. + + **Example:** + + .. code-block:: python + + from conda import plugins + + + def example_pre_command(command): + print("pre-command action") + + + @plugins.hookimpl + def conda_pre_commands(): + yield plugins.types.CondaPreCommand( + name="example-pre-command", + action=example_pre_command, + run_for={"install", "create"}, + ) + """ + yield from () + + @_hookspec + def conda_post_commands(self) -> Iterable[CondaPostCommand]: + """ + Register post-command functions in conda. + + **Example:** + + .. code-block:: python + + from conda import plugins + + + def example_post_command(command): + print("post-command action") + + + @plugins.hookimpl + def conda_post_commands(): + yield plugins.types.CondaPostCommand( + name="example-post-command", + action=example_post_command, + run_for={"install", "create"}, + ) + """ + yield from () + + @_hookspec + def conda_auth_handlers(self) -> Iterable[CondaAuthHandler]: + """ + Register a conda auth handler derived from the requests API. + + This plugin hook allows attaching requests auth handler subclasses, + e.g. when authenticating requests against individual channels hosted + at HTTP/HTTPS services. + + **Example:** + + .. code-block:: python + + import os + from conda import plugins + from requests.auth import AuthBase + + + class EnvironmentHeaderAuth(AuthBase): + def __init__(self, *args, **kwargs): + self.username = os.environ["EXAMPLE_CONDA_AUTH_USERNAME"] + self.password = os.environ["EXAMPLE_CONDA_AUTH_PASSWORD"] + + def __call__(self, request): + request.headers["X-Username"] = self.username + request.headers["X-Password"] = self.password + return request + + + @plugins.hookimpl + def conda_auth_handlers(): + yield plugins.types.CondaAuthHandler( + name="environment-header-auth", + handler=EnvironmentHeaderAuth, + ) + """ + yield from () + + @_hookspec + def conda_health_checks(self) -> Iterable[CondaHealthCheck]: + """ + Register health checks for conda doctor. + + This plugin hook allows you to add more "health checks" to conda doctor + that you can write to diagnose problems in your conda environment. + Check out the health checks already shipped with conda for inspiration. + + Health checks can optionally provide a ``fixer`` callable that is invoked + via ``conda doctor --fix`` or ``conda doctor --fix ``. + + **Example (check only):** + + .. code-block:: python + + from conda import plugins + + + def example_health_check(prefix: str, verbose: bool): + print("This is an example health check!") + + + @plugins.hookimpl + def conda_health_checks(): + yield plugins.types.CondaHealthCheck( + name="example-health-check", + action=example_health_check, + ) + + **Example (check with fix):** + + .. code-block:: python + + from conda import plugins + + + def my_health_check(prefix: str, verbose: bool): + # Check and report issues + print("Checking for issues...") + + + def my_health_fix(prefix: str, args) -> int: + # Fix the issues + print("Fixing issues...") + return 0 # exit code + + + @plugins.hookimpl + def conda_health_checks(): + yield plugins.CondaHealthCheck( + name="my-check", + action=my_health_check, + fixer=my_health_fix, + summary="Check for common issues", + fix="Repair detected issues", + ) + + :return: An iterable of health check entries. + """ + yield from () + + @_hookspec + def conda_pre_transaction_actions(self) -> Iterable[CondaPreTransactionAction]: + """Register pre-transaction hooks. + + Pre-transaction hooks run before all other actions run in a + UnlinkLinkTransaction. For information about the Action class, + see :class:`~conda.core.path_actions.Action`. + + **Example:** + + .. code-block:: python + + from conda import plugins + from conda.plugins.types import CondaPreTransactionAction + from conda.core.path_actions import Action + + + class PrintAction(Action): + def verify(self): + print("Performing verification...") + self._verified = True + + def execute(self): + print( + self.transaction_context, + self.target_prefix, + self.unlink_precs, + self.link_precs, + self.remove_specs, + self.update_specs, + self.neutered_specs, + ) + + def reverse(self): + print("Reversing only happens when `execute` raises an exception.") + + def cleanup(self): + print("Carrying out cleanup...") + + + class PrintActionPlugin: + @plugins.hookimpl + def conda_pre_transaction_actions( + self, + ) -> Iterable[CondaPreTransactionAction]: + yield CondaPreTransactionAction( + name="example-pre-transaction-action", + action=PrintAction, + ) + """ + yield from () + + @_hookspec + def conda_post_transaction_actions(self) -> Iterable[CondaPostTransactionAction]: + """Register post-transaction hooks. + + Post-transaction hooks run after all other actions run in a + UnlinkLinkTransaction. For information about the Action class, + see :class:`~conda.core.path_actions.Action`. + + **Example:** + + .. code-block:: python + + from conda import plugins + from conda.plugins.types import CondaPostTransactionAction + from conda.core.path_actions import Action + + + class PrintAction(Action): + def verify(self): + print("Performing verification...") + self._verified = True + + def execute(self): + print( + self.transaction_context, + self.target_prefix, + self.unlink_precs, + self.link_precs, + self.remove_specs, + self.update_specs, + self.neutered_specs, + ) + + def reverse(self): + print("Reversing only happens when `execute` raises an exception.") + + def cleanup(self): + print("Carrying out cleanup...") + + + class PrintActionPlugin: + @plugins.hookimpl + def conda_post_transaction_actions( + self, + ) -> Iterable[CondaPostTransactionAction]: + yield CondaPostTransactionAction( + name="example-post-transaction-action", + action=PrintAction, + ) + """ + yield from () + + @_hookspec + def conda_pre_solves(self) -> Iterable[CondaPreSolve]: + """ + Register pre-solve functions in conda that are used in the + general solver API, before the solver processes the package specs in + search of a solution. + + **Example:** + + .. code-block:: python + + from conda import plugins + from conda.models.match_spec import MatchSpec + + + def example_pre_solve( + specs_to_add: frozenset[MatchSpec], + specs_to_remove: frozenset[MatchSpec], + ): + print(f"Adding {len(specs_to_add)} packages") + print(f"Removing {len(specs_to_remove)} packages") + + + @plugins.hookimpl + def conda_pre_solves(): + yield plugins.types.CondaPreSolve( + name="example-pre-solve", + action=example_pre_solve, + ) + """ + yield from () + + @_hookspec + def conda_post_solves(self) -> Iterable[CondaPostSolve]: + """ + Register post-solve functions in conda that are used in the + general solver API, after the solver has provided the package + records to add or remove from the conda environment. + + **Example:** + + .. code-block:: python + + from conda import plugins + from conda.models.records import PackageRecord + + + def example_post_solve( + repodata_fn: str, + unlink_precs: tuple[PackageRecord, ...], + link_precs: tuple[PackageRecord, ...], + ): + print(f"Uninstalling {len(unlink_precs)} packages") + print(f"Installing {len(link_precs)} packages") + + + @plugins.hookimpl + def conda_post_solves(): + yield plugins.types.CondaPostSolve( + name="example-post-solve", + action=example_post_solve, + ) + """ + yield from () + + @_hookspec + def conda_settings(self) -> Iterable[CondaSetting]: + """ + Register new setting + + The example below defines a simple string type parameter + + **Example:** + + .. code-block:: python + + from conda import plugins + from conda.common.configuration import PrimitiveParameter, SequenceParameter + + + @plugins.hookimpl + def conda_settings(): + yield plugins.types.CondaSetting( + name="example_option", + description="This is an example option", + parameter=PrimitiveParameter("default_value", element_type=str), + aliases=("example_option_alias",), + ) + """ + yield from () + + @_hookspec + def conda_reporter_backends(self) -> Iterable[CondaReporterBackend]: + """ + Register new reporter backend + + The example below defines a reporter backend that uses the ``pprint`` module in Python. + + **Example:** + + .. code-block:: python + + from pprint import pformat + + from conda import plugins + from conda.plugins.types import ( + CondaReporterBackend, + ReporterRendererBase, + ProgressBarBase, + ) + + + class PprintReporterRenderer(ReporterRendererBase): + "Implementation of the ReporterRendererBase" + + def detail_view(self, data): + return pformat(data) + + def envs_list(self, data): + formatted_data = pformat(data) + return f"Environments: {formatted_data}" + + def progress_bar(self, description, io_context_manager) -> ProgressBarBase: + "Returns our custom progress bar implementation" + return PprintProgressBar(description, io_context_manager) + + + class PprintProgressBar(ProgressBarBase): + "Blank implementation of ProgressBarBase which does nothing" + + def update_to(self, fraction) -> None: + pass + + def refresh(self) -> None: + pass + + def close(self) -> None: + pass + + + @plugins.hookimpl + def conda_reporter_backends(): + yield CondaReporterBackend( + name="pprint", + description="Reporter backend based on the pprint module", + renderer=PprintReporterRenderer, + ) + + """ + yield from () + + @_hookspec + def conda_session_headers(self, host: str) -> Iterable[CondaRequestHeader]: + """ + Register new HTTP request headers + + The example below defines how to add HTTP headers for all requests + with the hostname of ``example.com``. + + **Example:** + + .. code-block:: python + + from conda import plugins + + HOSTS = {"example.com", "sub.example.com"} + + + @plugins.hookimpl + def conda_session_headers(host: str): + if host in HOSTS: + yield plugins.types.CondaRequestHeader( + name="Example-Header", + value="example", + ) + """ + yield from () + + @_hookspec + def conda_request_headers( + self, host: str, path: str + ) -> Iterable[CondaRequestHeader]: + """ + Register new HTTP request headers + + The example below defines how to add HTTP headers for all requests + with the hostname of ``example.com`` and a ``path/to/endpoint.json`` path. + + **Example:** + + .. code-block:: python + + from conda import plugins + + HOSTS = {"example.com", "sub.example.com"} + ENDPOINT = "/path/to/endpoint.json" + + + @plugins.hookimpl + def conda_request_headers(host: str, path: str): + if host in HOSTS and path == ENDPOINT: + yield plugins.types.CondaRequestHeader( + name="Example-Header", + value="example", + ) + """ + yield from () + + @_hookspec + def conda_prefix_data_loaders() -> Iterable[CondaPrefixDataLoader]: + """ + Register new loaders for PrefixData + + The example below defines how to expose the packages installed + by a hypothetical 'penguin' tool as conda packages. + + **Example:** + + .. code-block:: python + + from pathlib import Path + + from conda import plugins + from conda.common.path import PathType + from conda.models.records import PrefixRecord + from conda.plugins.types import CondaPrefixDataLoader + + + @plugins.hookimpl + def conda_prefix_data_loaders(): + yield CondaPrefixDataLoader( + "hypothetical", + load_hypothetical_packages, + ) + + + def load_hypothetical_packages( + prefix: PathType, records: dict[str, PrefixRecord] + ) -> dict[str, PrefixRecord]: + penguin_records = {} + for info in Path(prefix).glob("lib/penguin/*.penguin-info"): + name, version = info.name.rsplit("-", 1) + kwargs = {} # retrieve extra fields here + penguin_records[name] = PrefixRecord( + name=name, version=version, build_number=0, build="0", **kwargs + ) + records.update(penguin_records) + return penguin_records + """ + yield from () + + @_hookspec + def conda_environment_specifiers(self) -> Iterable[CondaEnvironmentSpecifier]: + """ + **EXPERIMENTAL** + Register new conda env spec type + + The example below defines a type of conda env file called "random". It + can parse a file with the file extension `.random`. This plugin will ignore + whatever is in the input environment file and produce an environment with a + random name and with random packages. + + **Example:** + + .. code-block:: python + + import json + import random + from pathlib import Path + from subprocess import run + from conda import plugins + from ...plugins.types import EnvironmentSpecBase + from conda.env.env import Environment + + packages = ["python", "numpy", "scipy", "matplotlib", "pandas", "scikit-learn"] + + + class RandomSpec(EnvironmentSpecBase): + extensions = {".random"} + + def __init__(self, filename: str): + self.filename = filename + + def can_handle(self): + # Return early if no filename was provided + if self.filename is None: + return False + + # Extract the file extension (e.g., '.txt' or '' if no extension) + file_ext = os.path.splitext(self.filename)[1] + + # Check if the file has a supported extension and exists + return any( + spec_ext == file_ext and os.path.exists(self.filename) + for spec_ext in RandomSpec.extensions + ) + + def env(self): + return Environment( + name="".join(random.choice("0123456789abcdef") for i in range(6)), + dependencies=[random.choice(packages) for i in range(6)], + ) + + + @plugins.hookimpl + def conda_environment_specifiers(): + yield plugins.CondaEnvSpec( + name="random", + environment_spec=RandomSpec, + ) + """ + yield from () + + @_hookspec + def conda_environment_exporters(self) -> Iterable[CondaEnvironmentExporter]: + """ + Register new conda environment exporter + + Environment exporters serialize conda Environment objects to different + output formats (JSON, TOML, XML, etc.) for the 'conda export' command. + This is separate from environment specifiers which parse input files. + + **Example:** + + .. code-block:: python + + import tomlkit + from conda import plugins + from conda.exceptions import CondaValueError + from conda.models.environment import Environment + from conda.plugins.types import CondaEnvironmentExporter + + + def export_toml(env: Environment) -> str: + # Export Environment to TOML format + # For formats that use the standard dictionary structure, + # you can use the shared utility: + from conda.plugins.environment_exporters.standard import to_dict + + env_dict = to_dict(env) + + # Create TOML document + toml_doc = tomlkit.document() + + if env_dict.get("name"): + toml_doc["name"] = env_dict["name"] + + if env_dict.get("channels"): + toml_doc["channels"] = env_dict["channels"] + + if env_dict.get("dependencies"): + toml_doc["dependencies"] = env_dict["dependencies"] + + if env_dict.get("variables"): + toml_doc["variables"] = env_dict["variables"] + + return tomlkit.dumps(toml_doc) + + + @plugins.hookimpl + def conda_environment_exporters(): + yield CondaEnvironmentExporter( + name="environment-toml", + aliases=("toml",), + default_filenames=("environment.toml",), + export=export_toml, + ) + """ + yield from () + + @_hookspec + def conda_package_extractors(self) -> Iterable[CondaPackageExtractor]: + """ + Register package extractors for different archive formats. + + Package extractors handle the unpacking of package archives. Each extractor + specifies which file extensions it supports (e.g., ``.conda``, ``.tar.bz2``) + and provides an extraction function that takes the source archive path and + destination directory. + + **Example:** + + .. code-block:: python + + from conda import plugins + from conda.common.path import PathType + + + def extract_custom(source_path: PathType, destination_directory: PathType) -> None: + # Custom extraction logic for a hypothetical package format + ... + + + @plugins.hookimpl + def conda_package_extractors(): + yield plugins.types.CondaPackageExtractor( + name="custom-package", + extensions=[".custom"], + extract=extract_custom, + ) + + :return: An iterable of :class:`~conda.plugins.types.CondaPackageExtractor` entries. + """ + yield from () diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/manager.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..0d7b94144b9f94f22272f5a092cac27edc7d495a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/manager.py @@ -0,0 +1,921 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This module contains a subclass implementation of pluggy's +`PluginManager `_. + +Additionally, it contains a function we use to construct the ``PluginManager`` object and +register all plugins during conda's startup process. +""" + +from __future__ import annotations + +import functools +import logging +import os +from importlib.metadata import distributions +from inspect import getmodule, isclass +from typing import TYPE_CHECKING, overload + +import pluggy + +from ..auxlib import NULL +from ..auxlib.ish import dals +from ..base.constants import APP_NAME, DEFAULT_CONSOLE_REPORTER_BACKEND +from ..base.context import context +from ..common.io import dashlist +from ..exceptions import ( + CondaValueError, + EnvironmentExporterNotDetected, + EnvironmentSpecPluginNotDetected, + PluginError, +) +from . import ( + environment_exporters, + environment_specifiers, + package_extractors, + post_solves, + prefix_data_loaders, + reporter_backends, + solvers, + subcommands, + virtual_packages, +) +from .config import PluginConfig +from .hookspec import CondaSpecs +from .subcommands.doctor import health_checks + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + from typing import Literal + + from requests.auth import AuthBase + + from ..common.path import PathType + from ..core.path_actions import Action + from ..core.solve import Solver + from ..models.match_spec import MatchSpec + from ..models.records import PackageRecord + from .types import ( + CondaAuthHandler, + CondaEnvironmentExporter, + CondaEnvironmentSpecifier, + CondaHealthCheck, + CondaPackageExtractor, + CondaPostCommand, + CondaPostSolve, + CondaPostTransactionAction, + CondaPreCommand, + CondaPrefixDataLoader, + CondaPrefixDataLoaderCallable, + CondaPreSolve, + CondaPreTransactionAction, + CondaReporterBackend, + CondaRequestHeader, + CondaSetting, + CondaSolver, + CondaSubcommand, + CondaVirtualPackage, + ) + +log = logging.getLogger(__name__) + + +class CondaPluginManager(pluggy.PluginManager): + """ + The conda plugin manager to implement behavior additional to pluggy's default plugin manager. + """ + + get_cached_solver_backend: Callable[[str | None], type[Solver]] + """Cached version of the :meth:`~conda.plugins.manager.CondaPluginManager.get_solver_backend` method.""" + + get_cached_session_headers: Callable[[str], dict[str, str]] + """Cached version of the :meth:`~conda.plugins.manager.CondaPluginManager.get_session_headers` method.""" + + get_cached_request_headers: Callable[[str, str], dict[str, str]] + """Cached version of the :meth:`~conda.plugins.manager.CondaPluginManager.get_request_headers` method.""" + + def __init__(self, *args, **kwargs): + super().__init__(APP_NAME, *args, **kwargs) + # Make the cache containers local to the instances so that the + # reference from cache to the instance gets garbage collected with the instance + self.get_cached_solver_backend = functools.cache(self.get_solver_backend) + self.get_cached_session_headers = functools.cache(self.get_session_headers) + self.get_cached_request_headers = functools.cache(self.get_request_headers) + + def get_canonical_name(self, plugin: object) -> str: + # detect the fully qualified module name + prefix = "" + if (module := getmodule(plugin)) and module.__spec__: + prefix = module.__spec__.name + + # return the fully qualified name for modules + if module is plugin: + return prefix + + # return the fully qualified name for classes + elif isclass(plugin): + return f"{prefix}.{plugin.__qualname__}" + + # return the fully qualified name for instances + else: + return f"{prefix}.{plugin.__class__.__qualname__}[{id(plugin)}]" + + def register(self, plugin, name: str | None = None) -> str | None: + """ + Call :meth:`pluggy.PluginManager.register` and return the result or + ignore errors raised, except ``ValueError``, which means the plugin + had already been registered. + """ + try: + # register plugin but ignore ValueError since that means + # the plugin has already been registered + return super().register(plugin, name=name) + except ValueError: + return None + except Exception as err: + raise PluginError( + f"Error while loading conda plugin: " + f"{name or self.get_canonical_name(plugin)} ({err})" + ) from err + + def load_plugins(self, *plugins) -> int: + """ + Load the provided list of plugins and fail gracefully on error. + The provided list of plugins can either be classes or modules with + :attr:`~conda.plugins.hookimpl`. + """ + count = 0 + for plugin in plugins: + if self.register(plugin): + count += 1 + return count + + def load_entrypoints(self, group: str, name: str | None = None) -> int: + """Load modules from querying the specified setuptools ``group``. + + :param str group: Entry point group to load plugins. + :param str name: If given, loads only plugins with the given ``name``. + :rtype: int + :return: The number of plugins loaded by this call. + """ + count = 0 + for dist in distributions(): + for entry_point in dist.entry_points: + # skip entry points that don't match the group/name + if entry_point.group != group or ( + name is not None and entry_point.name != name + ): + continue + + # attempt to load plugin from entry point + try: + plugin = entry_point.load() + except Exception as err: + # not using exc_info=True here since the CLI loggers are + # set up after CLI initialization and argument parsing, + # meaning that it comes too late to properly render + # a traceback; instead we pass exc_info conditionally on + # context.verbosity + log.warning( + f"Error while loading conda entry point: {entry_point.name} ({err})", + exc_info=err if context.info else None, + ) + continue + + if self.register(plugin): + count += 1 + return count + + @overload + def get_hook_results( + self, name: Literal["subcommands"] + ) -> list[CondaSubcommand]: ... + + @overload + def get_hook_results( + self, name: Literal["virtual_packages"] + ) -> list[CondaVirtualPackage]: ... + + @overload + def get_hook_results(self, name: Literal["solvers"]) -> list[CondaSolver]: ... + + @overload + def get_hook_results( + self, name: Literal["pre_commands"] + ) -> list[CondaPreCommand]: ... + + @overload + def get_hook_results( + self, name: Literal["post_commands"] + ) -> list[CondaPostCommand]: ... + + @overload + def get_hook_results( + self, name: Literal["auth_handlers"] + ) -> list[CondaAuthHandler]: ... + + @overload + def get_hook_results( + self, name: Literal["health_checks"] + ) -> list[CondaHealthCheck]: ... + + @overload + def get_hook_results(self, name: Literal["pre_solves"]) -> list[CondaPreSolve]: ... + + @overload + def get_hook_results( + self, name: Literal["post_solves"] + ) -> list[CondaPostSolve]: ... + + @overload + def get_hook_results( + self, name: Literal["session_headers"], *, host: str + ) -> list[CondaRequestHeader]: ... + + @overload + def get_hook_results( + self, name: Literal["request_headers"], *, host: str, path: str + ) -> list[CondaRequestHeader]: ... + + @overload + def get_hook_results(self, name: Literal["settings"]) -> list[CondaSetting]: ... + + @overload + def get_hook_results( + self, name: Literal["reporter_backends"] + ) -> list[CondaReporterBackend]: ... + + @overload + def get_hook_results( + self, name: Literal["pre_transaction_actions"] + ) -> list[CondaPreTransactionAction]: ... + + @overload + def get_hook_results( + self, name: Literal["post_transaction_actions"] + ) -> list[CondaPostTransactionAction]: ... + + @overload + def get_hook_results( + self, name: Literal["prefix_data_loaders"] + ) -> list[CondaPrefixDataLoader]: ... + + @overload + def get_hook_results( + self, name: Literal["environment_specifiers"] + ) -> list[CondaEnvironmentSpecifier]: ... + + @overload + def get_hook_results( + self, name: Literal["package_extractors"] + ) -> list[CondaPackageExtractor]: ... + + @overload + def get_hook_results( + self, name: Literal["environment_exporters"] + ) -> list[CondaEnvironmentExporter]: ... + + def get_hook_results(self, name, **kwargs): + """ + Return results of the plugin hooks with the given name and + raise an error if there is a conflict. + """ + specname = f"{self.project_name}_{name}" # e.g. conda_solvers + hook = getattr(self.hook, specname, None) + if hook is None: + raise PluginError(f"Could not find requested `{name}` plugins") + + # hook() returns a generator of all plugins for a given specname, + # unfortunately this generator does not offer any information about which + # package/module the plugin is defined in, this makes reporting errors in + # a meaningful way to users difficult + plugins = [plugin for plugins in hook(**kwargs) for plugin in plugins] + + # Validate plugin names since plugins may not properly inherit from CondaPlugin + invalid = [ + plugin + for plugin in plugins + if not hasattr(plugin, "name") + or not isinstance(plugin.name, str) + or plugin.name != plugin.name.lower().strip() + ] + if invalid: + raise PluginError( + f"Invalid plugin names found for `{name}`:\n" + f"{dashlist(map(repr, invalid))}\n" + f"\n" + f"Please report this issue to the plugin author(s)." + ) + + # Check for conflicts since no two plugins can have the same name + seen = set() + conflicts = [ + plugin for plugin in plugins if plugin.name in seen or seen.add(plugin.name) + ] + if conflicts: + raise PluginError( + f"Conflicting plugins found for `{name}`:\n" + f"{dashlist(map(repr, conflicts))}\n" + f"\n" + f"Multiple conda plugins are registered via the `{specname}` hook. " + f"Please make sure that you don't have any incompatible plugins installed." + ) + + return sorted(plugins, key=lambda plugin: plugin.name) + + def get_solvers(self) -> dict[str, CondaSolver]: + """Return a mapping from solver name to solver class.""" + return { + solver_plugin.name: solver_plugin + for solver_plugin in self.get_hook_results("solvers") + } + + def get_solver_backend(self, name: str | None = None) -> type[Solver]: + """ + Get the solver backend with the given name (or fall back to the + name provided in the context). + + See ``context.solver`` for more details. + + Please use the cached version of this method called + :meth:`get_cached_solver_backend` for high-throughput code paths + which is set up as a instance-specific LRU cache. + """ + # Some light data validation in case name isn't given. + name = (name or context.solver).lower().strip() + + solvers_mapping = self.get_solvers() + + # Look up the solver mapping and fail loudly if it can't + # find the requested solver. + solver_plugin = solvers_mapping.get(name, None) + if solver_plugin is None: + raise CondaValueError( + f"You have chosen a non-default solver backend ({name}) " + f"but it was not recognized. Choose one of: " + f"{', '.join(solvers_mapping)}" + ) + + return solver_plugin.backend + + def get_auth_handler(self, name: str) -> type[AuthBase] | None: + """ + Get the auth handler with the given name or None + """ + name = name.lower().strip() + auth_handlers = self.get_hook_results("auth_handlers") + matches = [item for item in auth_handlers if item.name == name] + + if len(matches) > 0: + return matches[0].handler + return None + + def get_settings(self) -> dict[str, CondaSetting]: + """ + Return a mapping of plugin setting name to CondaSetting objects. + + This method intentionally overwrites any duplicates that may be present + """ + return { + config_param.name: config_param + for config_param in self.get_hook_results("settings") + } + + def invoke_pre_commands(self, command: str) -> None: + """ + Invokes ``CondaPreCommand.action`` functions registered with ``conda_pre_commands``. + + :param command: name of the command that is currently being invoked + """ + for hook in self.get_hook_results("pre_commands"): + if command in hook.run_for: + hook.action(command) + + def invoke_post_commands(self, command: str) -> None: + """ + Invokes ``CondaPostCommand.action`` functions registered with ``conda_post_commands``. + + :param command: name of the command that is currently being invoked + """ + for hook in self.get_hook_results("post_commands"): + if command in hook.run_for: + hook.action(command) + + def disable_external_plugins(self) -> None: + """ + Disables all currently registered plugins except built-in conda plugins + """ + for name, plugin in self.list_name_plugin(): + if not name.startswith("conda.plugins.") and not self.is_blocked(name): + self.set_blocked(name) + + def get_subcommands(self) -> dict[str, CondaSubcommand]: + return { + subcommand.name: subcommand + for subcommand in self.get_hook_results("subcommands") + } + + def get_health_checks(self) -> dict[str, CondaHealthCheck]: + """Return a mapping of health check name to health check.""" + return {check.name: check for check in self.get_hook_results("health_checks")} + + def get_reporter_backends(self) -> tuple[CondaReporterBackend, ...]: + return tuple(self.get_hook_results("reporter_backends")) + + def get_reporter_backend(self, name: str) -> CondaReporterBackend: + """ + Attempts to find a reporter backend while providing a fallback option if it is + not found. + + This method must return a valid ``CondaReporterBackend`` object or else it will + raise an exception. + """ + reporter_backends_map = { + reporter_backend.name: reporter_backend + for reporter_backend in self.get_reporter_backends() + } + reporter_backend = reporter_backends_map.get(name, None) + if reporter_backend is None: + log.warning( + f'Unable to find reporter backend: "{name}"; ' + f'falling back to using "{DEFAULT_CONSOLE_REPORTER_BACKEND}"' + ) + return reporter_backends_map.get(DEFAULT_CONSOLE_REPORTER_BACKEND) + else: + return reporter_backend + + def get_virtual_package_records(self) -> tuple[PackageRecord, ...]: + return tuple( + virtual_package + for hook in self.get_hook_results("virtual_packages") + if (virtual_package := hook.to_virtual_package()) is not NULL + ) + + def get_session_headers(self, host: str) -> dict[str, str]: + return { + hook.name: hook.value + for hook in self.get_hook_results("session_headers", host=host) + } + + def get_request_headers(self, host: str, path: str) -> dict[str, str]: + return { + hook.name: hook.value + for hook in self.get_hook_results("request_headers", host=host, path=path) + } + + def get_prefix_data_loaders(self) -> Iterable[CondaPrefixDataLoaderCallable]: + for hook in self.get_hook_results("prefix_data_loaders"): + yield hook.loader + + def invoke_pre_solves( + self, + specs_to_add: frozenset[MatchSpec], + specs_to_remove: frozenset[MatchSpec], + ) -> None: + """ + Invokes ``CondaPreSolve.action`` functions registered with ``conda_pre_solves``. + + :param specs_to_add: + :param specs_to_remove: + """ + for hook in self.get_hook_results("pre_solves"): + hook.action(specs_to_add, specs_to_remove) + + def invoke_post_solves( + self, + repodata_fn: str, + unlink_precs: tuple[PackageRecord, ...], + link_precs: tuple[PackageRecord, ...], + ) -> None: + """ + Invokes ``CondaPostSolve.action`` functions registered with ``conda_post_solves``. + + :param repodata_fn: + :param unlink_precs: + :param link_precs: + """ + for hook in self.get_hook_results("post_solves"): + hook.action(repodata_fn, unlink_precs, link_precs) + + def load_settings(self) -> None: + """ + Iterates through all registered settings and adds them to the + :class:`conda.common.configuration.PluginConfig` class. + """ + for name, setting in self.get_settings().items(): + PluginConfig.add_plugin_setting(name, setting.parameter, setting.aliases) + + def get_config(self, data) -> PluginConfig: + """ + Retrieve the configuration for the plugin. + Returns: + PluginConfig: The configuration object for the plugin, initialized with raw data from the context. + """ + return PluginConfig(data) + + def get_environment_specifiers(self) -> dict[str, CondaEnvironmentSpecifier]: + """ + Returns a mapping from environment specifier name to environment specifier. + """ + return { + hook.name: hook for hook in self.get_hook_results("environment_specifiers") + } + + def get_environment_specifier_by_name( + self, + source: str, + name: str, + ) -> CondaEnvironmentSpecifier: + """Get an environment specifier plugin by name + + :param source: full path to the environment spec file/source + :param name: name of the environment plugin to load + :raises CondaValueError: if the requested plugin is not available. + :raises PluginError: if the requested plugin is unable to handle the provided file. + :returns: an environment specifier plugin that matches the provided plugin name, or can handle the provided file + """ + name = name.lower().strip() + plugins = self.get_environment_specifiers() + try: + plugin = plugins[name] + except KeyError: + raise CondaValueError( + f"You have chosen an unrecognized environment" + f" specifier type ({name}). Choose one of: " + f"{dashlist(plugins)}" + ) + else: + # Try to load the plugin and check if it can handle the environment spec + try: + if plugin.environment_spec(source).can_handle(): + return plugin + except Exception as e: + raise PluginError( + dals( + f""" + An error occured when handling '{source}' with plugin '{name}'. + + {type(e).__name__}: {e} + """ + ) + ) + else: + # If the plugin was not able to handle the environment spec, raise an error + raise PluginError( + f"Requested plugin '{name}' is unable to handle environment spec '{source}'" + ) + + def detect_environment_specifier(self, source: str) -> CondaEnvironmentSpecifier: + """Detect the environment specifier plugin for a given spec source + + Raises PluginError if more than one environment_spec plugin is found to be able to handle the file. + Raises EnvironmentSpecPluginNotDetected if no plugins were found. + + :param source: full path to the environment spec file or source + :returns: an environment specifier plugin that can handle the provided file + """ + hooks = self.get_environment_specifiers() + found = [] + autodetect_disabled_plugins = [] + for hook_name, hook in hooks.items(): + if hook.environment_spec.detection_supported: + log.debug("EnvironmentSpec hook: checking %s", hook_name) + try: + if hook.environment_spec(source).can_handle(): + log.debug( + "EnvironmentSpec hook: %s can be %s", + source, + hook_name, + ) + found.append(hook) + else: + log.debug( + "EnvironmentSpec hook: %s can NOT be handled by %s", + source, + hook_name, + ) + except Exception as e: + log.error( + "EnvironmentSpec hook: an error occurred when handling '%s' with plugin '%s'. %s", + source, + hook_name, + e, + ) + log.debug("%r", e, exc_info=e) + else: + log.debug( + "EnvironmentSpec hook: %s can NOT be handled by %s", + source, + hook_name, + ) + autodetect_disabled_plugins.append(hook_name) + + if not found: + # HACK: if there was no plugin found, try to catch all `environment.yml` plugin + # FUTURE: Remove this final try at using the environment.yml to read the environment + # file. This should be removed in "26.9" when the deprecations warning for + # environment.yml's that are not compliant with cep-0024 are removed. + try: + return self.get_environment_specifier_by_name( + source=source, name="environment.yml" + ) + except (PluginError, CondaValueError) as exc: + # raise error if no plugins found that can read the environment file + raise EnvironmentSpecPluginNotDetected( + name=source, + plugin_names=hooks, + autodetect_disabled_plugins=autodetect_disabled_plugins, + ) from exc + elif len(found) == 1: + # return the plugin if only one is found + return found[0] + else: + # raise an error if there is more than one plugin found + raise PluginError( + dals( + f""" + Too many plugins found that can handle the environment file '{source}': + + {", ".join([hook.name for hook in found])} + + Please make sure that you don't have any overlapping plugins installed. + """ + ) + ) + + def get_environment_specifier( + self, + source: str, + name: str | None = None, + ) -> CondaEnvironmentSpecifier: + """Get the environment specifier plugin for a given spec source, or given a plugin name + Raises PluginError if more than one environment_spec plugin is found to be able to handle the file. + Raises EnvironmentSpecPluginNotDetected if no plugins were found. + Raises CondaValueError if the requested plugin is not available. + + :param filename: full path to the environment spec file/source + :param name: name of the environment plugin to load + :returns: an environment specifier plugin that matches the provided plugin name, or can handle the provided file + """ + if not name: + return self.detect_environment_specifier(source) + else: + return self.get_environment_specifier_by_name(source=source, name=name) + + def get_environment_exporters(self) -> Iterable[CondaEnvironmentExporter]: + """ + Yields all detected environment exporters. + """ + yield from self.get_hook_results("environment_exporters") + + def get_exporter_format_mapping(self) -> dict[str, CondaEnvironmentExporter]: + """ + Get a mapping from format names (including aliases) to environment exporters. + + :return: Dict mapping format name to CondaEnvironmentExporter + :raises PluginError: If multiple exporters use the same format name or alias + """ + mapping = {} + conflicts = {} # format_name -> set of plugin names + + for plugin in self.get_environment_exporters(): + for format_name in (plugin.name, *plugin.aliases): + if format_name in mapping: + if format_name not in conflicts: + conflicts[format_name] = {mapping[format_name].name} + conflicts[format_name].add(plugin.name) + else: + mapping[format_name] = plugin + + if conflicts: + conflict_details = [] + for format_name, plugin_names in sorted(conflicts.items()): + plugins_str = ", ".join(sorted(plugin_names)) + conflict_details.append( + f"'{format_name}' used by plugins: {plugins_str}" + ) + + raise PluginError( + f"Format name conflicts detected in environment exporters:" + f"{dashlist(conflict_details)}\n" + f"Multiple plugins cannot use the same format name or alias." + ) + + return mapping + + def detect_environment_exporter(self, filename: str) -> CondaEnvironmentExporter: + """ + Detect an environment exporter based on exact filename matching against default_filenames. + + :param filename: Filename to find an exporter for (basename is used for detection) + :return: CondaEnvironmentExporter that supports the filename + :raises EnvironmentExporterNotDetected: If no exporter supports the filename + :raises PluginError: If multiple exporters claim to support the same filename + """ + # Extract just the basename for matching + basename = os.path.basename(filename) + + matches = [] + for exporter_config in self.get_environment_exporters(): + # Check if basename exactly matches any of the default filenames + if basename in exporter_config.default_filenames: + matches.append(exporter_config) + + if not matches: + raise EnvironmentExporterNotDetected( + filename=basename, + exporters=self.get_environment_exporters(), + ) + elif len(matches) > 1: + raise PluginError( + f"Multiple environment exporters found that can handle filename '{basename}':" + f"{dashlist([match.name for match in matches])}\n" + f"\n" + f"Please make sure that you don't have any conflicting exporter plugins installed." + ) + return matches[0] + + def get_environment_exporter_by_format( + self, format_name: str + ) -> CondaEnvironmentExporter: + """ + Get an environment exporter based on the format name. + + :param format_name: Format name to find an exporter for (e.g., 'yaml', 'json', 'environment-yaml') + :return: CondaEnvironmentExporter that supports the format + :raises CondaValueError: If no exporter is found for the given format + """ + format_mapping = self.get_exporter_format_mapping() + exporter = format_mapping.get(format_name) + + if exporter is None: + raise CondaValueError( + f"Unknown export format '{format_name}'. " + f"Available formats:{dashlist(sorted(format_mapping.keys()))}" + ) + + return exporter + + def get_pre_transaction_actions( + self, + transaction_context: dict[str, str] | None = None, + target_prefix: str | None = None, + unlink_precs: Iterable[PackageRecord] | None = None, + link_precs: Iterable[PackageRecord] | None = None, + remove_specs: Iterable[MatchSpec] | None = None, + update_specs: Iterable[MatchSpec] | None = None, + neutered_specs: Iterable[MatchSpec] | None = None, + ) -> list[Action]: + """Get the plugin-defined pre-transaction actions. + + :param transaction_context: Mapping between target prefixes and PrefixActions + instances + :param target_prefix: Target prefix for the action + :param unlink_precs: Package records to be unlinked + :param link_precs: Package records to link + :param remove_specs: Specs to be removed + :param update_specs: Specs to be updated + :param neutered_specs: Specs to be neutered + :return: The plugin-defined pre-transaction actions + """ + return [ + hook.action( + transaction_context, + target_prefix, + unlink_precs, + link_precs, + remove_specs, + update_specs, + neutered_specs, + ) + for hook in self.get_hook_results("pre_transaction_actions") + ] + + def get_post_transaction_actions( + self, + transaction_context: dict[str, str] | None = None, + target_prefix: str | None = None, + unlink_precs: Iterable[PackageRecord] | None = None, + link_precs: Iterable[PackageRecord] | None = None, + remove_specs: Iterable[MatchSpec] | None = None, + update_specs: Iterable[MatchSpec] | None = None, + neutered_specs: Iterable[MatchSpec] | None = None, + ) -> list[Action]: + """Get the plugin-defined post-transaction actions. + + :param transaction_context: Mapping between target prefixes and PrefixActions + instances + :param target_prefix: Target prefix for the action + :param unlink_precs: Package records to be unlinked + :param link_precs: Package records to link + :param remove_specs: Specs to be removed + :param update_specs: Specs to be updated + :param neutered_specs: Specs to be neutered + :return: The plugin-defined post-transaction actions + """ + return [ + hook.action( + transaction_context, + target_prefix, + unlink_precs, + link_precs, + remove_specs, + update_specs, + neutered_specs, + ) + for hook in self.get_hook_results("post_transaction_actions") + ] + + def get_package_extractors(self) -> dict[str, CondaPackageExtractor]: + """ + Return a mapping from file extension to package extractor plugin. + + Extensions are lowercased for case-insensitive matching. + + :return: Dictionary mapping lowercased extensions (e.g., ``".conda"``) to their + :class:`~conda.plugins.types.CondaPackageExtractor` plugins. + """ + return { + extension.lower(): hook + for hook in self.get_hook_results("package_extractors") + for extension in hook.extensions + } + + def get_package_extractor( + self, + source_full_path: PathType, + ) -> CondaPackageExtractor: + """ + Get the package extractor plugin for a given package path. + + Searches through registered package extractor plugins to find one that + handles the file extension of the provided package path. + + :param source_full_path: Full path to the package archive file. + :return: The matching :class:`~conda.plugins.types.CondaPackageExtractor` plugin. + :raises PluginError: If no registered extractor handles the file extension. + """ + source_str = os.fspath(source_full_path).lower() + for extension, extractor in self.get_package_extractors().items(): + if source_str.endswith(extension): + return extractor + + raise PluginError( + f"No registered 'package_extractors' plugin found for package: {source_full_path}" + ) + + def extract_package( + self, + source_full_path: PathType, + destination_directory: PathType, + ) -> None: + """ + Extract a package archive to a destination directory. + + Finds the appropriate extractor plugin based on the file extension + and extracts the package. + + :param source_full_path: Full path to the package archive file. + :param destination_directory: Directory to extract the package contents to. + :raises PluginError: If no registered extractor handles the file extension. + """ + extractor = self.get_package_extractor(source_full_path) + extractor.extract(source_full_path, destination_directory) + + def has_package_extension(self, path: PathType) -> str | None: + """ + Check if a path has a supported package file extension. + + :param path: Path to check. + :return: The matched extension (lowercased) if found, None otherwise. + """ + path_str = os.fspath(path).lower() + for ext in self.get_package_extractors(): + if path_str.endswith(ext): + return ext + return None + + +@functools.cache +def get_plugin_manager() -> CondaPluginManager: + """ + Get a cached version of the :class:`~conda.plugins.manager.CondaPluginManager` instance, + with the built-in and entrypoints provided by the plugins loaded. + """ + plugin_manager = CondaPluginManager() + plugin_manager.add_hookspecs(CondaSpecs) + plugin_manager.load_plugins( + solvers, + *virtual_packages.plugins, + *subcommands.plugins, + *health_checks.plugins, + *post_solves.plugins, + *reporter_backends.plugins, + *package_extractors.plugins, + *prefix_data_loaders.plugins, + *environment_specifiers.plugins, + *environment_exporters.plugins, + ) + plugin_manager.load_entrypoints(APP_NAME) + return plugin_manager diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/package_extractors/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/package_extractors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7f11167a47124d84fa46a0d7f84c89d9b0871e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/package_extractors/__init__.py @@ -0,0 +1,7 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Package extractor plugins.""" + +from . import conda + +plugins = [conda] diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/package_extractors/conda.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/package_extractors/conda.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed71fd002bceefdc30c1dd33a2a3f2dfae649f8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/package_extractors/conda.py @@ -0,0 +1,75 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause + +"""Package extractor plugin for .conda and .tar.bz2 formats.""" + +from __future__ import annotations + +import os +from logging import getLogger +from os.path import join +from typing import TYPE_CHECKING + +from ...common.compat import on_linux +from ...gateways.disk.delete import path_is_clean +from ..hookspec import hookimpl +from ..types import CondaPackageExtractor + +if TYPE_CHECKING: + from ...common.path import PathType + +log = getLogger(__name__) + + +def extract_conda_or_tarball( + tarball_full_path: PathType, + destination_directory: PathType, +) -> None: + """ + Extract a .conda or .tar.bz2 package to the specified destination. + + :param tarball_full_path: Path to the package archive. + :param destination_directory: Directory to extract the package contents to. + """ + import conda_package_handling.api + + # Convert PathType to string for conda_package_handling compatibility + tarball_full_path = os.fspath(tarball_full_path) + destination_directory = os.fspath(destination_directory) + + log.debug("extracting %s\n to %s", tarball_full_path, destination_directory) + + # the most common reason this happens is due to hard-links, windows thinks + # files in the package cache are in-use. rm_rf should have moved them to + # have a .conda_trash extension though, so it's ok to just write into + # the same existing folder. + if not path_is_clean(destination_directory): + log.debug( + "package folder %s was not empty, but we're writing there.", + destination_directory, + ) + + conda_package_handling.api.extract( + tarball_full_path, dest_dir=destination_directory + ) + + if hasattr(conda_package_handling.api, "THREADSAFE_EXTRACT"): + return # indicates conda-package-handling 2.x, which implements --no-same-owner + + if on_linux and os.getuid() == 0: # pragma: no cover + # When extracting as root, tarfile will by restore ownership + # of extracted files. However, we want root to be the owner + # (our implementation of --no-same-owner). + for root, dirs, files in os.walk(destination_directory): + for fn in files: + p = join(root, fn) + os.lchown(p, 0, 0) + + +@hookimpl +def conda_package_extractors(): + yield CondaPackageExtractor( + name="conda-package", + extensions=[".tar.bz2", ".conda"], + extract=extract_conda_or_tarball, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/post_solves/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/post_solves/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..150951fc3f88fa8cf7018e6217007ceadcae7f66 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/post_solves/__init__.py @@ -0,0 +1,8 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Register the built-in post_solves hook implementations.""" + +from . import signature_verification + +plugins = [signature_verification] +"""The list of post-solve plugins for easier registration with pluggy.""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/post_solves/signature_verification.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/post_solves/signature_verification.py new file mode 100644 index 0000000000000000000000000000000000000000..0c3276d976b3b560fcce613deac467b1bd46c7ec --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/post_solves/signature_verification.py @@ -0,0 +1,25 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Register signature verification as a post-solve plugin.""" + +import warnings + +from .. import hookimpl +from ..types import CondaPostSolve + + +@hookimpl +def conda_post_solves(): + # FUTURE: conda 26.3+, remove ignore signature_verification deprecation + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=r"conda\.trust(\.\w+)? is deprecated and will be removed in 26\.3\.", + category=DeprecationWarning, + ) + from ...trust.signature_verification import signature_verification + + yield CondaPostSolve( + name="signature-verification", + action=signature_verification, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de899adfffc69c9594437ce8063789342512916a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__init__.py @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from . import pypi + +plugins = [pypi] diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc19154e1f26da25617c13e02f3dfc59b5d5783 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__init__.py @@ -0,0 +1,159 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Reads PyPI packages in a conda prefix that have been installed with non-conda tools.""" + +from __future__ import annotations + +import sys +import traceback +from logging import getLogger +from os.path import basename +from pathlib import Path +from typing import TYPE_CHECKING + +from ....auxlib.exceptions import ValidationError +from ....common.path import ( + get_python_site_packages_short_path, + win_path_ok, +) +from ....core.prefix_data import get_conda_anchor_files_and_records +from ....gateways.disk.delete import rm_rf +from ....models.prefix_graph import PrefixGraph +from ... import hookimpl +from ...types import CondaPrefixDataLoader +from .pkg_format import get_site_packages_anchor_files, read_python_record + +if TYPE_CHECKING: + from ....common.path import PathType + from ....models.records import PrefixRecord + +log = getLogger(__name__) + + +def resolved_short_path(short_path: str, prefix_path: Path) -> str: + """Return short_path with any symlinks resolved.""" + resolved_path = (prefix_path / short_path).resolve() + return resolved_path.relative_to(prefix_path.resolve()).as_posix() + + +def load_site_packages( + prefix: PathType, records: dict[str, PrefixRecord] +) -> dict[str, PrefixRecord]: + """ + Load non-conda-installed python packages in the site-packages of the prefix. + + Python packages not handled by conda are installed via other means, + like using pip or using python setup.py develop for local development. + + Packages found that are not handled by conda are converted into a + prefix record and handled in memory. + + Packages clobbering conda packages (i.e. the conda-meta record) are + removed from the in memory representation. + """ + python_pkg_record = records.get("python") + if not python_pkg_record or not python_pkg_record.version: + return {} + + prefix_path = Path(prefix) + + site_packages_dir = python_pkg_record.python_site_packages_path + if site_packages_dir is None: + site_packages_dir = get_python_site_packages_short_path( + python_pkg_record.version + ) + site_packages_path = prefix_path / win_path_ok(site_packages_dir) + + # The site-packages directory may include a symlink + # for example if lib/python3.XY is a symlink to lib/python3.XYt + resolved_site_packages_path = site_packages_path.resolve() + resolved_site_packages_dir = resolved_site_packages_path.relative_to( + prefix_path.resolve() + ).as_posix() + + if not resolved_site_packages_path.is_dir(): + return {} + + # Get anchor files for corresponding conda (handled) python packages + prefix_graph = PrefixGraph(records.values()) + python_records = prefix_graph.all_descendants(python_pkg_record) + conda_python_packages = get_conda_anchor_files_and_records( + resolved_site_packages_dir, python_records + ) + + if resolved_site_packages_dir != site_packages_dir: + # The short site-packages directory is a symlink to another path. + # It is possible that conda installed files through the symlink. + # Find those files and resolve them for comparison. + symlinked_conda_python_packages = get_conda_anchor_files_and_records( + site_packages_dir, python_records + ) + for anchor_file, pkg in symlinked_conda_python_packages.items(): + conda_python_packages[resolved_short_path(anchor_file, prefix_path)] = pkg + + # Get all anchor files and compare against conda anchor files to find clobbered conda + # packages and python packages installed via other means (not handled by conda) + sp_anchor_files = get_site_packages_anchor_files( + resolved_site_packages_path, resolved_site_packages_dir + ) + conda_anchor_files = set(conda_python_packages) + clobbered_conda_anchor_files = conda_anchor_files - sp_anchor_files + non_conda_anchor_files = sp_anchor_files - conda_anchor_files + + # If there's a mismatch for anchor files between what conda expects for a package + # based on conda-meta, and for what is actually in site-packages, then we'll delete + # the in-memory record for the conda package. In the future, we should consider + # also deleting the record on disk in the conda-meta/ directory. + for conda_anchor_file in clobbered_conda_anchor_files: + prefix_rec = records.pop(conda_python_packages[conda_anchor_file].name) + try: + extracted_package_dir = basename(prefix_rec.extracted_package_dir) + except AttributeError: + extracted_package_dir = "-".join( + map(str, (prefix_rec.name, prefix_rec.version, prefix_rec.build)) + ) + prefix_rec_json_path = ( + prefix_path / "conda-meta" / f"{extracted_package_dir}.json" + ) + try: + rm_rf(prefix_rec_json_path) + except OSError: + log.debug( + "stale information, but couldn't remove: %s", prefix_rec_json_path + ) + else: + log.debug("removed due to stale information: %s", prefix_rec_json_path) + + # Create prefix records for python packages not handled by conda + new_packages = {} + for af in non_conda_anchor_files: + try: + python_record = read_python_record( + prefix_path, af, python_pkg_record.version + ) + except OSError as e: + log.info("Python record ignored for anchor path '%s'\n due to %s", af, e) + continue + except ValidationError: + exc_type, exc_value, exc_traceback = sys.exc_info() + + tb = traceback.format_exception(exc_type, exc_value, exc_traceback) + log.warning( + "Problem reading non-conda package record at %s. Please verify that you " + "still need this, and if so, that this is still installed correctly. " + "Reinstalling this package may help.", + af, + ) + log.debug("ValidationError: \n%s\n", "\n".join(tb)) + continue + if not python_record: + continue + records[python_record.name] = python_record + new_packages[python_record.name] = python_record + + return new_packages + + +@hookimpl(tryfirst=True) +def conda_prefix_data_loaders(): + yield CondaPrefixDataLoader("pypi", load_site_packages) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/pkg_format.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/pkg_format.py new file mode 100644 index 0000000000000000000000000000000000000000..49fe720dc83d568cbea512be35fc9939091e337d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/pkg_format.py @@ -0,0 +1,1304 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Common Python package format utilities.""" + +from __future__ import annotations + +import platform +import re +import sys +import warnings +from base64 import urlsafe_b64decode +from collections import namedtuple +from configparser import ConfigParser +from csv import reader as csv_reader +from email.parser import HeaderParser +from errno import ENOENT +from io import StringIO +from itertools import chain +from logging import getLogger +from os import name as os_name +from os import scandir, strerror +from os.path import basename, dirname, isdir, isfile, join, lexists +from posixpath import normpath as posix_normpath + +from frozendict import frozendict + +from .... import CondaError +from ....auxlib.decorators import memoizedproperty +from ....common.compat import open_utf8 +from ....common.iterators import groupby_to_dict as groupby +from ....common.path import ( + get_major_minor_version, + get_python_site_packages_short_path, + pyc_path, + win_path_ok, +) +from ....models.channel import Channel +from ....models.enums import PackageType, PathEnum +from ....models.records import PathDataV1, PathsData, PrefixRecord + +log = getLogger(__name__) + +# TODO: complete this list +PYPI_TO_CONDA = { + "graphviz": "python-graphviz", +} +# TODO: complete this list +PYPI_CONDA_DEPS = { + "graphviz": ["graphviz"], # What version constraints? +} +# This regex can process requirement including or not including name. +# This is useful for parsing, for example, `Python-Version` +PARTIAL_PYPI_SPEC_PATTERN = re.compile( + r""" + # Text needs to be stripped and all extra spaces replaced by single spaces + (?P^[A-Z0-9][A-Z0-9._-]*)? + \s? + (\[(?P.*)\])? + \s? + (?P\(? \s? ([\w\d<>=!~,\s\.\*+-]*) \s? \)? )? + \s? +""", + re.VERBOSE | re.IGNORECASE, +) +PY_FILE_RE = re.compile(r"^[^\t\n\r\f\v]+/site-packages/[^\t\n\r\f\v]+\.py$") +PySpec = namedtuple("PySpec", ["name", "extras", "constraints", "marker", "url"]) + + +class MetadataWarning(Warning): + pass + + +# Dist classes +# ----------------------------------------------------------------------------- +class PythonDistribution: + """Base object describing a python distribution based on path to anchor file.""" + + MANIFEST_FILES = () # Only one is used, but many names available + REQUIRES_FILES = () # Only one is used, but many names available + MANDATORY_FILES = () + ENTRY_POINTS_FILES = ("entry_points.txt",) + + @staticmethod + def init(prefix_path, anchor_file, python_version): + if anchor_file.endswith(".egg-link"): + return PythonEggLinkDistribution(prefix_path, anchor_file, python_version) + elif ".dist-info" in anchor_file: + return PythonInstalledDistribution(prefix_path, anchor_file, python_version) + elif anchor_file.endswith(".egg-info"): + anchor_full_path = join(prefix_path, win_path_ok(anchor_file)) + sp_reference = basename(anchor_file) + return PythonEggInfoDistribution( + anchor_full_path, python_version, sp_reference + ) + elif ".egg-info" in anchor_file: + anchor_full_path = join(prefix_path, win_path_ok(dirname(anchor_file))) + sp_reference = basename(dirname(anchor_file)) + return PythonEggInfoDistribution( + anchor_full_path, python_version, sp_reference + ) + elif ".egg" in anchor_file: + anchor_full_path = join(prefix_path, win_path_ok(dirname(anchor_file))) + sp_reference = basename(dirname(anchor_file)) + return PythonEggInfoDistribution( + anchor_full_path, python_version, sp_reference + ) + else: + raise NotImplementedError() + + def __init__(self, anchor_full_path, python_version): + # Don't call PythonDistribution directly. Use the init() static method. + self.anchor_full_path = anchor_full_path + self.python_version = python_version + + if anchor_full_path and isfile(anchor_full_path): + self._metadata_dir_full_path = dirname(anchor_full_path) + elif anchor_full_path and isdir(anchor_full_path): + self._metadata_dir_full_path = anchor_full_path + else: + raise RuntimeError(f"Path not found: {anchor_full_path}") + + self._check_files() + self._metadata = PythonDistributionMetadata(anchor_full_path) + self._provides_file_data = () + self._requires_file_data = () + + def _check_files(self): + """Check the existence of mandatory files for a given distribution.""" + for fname in self.MANDATORY_FILES: + if self._metadata_dir_full_path: + fpath = join(self._metadata_dir_full_path, fname) + if not isfile(fpath): + raise OSError(ENOENT, strerror(ENOENT), fpath) + + def _check_path_data(self, path, checksum, size): + """Normalizes record data content and format.""" + if checksum: + if not checksum.startswith("sha256="): + raise ValueError( + f"Invalid checksum {checksum} at {path}. " + f"Check {self._metadata_dir_full_path}." + ) + checksum = checksum[7:] + else: + checksum = None + size = int(size) if size else None + + return path, checksum, size + + @staticmethod + def _parse_requires_file_data(data, global_section="__global__"): + # https://setuptools.readthedocs.io/en/latest/formats.html#requires-txt + requires = {} + lines = [line.strip() for line in data.split("\n") if line] + + if lines and not (lines[0].startswith("[") and lines[0].endswith("]")): + # Add dummy section for unsectioned items + lines = [f"[{global_section}]"] + lines + + # Parse sections + for line in lines: + if line.startswith("[") and line.endswith("]"): + section = line.strip()[1:-1] + requires[section] = [] + continue + + if line.strip(): + requires[section].append(line.strip()) + + # Adapt to *standard* requirements (add env markers to requirements) + reqs = [] + extras = [] + for section, values in requires.items(): + if section == global_section: + # This is the global section (same as dist_requires) + reqs.extend(values) + elif section.startswith(":"): + # The section is used as a marker + # Example: ":python_version < '3'" + marker = section.replace(":", "; ") + new_values = [v + marker for v in values] + reqs.extend(new_values) + else: + # The section is an extra, i.e. "docs", or "tests"... + extras.append(section) + marker = f'; extra == "{section}"' + new_values = [v + marker for v in values] + reqs.extend(new_values) + + return frozenset(reqs), extras + + @staticmethod + def _parse_entries_file_data(data): + # https://setuptools.readthedocs.io/en/latest/formats.html#entry-points-txt-entry-point-plugin-metadata + # FIXME: Use pkg_resources which provides API for this? + entries_data = {} + config = ConfigParser() + config.optionxform = lambda x: x # Avoid lowercasing keys + try: + do_read = config.read_file + except AttributeError: + do_read = config.readfp + do_read(StringIO(data)) + for section in config.sections(): + entries_data[section] = dict(config.items(section)) + + return entries_data + + def _load_requires_provides_file(self): + # https://setuptools.readthedocs.io/en/latest/formats.html#requires-txt + # FIXME: Use pkg_resources which provides API for this? + requires, extras = None, None + for fname in self.REQUIRES_FILES: + fpath = join(self._metadata_dir_full_path, fname) + if isfile(fpath): + with open_utf8(fpath) as fh: + data = fh.read() + + requires, extras = self._parse_requires_file_data(data) + self._provides_file_data = extras + self._requires_file_data = requires + break + + return requires, extras + + @memoizedproperty + def manifest_full_path(self): + manifest_full_path = None + if self._metadata_dir_full_path: + for fname in self.MANIFEST_FILES: + manifest_full_path = join(self._metadata_dir_full_path, fname) + if isfile(manifest_full_path): + break + return manifest_full_path + + def get_paths(self): + """ + Read the list of installed paths from record or source file. + + Example + ------- + [(u'skdata/__init__.py', u'sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU', 0), + (u'skdata/diabetes.py', None, None), + ... + ] + """ + manifest_full_path = self.manifest_full_path + if manifest_full_path: + python_version = self.python_version + sp_dir = get_python_site_packages_short_path(python_version) + "/" + prepend_metadata_dirname = ( + basename(manifest_full_path) == "installed-files.txt" + ) + if prepend_metadata_dirname: + path_prepender = basename(dirname(manifest_full_path)) + "/" + else: + path_prepender = "" + + def process_csv_row(reader): + seen = [] + records = [] + for row in reader: + cleaned_path = posix_normpath(f"{sp_dir}{path_prepender}{row[0]}") + if len(row) == 3: + checksum, size = row[1:] + if checksum: + if not checksum.startswith("sha256="): + raise ValueError( + f"Invalid checksum {checksum} at {cleaned_path}. " + f"Check {self._metadata_dir_full_path}." + ) + checksum = checksum[7:] # remove the 'sha256=' prefix + # Checksum is base64 encoded, but may not be padded; + # fix before decoding! + pad = "=" * (4 - (len(checksum) & 3)) + checksum = urlsafe_b64decode(checksum + pad).hex() + else: + checksum = None + size = int(size) if size else None + else: + checksum = size = None + if cleaned_path not in seen and row[0]: + seen.append(cleaned_path) + records.append((cleaned_path, checksum, size)) + return tuple(records) + + csv_delimiter = "," + with open_utf8(manifest_full_path) as csvfile: + record_reader = csv_reader(csvfile, delimiter=csv_delimiter) + # format of each record is (path, checksum, size) + records = process_csv_row(record_reader) + files_set = {record[0] for record in records} + + _pyc_path, _py_file_re = pyc_path, PY_FILE_RE + py_ver_mm = get_major_minor_version(python_version, with_dot=False) + missing_pyc_files = ( + ff + for ff in ( + _pyc_path(f, py_ver_mm) for f in files_set if _py_file_re.match(f) + ) + if ff not in files_set + ) + records = sorted( + (*records, *((pf, None, None) for pf in missing_pyc_files)) + ) + return records + + return [] + + def get_dist_requirements(self): + # FIXME: On some packages, requirements are not added to metadata, + # but on a separate requires.txt, see: python setup.py develop for + # anaconda-client. This is setuptools behavior. + # TODO: what is the dependency_links.txt on the same example? + data = self._metadata.get_dist_requirements() + if self._requires_file_data: + data = self._requires_file_data + elif not data: + self._load_requires_provides_file() + data = self._requires_file_data + return data + + def get_python_requirements(self): + return self._metadata.get_python_requirements() + + def get_external_requirements(self): + return self._metadata.get_external_requirements() + + def get_extra_provides(self): + # FIXME: On some packages, requirements are not added to metadata, + # but on a separate requires.txt, see: python setup.py develop for + # anaconda-client. This is setuptools behavior. + data = self._metadata.get_extra_provides() + if self._provides_file_data: + data = self._provides_file_data + elif not data: + self._load_requires_provides_file() + data = self._provides_file_data + + return data + + def get_conda_dependencies(self): + """ + Process metadata fields providing dependency information. + + This includes normalizing fields, and evaluating environment markers. + """ + python_spec = "python {}.*".format(".".join(self.python_version.split(".")[:2])) + + def pyspec_to_norm_req(pyspec): + conda_name = pypi_name_to_conda_name(norm_package_name(pyspec.name)) + return ( + f"{conda_name} {pyspec.constraints}" + if pyspec.constraints + else conda_name + ) + + reqs = self.get_dist_requirements() + pyspecs = tuple(parse_specification(req) for req in reqs) + marker_groups = groupby(lambda ps: ps.marker.split("==", 1)[0].strip(), pyspecs) + depends = {pyspec_to_norm_req(pyspec) for pyspec in marker_groups.pop("", ())} + extras = marker_groups.pop("extra", ()) + execution_context = { + "python_version": self.python_version, + } + depends.update( + pyspec_to_norm_req(pyspec) + for pyspec in chain.from_iterable(marker_groups.values()) + if interpret(pyspec.marker, execution_context) + ) + constrains = { + pyspec_to_norm_req(pyspec) for pyspec in extras if pyspec.constraints + } + depends.add(python_spec) + + return sorted(depends), sorted(constrains) + + def get_optional_dependencies(self): + raise NotImplementedError + + def get_entry_points(self): + # TODO: need to add entry points, "exports," and other files that might + # not be in RECORD + for fname in self.ENTRY_POINTS_FILES: + fpath = join(self._metadata_dir_full_path, fname) + if isfile(fpath): + with open_utf8(fpath) as fh: + data = fh.read() + return self._parse_entries_file_data(data) + + @property + def name(self): + return self._metadata.name + + @property + def norm_name(self): + return norm_package_name(self.name) + + @property + def conda_name(self): + return pypi_name_to_conda_name(self.norm_name) + + @property + def version(self): + return self._metadata.version + + +class PythonInstalledDistribution(PythonDistribution): + """ + Python distribution installed via distutils. + + Notes + ----- + - https://www.python.org/dev/peps/pep-0376/ + """ + + MANIFEST_FILES = ("RECORD",) + REQUIRES_FILES = () + MANDATORY_FILES = ("METADATA",) + # FIXME: Do this check? Disabled for tests where only Metadata file is stored + # MANDATORY_FILES = ('METADATA', 'RECORD', 'INSTALLER') + ENTRY_POINTS_FILES = () + + is_manageable = True + + def __init__(self, prefix_path, anchor_file, python_version): + anchor_full_path = join(prefix_path, win_path_ok(dirname(anchor_file))) + super().__init__(anchor_full_path, python_version) + self.sp_reference = basename(dirname(anchor_file)) + + +class PythonEggInfoDistribution(PythonDistribution): + """ + Python distribution installed via setuptools. + + Notes + ----- + - http://peak.telecommunity.com/DevCenter/EggFormats + """ + + MANIFEST_FILES = ("installed-files.txt", "SOURCES", "SOURCES.txt") + REQUIRES_FILES = ("requires.txt", "depends.txt") + MANDATORY_FILES = () + ENTRY_POINTS_FILES = ("entry_points.txt",) + + def __init__(self, anchor_full_path, python_version, sp_reference): + super().__init__(anchor_full_path, python_version) + self.sp_reference = sp_reference + + @property + def is_manageable(self): + return ( + self.manifest_full_path + and basename(self.manifest_full_path) == "installed-files.txt" + ) + + +class PythonEggLinkDistribution(PythonEggInfoDistribution): + is_manageable = False + + def __init__(self, prefix_path, anchor_file, python_version): + anchor_full_path = get_dist_file_from_egg_link(anchor_file, prefix_path) + sp_reference = None # This can be None in case the egg-info is no longer there + super().__init__(anchor_full_path, python_version, sp_reference) + + +# Python distribution/eggs metadata +# ----------------------------------------------------------------------------- + + +class PythonDistributionMetadata: + """ + Object representing the metada of a Python Distribution given by anchor + file (or directory) path. + + This metadata is extracted from a single file. Python distributions might + create additional files that complement this metadata information, but + that is handled at the python distribution level. + + Notes + ----- + - https://packaging.python.org/specifications/core-metadata/ + - Metadata 2.1: https://www.python.org/dev/peps/pep-0566/ + - Metadata 2.0: https://www.python.org/dev/peps/pep-0426/ (Withdrawn) + - Metadata 1.2: https://www.python.org/dev/peps/pep-0345/ + - Metadata 1.1: https://www.python.org/dev/peps/pep-0314/ + - Metadata 1.0: https://www.python.org/dev/peps/pep-0241/ + """ + + FILE_NAMES = ("METADATA", "PKG-INFO") + + # Python Packages Metadata 2.1 + # ----------------------------------------------------------------------------- + SINGLE_USE_KEYS = frozendict( + ( + ("Metadata-Version", "metadata_version"), + ("Name", "name"), + ("Version", "version"), + # ('Summary', 'summary'), + # ('Description', 'description'), + # ('Description-Content-Type', 'description_content_type'), + # ('Keywords', 'keywords'), + # ('Home-page', 'home_page'), + # ('Download-URL', 'download_url'), + # ('Author', 'author'), + # ('Author-email', 'author_email'), + # ('Maintainer', 'maintainer'), + # ('Maintainer-email', 'maintainer_email'), + ("License", "license"), + # # Deprecated + # ('Obsoleted-By', 'obsoleted_by'), # Note: See 2.0 + # ('Private-Version', 'private_version'), # Note: See 2.0 + ) + ) + MULTIPLE_USE_KEYS = frozendict( + ( + ("Platform", "platform"), + ("Supported-Platform", "supported_platform"), + # ('Classifier', 'classifier'), + ("Requires-Dist", "requires_dist"), + ("Requires-External", "requires_external"), + ("Requires-Python", "requires_python"), + # ('Project-URL', 'project_url'), + ("Provides-Extra", "provides_extra"), + # ('Provides-Dist', 'provides_dist'), + # ('Obsoletes-Dist', 'obsoletes_dist'), + # # Deprecated + # ('Extension', 'extension'), # Note: See 2.0 + # ('Obsoletes', 'obsoletes'), + # ('Provides', 'provides'), + ("Requires", "requires"), + # ('Setup-Requires-Dist', 'setup_requires_dist'), # Note: See 2.0 + ) + ) + + def __init__(self, path): + metadata_path = self._process_path(path, self.FILE_NAMES) + self._path = path + self._data = self._read_metadata(metadata_path) + + @staticmethod + def _process_path(path, metadata_filenames): + """Find metadata file inside dist-info folder, or check direct file.""" + metadata_path = None + if path: + if isdir(path): + for fname in metadata_filenames: + fpath = join(path, fname) + if isfile(fpath): + metadata_path = fpath + break + elif isfile(path): + # '.egg-info' file contains metadata directly + filenames = [".egg-info"] + if metadata_filenames: + filenames.extend(metadata_filenames) + if not any(path.endswith(filename) for filename in filenames): + raise RuntimeError("Mismatched paths in dist-info folder") + metadata_path = path + else: + # `path` does not exist + warnings.warn("Metadata path not found", MetadataWarning) + else: + warnings.warn("Metadata path not found", MetadataWarning) + + return metadata_path + + @classmethod + def _message_to_dict(cls, message): + """ + Convert the RFC-822 headers data into a dictionary. + + `message` is an email.parser.Message instance. + + The canonical method to transform metadata fields into such a data + structure is as follows: + - The original key-value format should be read with + email.parser.HeaderParser + - All transformed keys should be reduced to lower case. Hyphens + should be replaced with underscores, but otherwise should retain + all other characters + - The transformed value for any field marked with "(Multiple-use") + should be a single list containing all the original values for the + given key + - The Keywords field should be converted to a list by splitting the + original value on whitespace characters + - The message body, if present, should be set to the value of the + description key. + - The result should be stored as a string-keyed dictionary. + """ + new_data = {} + + if message: + for key, value in message.items(): + if key in cls.MULTIPLE_USE_KEYS: + new_key = cls.MULTIPLE_USE_KEYS[key] + if new_key not in new_data: + new_data[new_key] = [value] + else: + new_data[new_key].append(value) + + elif key in cls.SINGLE_USE_KEYS: + new_key = cls.SINGLE_USE_KEYS[key] + new_data[new_key] = value + + # TODO: Handle license later on for convenience + + return new_data + + @classmethod + def _read_metadata(cls, fpath): + """Read the original format which is stored as RFC-822 headers.""" + data = {} + if fpath and isfile(fpath): + parser = HeaderParser() + + # FIXME: Is this a correct assumption for the encoding? + # This was needed due to some errors on windows + with open_utf8(fpath) as fp: + data = parser.parse(fp) + + return cls._message_to_dict(data) + + def _get_multiple_data(self, keys): + """ + Helper method to get multiple data values by keys. + + Keys is an iterable including the preferred key in order, to include + values of key that might have been replaced (deprecated), for example + keys can be ['requires_dist', 'requires'], where the key 'requires' is + deprecated and replaced by 'requires_dist'. + """ + data = [] + if self._data: + for key in keys: + raw_data = self._data.get(key, []) + for req in raw_data: + data.append(req.strip()) + + if data: + break + + return frozenset(data) + + def get_dist_requirements(self): + """ + Changed in version 2.1: The field format specification was relaxed to + accept the syntax used by popular publishing tools. + + Each entry contains a string naming some other distutils project + required by this distribution. + + The format of a requirement string contains from one to four parts: + - A project name, in the same format as the Name: field. The only + mandatory part. + - A comma-separated list of ‘extra’ names. These are defined by the + required project, referring to specific features which may need + extra dependencies. + - A version specifier. Tools parsing the format should accept + optional parentheses around this, but tools generating it should + not use parentheses. + - An environment marker after a semicolon. This means that the + requirement is only needed in the specified conditions. + + This field may be followed by an environment marker after a semicolon. + + Example + ------- + frozenset(['pkginfo', 'PasteDeploy', 'zope.interface (>3.5.0)', + 'pywin32 >1.0; sys_platform == "win32"']) + + Return 'Requires' if 'Requires-Dist' is empty. + """ + return self._get_multiple_data(["requires_dist", "requires"]) + + def get_python_requirements(self): + """ + New in version 1.2. + + This field specifies the Python version(s) that the distribution is + guaranteed to be compatible with. Installation tools may look at this + when picking which version of a project to install. + + The value must be in the format specified in Version specifiers. + + This field may be followed by an environment marker after a semicolon. + + Example + ------- + frozenset(['>=3', '>2.6,!=3.0.*,!=3.1.*', '~=2.6', + '>=3; sys_platform == "win32"']) + """ + return self._get_multiple_data(["requires_python"]) + + def get_external_requirements(self): + """ + Changed in version 2.1: The field format specification was relaxed to + accept the syntax used by popular publishing tools. + + Each entry contains a string describing some dependency in the system + that the distribution is to be used. This field is intended to serve + as a hint to downstream project maintainers, and has no semantics + which are meaningful to the distutils distribution. + + The format of a requirement string is a name of an external dependency, + optionally followed by a version declaration within parentheses. + + This field may be followed by an environment marker after a semicolon. + + Because they refer to non-Python software releases, version numbers for + this field are not required to conform to the format specified in PEP + 440: they should correspond to the version scheme used by the external + dependency. + + Notice that there’s is no particular rule on the strings to be used! + + Example + ------- + frozenset(['C', 'libpng (>=1.5)', 'make; sys_platform != "win32"']) + """ + return self._get_multiple_data(["requires_external"]) + + def get_extra_provides(self): + """ + New in version 2.1. + + A string containing the name of an optional feature. Must be a valid + Python identifier. May be used to make a dependency conditional on + hether the optional feature has been requested. + + Example + ------- + frozenset(['pdf', 'doc', 'test']) + """ + return self._get_multiple_data(["provides_extra"]) + + def get_dist_provides(self): + """ + New in version 1.2. + + Changed in version 2.1: The field format specification was relaxed to + accept the syntax used by popular publishing tools. + + Each entry contains a string naming a Distutils project which is + contained within this distribution. This field must include the project + identified in the Name field, followed by the version : Name (Version). + + A distribution may provide additional names, e.g. to indicate that + multiple projects have been bundled together. For instance, source + distributions of the ZODB project have historically included the + transaction project, which is now available as a separate distribution. + Installing such a source distribution satisfies requirements for both + ZODB and transaction. + + A distribution may also provide a “virtual” project name, which does + not correspond to any separately-distributed project: such a name might + be used to indicate an abstract capability which could be supplied by + one of multiple projects. E.g., multiple projects might supply RDBMS + bindings for use by a given ORM: each project might declare that it + provides ORM-bindings, allowing other projects to depend only on having + at most one of them installed. + + A version declaration may be supplied and must follow the rules + described in Version specifiers. The distribution’s version number + will be implied if none is specified. + + This field may be followed by an environment marker after a semicolon. + + Return `Provides` in case `Provides-Dist` is empty. + """ + return self._get_multiple_data(["provides_dist", "provides"]) + + def get_dist_obsolete(self): + """ + New in version 1.2. + + Changed in version 2.1: The field format specification was relaxed to + accept the syntax used by popular publishing tools. + + Each entry contains a string describing a distutils project’s + distribution which this distribution renders obsolete, meaning that + the two projects should not be installed at the same time. + + Version declarations can be supplied. Version numbers must be in the + format specified in Version specifiers [1]. + + The most common use of this field will be in case a project name + changes, e.g. Gorgon 2.3 gets subsumed into Torqued Python 1.0. When + you install Torqued Python, the Gorgon distribution should be removed. + + This field may be followed by an environment marker after a semicolon. + + Return `Obsoletes` in case `Obsoletes-Dist` is empty. + + Example + ------- + frozenset(['Gorgon', "OtherProject (<3.0) ; python_version == '2.7'"]) + + Notes + ----- + - [1] https://packaging.python.org/specifications/version-specifiers/ + """ + return self._get_multiple_data(["obsoletes_dist", "obsoletes"]) + + def get_classifiers(self): + """ + Classifiers are described in PEP 301, and the Python Package Index + publishes a dynamic list of currently defined classifiers. + + This field may be followed by an environment marker after a semicolon. + + Example + ------- + frozenset(['Development Status :: 4 - Beta', + "Environment :: Console (Text Based) ; os_name == "posix"]) + """ + return self._get_multiple_data(["classifier"]) + + @property + def name(self): + return self._data.get("name") # TODO: Check for existence? + + @property + def version(self): + return self._data.get("version") # TODO: Check for existence? + + +# Helper functions +# ----------------------------------------------------------------------------- +def norm_package_name(name): + return name.replace(".", "-").replace("_", "-").lower() if name else "" + + +def pypi_name_to_conda_name(pypi_name): + return PYPI_TO_CONDA.get(pypi_name, pypi_name) if pypi_name else "" + + +def norm_package_version(version): + """Normalize a version by removing extra spaces and parentheses.""" + if version: + version = ",".join(v.strip() for v in version.split(",")).strip() + + if version.startswith("(") and version.endswith(")"): + version = version[1:-1] + + version = "".join(v for v in version if v.strip()) + else: + version = "" + + return version + + +def split_spec(spec, sep): + """Split a spec by separator and return stripped start and end parts.""" + parts = spec.rsplit(sep, 1) + spec_start = parts[0].strip() + spec_end = "" + if len(parts) == 2: + spec_end = parts[-1].strip() + return spec_start, spec_end + + +def parse_specification(spec): + """ + Parse a requirement from a python distribution metadata and return a + namedtuple with name, extras, constraints, marker and url components. + + This method does not enforce strict specifications but extracts the + information which is assumed to be *correct*. As such no errors are raised. + + Example + ------- + PySpec(name='requests', extras=['security'], constraints='>=3.3.0', + marker='foo >= 2.7 or bar == 1', url='']) + """ + name, extras, const = spec, [], "" + + # Remove excess whitespace + spec = " ".join(p for p in spec.split(" ") if p).strip() + + # Extract marker (Assumes that there can only be one ';' inside the spec) + spec, marker = split_spec(spec, ";") + + # Extract url (Assumes that there can only be one '@' inside the spec) + spec, url = split_spec(spec, "@") + + # Find name, extras and constraints + r = PARTIAL_PYPI_SPEC_PATTERN.match(spec) + if r: + # Normalize name + name = r.group("name") + name = norm_package_name(name) # TODO: Do we want this or not? + + # Clean extras + extras = r.group("extras") + extras = [e.strip() for e in extras.split(",") if e] if extras else [] + + # Clean constraints + const = r.group("constraints") + const = "".join(c for c in const.split(" ") if c).strip() + if const.startswith("(") and const.endswith(")"): + # Remove parens + const = const[1:-1] + const = const.replace("-", ".") + + return PySpec(name=name, extras=extras, constraints=const, marker=marker, url=url) + + +def get_site_packages_anchor_files(site_packages_path, site_packages_dir): + """Get all the anchor files for the site packages directory.""" + site_packages_anchor_files = set() + for entry in scandir(site_packages_path): + fname = entry.name + anchor_file = None + if fname.endswith(".dist-info"): + anchor_file = "{}/{}/{}".format(site_packages_dir, fname, "RECORD") + elif fname.endswith(".egg-info"): + if isfile(join(site_packages_path, fname)): + anchor_file = f"{site_packages_dir}/{fname}" + else: + anchor_file = "{}/{}/{}".format(site_packages_dir, fname, "PKG-INFO") + elif fname.endswith(".egg"): + if isdir(join(site_packages_path, fname)): + anchor_file = "{}/{}/{}/{}".format( + site_packages_dir, fname, "EGG-INFO", "PKG-INFO" + ) + # FIXME: If it is a .egg file, we need to unzip the content to be + # able. Do this once and leave the directory, and remove the egg + # (which is a zip file in disguise?) + elif fname.endswith(".egg-link"): + anchor_file = f"{site_packages_dir}/{fname}" + elif fname.endswith(".pth"): + continue + else: + continue + + if anchor_file: + site_packages_anchor_files.add(anchor_file) + + return site_packages_anchor_files + + +def get_dist_file_from_egg_link(egg_link_file, prefix_path): + """Return the egg info file path following an egg link.""" + egg_info_full_path = None + + egg_link_path = join(prefix_path, win_path_ok(egg_link_file)) + try: + with open_utf8(egg_link_path) as fh: + # See: https://setuptools.readthedocs.io/en/latest/formats.html#egg-links + # "...Each egg-link file should contain a single file or directory name + # with no newlines..." + egg_link_contents = fh.readlines()[0].strip() + except UnicodeDecodeError: + from locale import getpreferredencoding + + with open_utf8(egg_link_path, encoding=getpreferredencoding()) as fh: + egg_link_contents = fh.readlines()[0].strip() + + if lexists(egg_link_contents): + egg_info_fnames = tuple( + name + for name in (entry.name for entry in scandir(egg_link_contents)) + if name[-9:] == ".egg-info" + ) + else: + egg_info_fnames = () + + if egg_info_fnames: + if len(egg_info_fnames) != 1: + raise CondaError( + f"Expected exactly one `egg-info` directory in '{egg_link_contents}', via egg-link '{egg_link_file}'." + f" Instead found: {egg_info_fnames}. These are often left over from " + "legacy operations that did not clean up correctly. Please " + "remove all but one of these." + ) + + egg_info_full_path = join(egg_link_contents, egg_info_fnames[0]) + + if isdir(egg_info_full_path): + egg_info_full_path = join(egg_info_full_path, "PKG-INFO") + + if egg_info_full_path is None: + raise OSError(ENOENT, strerror(ENOENT), egg_link_contents) + + return egg_info_full_path + + +# See: https://bitbucket.org/pypa/distlib/src/34629e41cdff5c29429c7a4d1569ef5508b56929/distlib/util.py?at=default&fileviewer=file-view-default +# ------------------------------------------------------------------------------------------------ +def parse_marker(marker_string): + """ + Parse marker string and return a dictionary containing a marker expression. + + The dictionary will contain keys "op", "lhs" and "rhs" for non-terminals in + the expression grammar, or strings. A string contained in quotes is to be + interpreted as a literal string, and a string not contained in quotes is a + variable (such as os_name). + """ + + def marker_var(remaining): + # either identifier, or literal string + m = IDENTIFIER.match(remaining) + if m: + result = m.groups()[0] + remaining = remaining[m.end() :] + elif not remaining: + raise SyntaxError("unexpected end of input") + else: + q = remaining[0] + if q not in "'\"": + raise SyntaxError(f"invalid expression: {remaining}") + oq = "'\"".replace(q, "") + remaining = remaining[1:] + parts = [q] + while remaining: + # either a string chunk, or oq, or q to terminate + if remaining[0] == q: + break + elif remaining[0] == oq: + parts.append(oq) + remaining = remaining[1:] + else: + m = STRING_CHUNK.match(remaining) + if not m: + raise SyntaxError(f"error in string literal: {remaining}") + parts.append(m.groups()[0]) + remaining = remaining[m.end() :] + else: + s = "".join(parts) + raise SyntaxError(f"unterminated string: {s}") + parts.append(q) + result = "".join(parts) + remaining = remaining[1:].lstrip() # skip past closing quote + return result, remaining + + def marker_expr(remaining): + if remaining and remaining[0] == "(": + result, remaining = marker(remaining[1:].lstrip()) + if remaining[0] != ")": + raise SyntaxError(f"unterminated parenthesis: {remaining}") + remaining = remaining[1:].lstrip() + else: + lhs, remaining = marker_var(remaining) + while remaining: + m = MARKER_OP.match(remaining) + if not m: + break + op = m.groups()[0] + remaining = remaining[m.end() :] + rhs, remaining = marker_var(remaining) + lhs = {"op": op, "lhs": lhs, "rhs": rhs} + result = lhs + return result, remaining + + def marker_and(remaining): + lhs, remaining = marker_expr(remaining) + while remaining: + m = AND.match(remaining) + if not m: + break + remaining = remaining[m.end() :] + rhs, remaining = marker_expr(remaining) + lhs = {"op": "and", "lhs": lhs, "rhs": rhs} + return lhs, remaining + + def marker(remaining): + lhs, remaining = marker_and(remaining) + while remaining: + m = OR.match(remaining) + if not m: + break + remaining = remaining[m.end() :] + rhs, remaining = marker_and(remaining) + lhs = {"op": "or", "lhs": lhs, "rhs": rhs} + return lhs, remaining + + return marker(marker_string) + + +# See: +# https://bitbucket.org/pypa/distlib/src/34629e41cdff5c29429c7a4d1569ef5508b56929/distlib/util.py?at=default&fileviewer=file-view-default +# https://bitbucket.org/pypa/distlib/src/34629e41cdff5c29429c7a4d1569ef5508b56929/distlib/markers.py?at=default&fileviewer=file-view-default +# ------------------------------------------------------------------------------------------------ +# +# Requirement parsing code as per PEP 508 +# +IDENTIFIER = re.compile(r"^([\w\.-]+)\s*") +VERSION_IDENTIFIER = re.compile(r"^([\w\.*+-]+)\s*") +COMPARE_OP = re.compile(r"^(<=?|>=?|={2,3}|[~!]=)\s*") +MARKER_OP = re.compile(r"^((<=?)|(>=?)|={2,3}|[~!]=|in|not\s+in)\s*") +OR = re.compile(r"^or\b\s*") +AND = re.compile(r"^and\b\s*") +NON_SPACE = re.compile(r"(\S+)\s*") +STRING_CHUNK = re.compile(r"([\s\w\.{}()*+#:;,/?!~`@$%^&=|<>\[\]-]+)") + + +def _is_literal(o): + if not isinstance(o, str) or not o: + return False + return o[0] in "'\"" + + +class Evaluator: + """This class is used to evaluate marker expressions.""" + + operations = { + "==": lambda x, y: x == y, + "===": lambda x, y: x == y, + "~=": lambda x, y: x == y or x > y, + "!=": lambda x, y: x != y, + "<": lambda x, y: x < y, + "<=": lambda x, y: x == y or x < y, + ">": lambda x, y: x > y, + ">=": lambda x, y: x == y or x > y, + "and": lambda x, y: x and y, + "or": lambda x, y: x or y, + "in": lambda x, y: x in y, + "not in": lambda x, y: x not in y, + } + + def evaluate(self, expr, context): + """ + Evaluate a marker expression returned by the :func:`parse_requirement` + function in the specified context. + """ + if isinstance(expr, str): + if expr[0] in "'\"": + result = expr[1:-1] + else: + if expr not in context: + raise SyntaxError(f"unknown variable: {expr}") + result = context[expr] + else: + if not isinstance(expr, dict): + raise TypeError("'expr' must be a dict.") + op = expr["op"] + if op not in self.operations: + raise NotImplementedError(f"op not implemented: {op}") + elhs = expr["lhs"] + erhs = expr["rhs"] + if _is_literal(expr["lhs"]) and _is_literal(expr["rhs"]): + raise SyntaxError(f"invalid comparison: {elhs} {op} {erhs}") + + lhs = self.evaluate(elhs, context) + rhs = self.evaluate(erhs, context) + result = self.operations[op](lhs, rhs) + return result + + +# def update_marker_context(python_version): +# """Update default marker context to include environment python version.""" +# updated_context = DEFAULT_MARKER_CONTEXT.copy() +# context = { +# 'python_full_version': python_version, +# 'python_version': '.'.join(python_version.split('.')[:2]), +# 'extra': '', +# } +# updated_context.update(context) +# return updated_context + + +def get_default_marker_context(): + """Return the default context dictionary to use when parsing markers.""" + + def format_full_version(info): + version = f"{info.major}.{info.minor}.{info.micro}" + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + if hasattr(sys, "implementation"): + implementation_version = format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + else: + implementation_version = "0" + implementation_name = "" + + # TODO: we can't use this + result = { + # See: https://www.python.org/dev/peps/pep-0508/#environment-markers + "implementation_name": implementation_name, + "implementation_version": implementation_version, + "os_name": os_name, + "platform_machine": platform.machine(), + "platform_python_implementation": platform.python_implementation(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "python_version": ".".join(platform.python_version().split(".")[:2]), + "sys_platform": sys.platform, + # See: https://www.python.org/dev/peps/pep-0345/#environment-markers + "os.name": os_name, + "platform.python_implementation": platform.python_implementation(), + "platform.version": platform.version(), + "platform.machine": platform.machine(), + "sys.platform": sys.platform, + "extra": "", + } + return result + + +DEFAULT_MARKER_CONTEXT = get_default_marker_context() +evaluator = Evaluator() + + +# FIXME: Should this raise errors, or fail silently or with a warning? +def interpret(marker, execution_context=None): + """ + Interpret a marker and return a result depending on environment. + + :param marker: The marker to interpret. + :type marker: str + :param execution_context: The context used for name lookup. + :type execution_context: mapping + """ + try: + expr, rest = parse_marker(marker) + except Exception as e: + raise SyntaxError(f"Unable to interpret marker syntax: {marker}: {e}") + + if rest and rest[0] != "#": + raise SyntaxError(f"unexpected trailing data in marker: {marker}: {rest}") + + context = DEFAULT_MARKER_CONTEXT.copy() + if execution_context: + context.update(execution_context) + + return evaluator.evaluate(expr, context) + + +def read_python_record(prefix_path, anchor_file, python_version): + """ + Convert a python package defined by an anchor file (Metadata information) + into a conda prefix record object. + """ + pydist = PythonDistribution.init(prefix_path, anchor_file, python_version) + depends, constrains = pydist.get_conda_dependencies() + + if isinstance(pydist, PythonInstalledDistribution): + channel = Channel("pypi") + build = "pypi_0" + package_type = PackageType.VIRTUAL_PYTHON_WHEEL + + paths_tups = pydist.get_paths() + paths_data = PathsData( + paths_version=1, + paths=( + PathDataV1( + _path=path, + path_type=PathEnum.hardlink, + sha256=checksum, + size_in_bytes=size, + ) + for (path, checksum, size) in paths_tups + ), + ) + files = tuple(p[0] for p in paths_tups) + + elif isinstance(pydist, PythonEggLinkDistribution): + channel = Channel("") + build = "dev_0" + package_type = PackageType.VIRTUAL_PYTHON_EGG_LINK + + paths_data, files = PathsData(paths_version=1, paths=()), () + + elif isinstance(pydist, PythonEggInfoDistribution): + channel = Channel("pypi") + build = "pypi_0" + if pydist.is_manageable: + package_type = PackageType.VIRTUAL_PYTHON_EGG_MANAGEABLE + + paths_tups = pydist.get_paths() + files = tuple(p[0] for p in paths_tups) + paths_data = PathsData( + paths_version=1, + paths=( + PathDataV1(_path=path, path_type=PathEnum.hardlink) + for path in files + ), + ) + else: + package_type = PackageType.VIRTUAL_PYTHON_EGG_UNMANAGEABLE + paths_data, files = PathsData(paths_version=1, paths=()), () + + else: + raise NotImplementedError() + + return PrefixRecord( + package_type=package_type, + name=pydist.norm_name, + version=pydist.version, + channel=channel, + subdir="pypi", + fn=pydist.sp_reference, + build=build, + build_number=0, + paths_data=paths_data, + files=files, + depends=depends, + constrains=constrains, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d890f55343640de051d7521c68efd224f2fcf1cc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/__init__.py @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from . import console, json + +plugins = [json, console] diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/console.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/console.py new file mode 100644 index 0000000000000000000000000000000000000000..002efafad1ca1178714ed8a9b9635e88538f22bb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/console.py @@ -0,0 +1,305 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Defines a "console" reporter backend. + +This reporter backend provides the default output for conda. +""" + +from __future__ import annotations + +import sys +from errno import EPIPE, ESHUTDOWN +from itertools import cycle +from threading import Event, Thread +from time import sleep +from typing import TYPE_CHECKING + +from ...base.constants import ( + DEFAULT_CONSOLE_REPORTER_BACKEND, +) +from ...base.context import context +from ...common.io import swallow_broken_pipe +from ...common.path import paths_equal +from ...core.prefix_data import PrefixData +from ...exceptions import CondaError +from ...utils import human_bytes +from .. import hookimpl +from ..types import ( + CondaReporterBackend, + ProgressBarBase, + ReporterRendererBase, + SpinnerBase, +) + +if TYPE_CHECKING: + from collections.abc import Iterable + + from ...common.path import PathType + + +class QuietProgressBar(ProgressBarBase): + """ + Progress bar class used when no output should be printed + """ + + def update_to(self, fraction) -> None: + pass + + def refresh(self) -> None: + pass + + def close(self) -> None: + pass + + +class TQDMProgressBar(ProgressBarBase): + """ + Progress bar class used for tqdm progress bars + """ + + def __init__( + self, + description: str, + position=None, + leave=True, + **kwargs, + ) -> None: + super().__init__(description) + + self.enabled = True + + bar_format = "{desc}{bar} | {percentage:3.0f}% " + + try: + self.pbar = self._tqdm( + desc=description, + bar_format=bar_format, + ascii=True, + total=1, + file=sys.stdout, + position=position, + leave=leave, + ) + except OSError as e: + if e.errno in (EPIPE, ESHUTDOWN): + self.enabled = False + else: + raise + + def update_to(self, fraction) -> None: + try: + if self.enabled: + self.pbar.update(fraction - self.pbar.n) + except OSError as e: + if e.errno in (EPIPE, ESHUTDOWN): + self.enabled = False + else: + raise + + @swallow_broken_pipe + def close(self) -> None: + if self.enabled: + self.pbar.close() + + def refresh(self) -> None: + if self.enabled: + self.pbar.refresh() + + @staticmethod + def _tqdm(*args, **kwargs): + """Deferred import so it doesn't hit the `conda activate` paths.""" + from tqdm.auto import tqdm + + return tqdm(*args, **kwargs) + + +class Spinner(SpinnerBase): + spinner_cycle = cycle("/-\\|") + + def __init__(self, message, fail_message="failed\n"): + super().__init__(message, fail_message) + + self.show_spin: bool = True + self._stop_running = Event() + self._spinner_thread = Thread(target=self._start_spinning) + self._indicator_length = len(next(self.spinner_cycle)) + 1 + self.fh = sys.stdout + + def start(self): + self._spinner_thread.start() + + def stop(self): + self._stop_running.set() + self._spinner_thread.join() + self.show_spin = False + + def _start_spinning(self): + try: + while not self._stop_running.is_set(): + self.fh.write(next(self.spinner_cycle) + " ") + self.fh.flush() + sleep(0.10) + self.fh.write("\b" * self._indicator_length) + except OSError as e: + if e.errno in (EPIPE, ESHUTDOWN): + self.stop() + else: + raise + + @swallow_broken_pipe + def __enter__(self): + sys.stdout.write(f"{self.message}: ") + sys.stdout.flush() + self.start() + + def __exit__(self, exc_type, exc_val, exc_tb): + self.stop() + with swallow_broken_pipe: + if exc_type or exc_val: + sys.stdout.write(self.fail_message) + else: + sys.stdout.write("done\n") + sys.stdout.flush() + + +class QuietSpinner(SpinnerBase): + def __enter__(self): + sys.stdout.write(f"{self.message}: ") + sys.stdout.flush() + + sys.stdout.write("...working... ") + sys.stdout.flush() + + def __exit__(self, exc_type, exc_val, exc_tb): + with swallow_broken_pipe: + if exc_type or exc_val: + sys.stdout.write(self.fail_message) + else: + sys.stdout.write("done\n") + sys.stdout.flush() + + +class ConsoleReporterRenderer(ReporterRendererBase): + """ + Default implementation for console reporting in conda + """ + + def detail_view(self, data: dict[str, str | int | bool], **kwargs) -> str: + table_parts = [""] + longest_header = max(map(len, data.keys())) + + for header, value in data.items(): + table_parts.append(f" {header:>{longest_header}} : {value}") + + table_parts.append("\n") + + return "\n".join(table_parts) + + @staticmethod + def envs_list( + prefixes: Iterable[PathType | PrefixData], output=True, **kwargs + ) -> str: + if not output: + return "" + + show_size = kwargs.get("show_size", False) + + output = [ + "", + "# conda environments:", + "#", + "# * -> active", + "# + -> frozen", + ] + + def disp_env(prefix: PrefixData) -> str: + active = ( + "*" + if context.active_prefix + and paths_equal(prefix.prefix_path, context.active_prefix) + else " " + ) + frozen = "+" if prefix.is_frozen() else " " + if show_size: + size_str = human_bytes(prefix.size()) + return f"{prefix.name:20} {active} {frozen} {size_str:>10} {prefix.prefix_path}" + else: + return f"{prefix.name:20} {active} {frozen} {prefix.prefix_path}" + + for env_prefix in prefixes: + if not isinstance(env_prefix, PrefixData): + env_prefix = PrefixData(env_prefix) + output.append(disp_env(env_prefix)) + + output.append("\n") + + return "\n".join(output) + + def progress_bar( + self, + description: str, + **kwargs, + ) -> ProgressBarBase: + """ + Determines whether to return a TQDMProgressBar or QuietProgressBar + """ + if context.quiet: + return QuietProgressBar(description, **kwargs) + else: + return TQDMProgressBar(description, **kwargs) + + def spinner(self, message: str, fail_message: str = "failed\n") -> SpinnerBase: + """ + Determines whether to return a Spinner or QuietSpinner + """ + if context.quiet: + return QuietSpinner(message, fail_message) + else: + return Spinner(message, fail_message) + + def prompt(self, message="Proceed", choices=("yes", "no"), default="yes") -> str: + """ + Implementation of a prompt dialog + """ + if default not in choices: + raise ValueError(f"Default value '{default}' must be part of `choices`") + options = [] + + for option in choices: + if option == default: + options.append(f"[{option[0]}]") + else: + options.append(option[0]) + + message = "{} ({})? ".format(message, "/".join(options)) + choices = {alt: choice for choice in choices for alt in [choice, choice[0]]} + choices[""] = default + while True: + # raw_input has a bug and prints to stderr, not desirable + sys.stdout.write(message) + sys.stdout.flush() + try: + user_choice = sys.stdin.readline().strip().lower() + except OSError as e: + raise CondaError(f"cannot read from stdin: {e}") + if user_choice not in choices: + print(f"Invalid choice: {user_choice}") + else: + sys.stdout.write("\n") + sys.stdout.flush() + return choices[user_choice] + + +@hookimpl( + tryfirst=True +) # make sure the default console reporter backend can't be overridden +def conda_reporter_backends(): + """ + Reporter backend for console + """ + yield CondaReporterBackend( + name=DEFAULT_CONSOLE_REPORTER_BACKEND, + description="Default implementation for console reporting in conda", + renderer=ConsoleReporterRenderer, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/json.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/json.py new file mode 100644 index 0000000000000000000000000000000000000000..7cba1f83778ccfa9393214a23a897f8e1217c93d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/reporter_backends/json.py @@ -0,0 +1,135 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Defines a JSON reporter backend + +This reporter backend is used to provide JSON strings for output rendering. It is +essentially just a wrapper around ``conda.common.serialize.json.dumps``. +""" + +from __future__ import annotations + +import sys +from threading import RLock +from typing import TYPE_CHECKING + +from ...base.constants import DEFAULT_JSON_REPORTER_BACKEND +from ...common.io import swallow_broken_pipe +from ...common.serialize import json +from .. import hookimpl +from ..types import ( + CondaReporterBackend, + ProgressBarBase, + ReporterRendererBase, + SpinnerBase, +) + +if TYPE_CHECKING: + from typing import Any + + +class JSONProgressBar(ProgressBarBase): + """ + Progress bar that outputs JSON to stdout + """ + + def __init__( + self, + description: str, + enabled: bool = True, + **kwargs, + ): + super().__init__(description) + self.enabled = enabled + + def update_to(self, fraction) -> None: + with self.get_lock(): + if self.enabled: + sys.stdout.write( + f'{{"fetch":"{self.description}","finished":false,"maxval":1,"progress":{fraction:f}}}\n\0' + ) + + def refresh(self): + pass + + @swallow_broken_pipe + def close(self): + with self.get_lock(): + if self.enabled: + sys.stdout.write( + f'{{"fetch":"{self.description}","finished":true,"maxval":1,"progress":1}}\n\0' + ) + sys.stdout.flush() + + @classmethod + def get_lock(cls): + """ + Used for our own sys.stdout.write/flush calls + """ + if not hasattr(cls, "_lock"): + cls._lock = RLock() + return cls._lock + + +class JSONReporterRenderer(ReporterRendererBase): + """ + Default implementation for JSON reporting in conda + """ + + def render(self, data: Any, **kwargs) -> str: + return json.dumps(data) + + def detail_view(self, data: dict[str, str | int | bool], **kwargs) -> str: + return json.dumps(data) + + def envs_list( + self, data: list[str] | dict[str, dict[str, str | bool | None]], **kwargs + ) -> str: + if isinstance(data, (list, tuple)): + return json.dumps({"envs": data}) + return json.dumps(data) + + def progress_bar( + self, + description: str, + **kwargs, + ) -> ProgressBarBase: + return JSONProgressBar(description, **kwargs) + + def spinner(self, message: str, fail_message: str = "failed\n") -> SpinnerBase: + return JSONSpinner(message, fail_message) + + def prompt( + self, message: str = "Proceed", choices=("yes", "no"), default: str = "yes" + ) -> str: + """ + For this class, we want this method to do nothing + """ + + +class JSONSpinner(SpinnerBase): + """ + This class for a JSONSpinner does nothing because we do not want to include this output. + """ + + def __enter__(self): + pass + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + + +@hookimpl( + tryfirst=True +) # make sure the default json reporter backend can't be overridden +def conda_reporter_backends(): + """ + Reporter backend for JSON + + This is the default reporter backend that returns objects as JSON strings. + """ + yield CondaReporterBackend( + name=DEFAULT_JSON_REPORTER_BACKEND, + description="Default implementation for JSON reporting in conda", + renderer=JSONReporterRenderer, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/solvers.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..abdb0f548d379955c4432bf6ec15b7914547fb97 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/solvers.py @@ -0,0 +1,18 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Register the classic conda solver.""" + +from ..base.constants import CLASSIC_SOLVER +from . import hookimpl +from .types import CondaSolver + + +@hookimpl(tryfirst=True) # make sure the classic solver can't be overwritten +def conda_solvers(): + """The classic solver as shipped by default in conda.""" + from ..core.solve import Solver + + yield CondaSolver( + name=CLASSIC_SOLVER, + backend=Solver, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f195138e5d12bc0f06dfc2f60e484bca4e53bc77 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/__init__.py @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from . import doctor + +plugins = [doctor] diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e71dfcbb5c66cf0388a847560a135d132d60587 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__init__.py @@ -0,0 +1,140 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Implementation for `conda doctor` subcommand. +Adds various environment and package checks to detect issues or possible environment +corruption. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from ....base.context import context +from ....cli.helpers import ( + add_output_and_prompt_options, + add_parser_help, + add_parser_prefix, +) +from ....core.prefix_data import PrefixData +from ....exceptions import CondaSystemExit, DryRunExit +from ....reporters import confirm_yn +from ... import hookimpl +from ...types import CondaSubcommand + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace + +log = logging.getLogger(__name__) + + +def configure_parser(parser: ArgumentParser): + add_parser_help(parser) + add_parser_prefix(parser) + add_output_and_prompt_options(parser) # includes --verbose, --dry-run, --yes + parser.add_argument( + "checks", + nargs="*", + metavar="NAME", + help="Health check names to run (default: all). Use --list to see available checks.", + ) + parser.add_argument( + "--list", + action="store_true", + help="List all available health checks and their fix capabilities.", + ) + parser.add_argument( + "--fix", + "--heal", # easter egg 🩺 + action="store_true", + help="Fix issues found by health checks.", + ) + + +def execute(args: Namespace) -> int: + """Run registered health_check plugins and optionally fix issues.""" + # Handle --list first (doesn't require environment) + if getattr(args, "list", False): + checks = context.plugin_manager.get_health_checks() + if not checks: + print("No health checks are available.") + return 0 + + print("Available health checks:\n") + for name, check in sorted(checks.items()): + summary = check.summary or name + if check.fixer: + fix = check.fix or "Fix available" + print(f" {name}: {summary} (fix: {fix})") + else: + print(f" {name}: {summary}") + print() + return 0 + + prefix_data = PrefixData.from_context() + prefix_data.assert_environment() + prefix = str(prefix_data.prefix_path) + + # Get and filter health checks by name + checks = context.plugin_manager.get_health_checks() + check_names = args.checks if args.checks else None + if check_names: + unknown = set(check_names) - set(checks.keys()) + if unknown: + log.warning(f"Unknown health check(s): {', '.join(sorted(unknown))}") + checks = {n: c for n, c in checks.items() if n in check_names} + + # Run health checks + print(f"Environment Health Report for: {prefix}\n") + for name, check in checks.items(): + try: + check.action(prefix, context.verbose) + except Exception as err: + log.warning(f"Error running health check: {name} ({err})") + + # If --fix was provided, run fixes + if getattr(args, "fix", False): + print("\n" + "=" * 60) + print("Running fixes...") + print("=" * 60 + "\n") + + fixable = {n: c for n, c in checks.items() if c.fixer} + if not fixable: + print("No health checks with fix capability are available.") + return 0 + + exit_code = 0 + confirm = lambda msg: confirm_yn(msg, default="no", dry_run=context.dry_run) + for name, check in fixable.items(): + try: + result = check.fixer(prefix, args, confirm) + if result != 0: + exit_code = result + except DryRunExit as exc: + # Dry-run mode: print the message and continue to next fixer + log.warning(str(exc)) + except CondaSystemExit: + # User cancelled the fix + pass + except Exception as err: + log.warning(f"Error running fix: {name} ({err})") + exit_code = 1 + return exit_code + + return 0 + + +@hookimpl +def conda_subcommands(): + yield CondaSubcommand( + name="doctor", + summary="Display a health report for your environment.", + action=execute, + configure_parser=configure_parser, + ) + yield CondaSubcommand( + name="check", + summary="Display a health report for your environment (alias for doctor).", + action=execute, + configure_parser=configure_parser, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ea57361784a2810bf95307a8dcc6bce35c6ec13 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/__init__.py @@ -0,0 +1,32 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health checks for `conda doctor`. + +This package contains individual health check modules that are registered +via the conda_health_checks plugin hook. +""" + +from __future__ import annotations + +from . import ( + altered_files, + consistency, + environment_txt, + file_locking, + missing_files, + pinned, + requests_ca_bundle, +) + +# The list of health check plugins for easier registration with pluggy +plugins = [ + altered_files, + consistency, + environment_txt, + file_locking, + missing_files, + pinned, + requests_ca_bundle, +] + +__all__ = ["plugins"] diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/altered_files.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/altered_files.py new file mode 100644 index 0000000000000000000000000000000000000000..8b900445dc01ebe5dd4d1ceb3759e4193f30f69f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/altered_files.py @@ -0,0 +1,123 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health check: Altered files in packages.""" + +from __future__ import annotations + +from logging import getLogger +from pathlib import Path +from typing import TYPE_CHECKING + +from .....base.constants import OK_MARK, X_MARK +from .....cli.install import reinstall_packages +from .....common.serialize import json +from .....exceptions import CondaError +from .....gateways.disk.read import compute_sum +from .... import hookimpl +from ....types import CondaHealthCheck +from .missing_files import excluded_files_check + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Iterable + + from ....types import ConfirmCallback + + +logger = getLogger(__name__) + + +def find_altered_packages(prefix: str | Path) -> dict[str, list[str]]: + """Finds packages with altered files (checksum mismatch).""" + altered_packages = {} + prefix = Path(prefix) + + for file in (prefix / "conda-meta").glob("*.json"): + try: + metadata = json.loads(file.read_text()) + except Exception as exc: + logger.error( + f"Could not load the json file {file} because of the following error: {exc}." + ) + continue + + try: + paths_data = metadata["paths_data"] + paths = paths_data["paths"] + except KeyError: + continue + + if paths_data.get("paths_version") != 1: + continue + + for path in paths: + _path = path.get("_path") + if excluded_files_check(_path): + continue + + old_sha256 = path.get("sha256_in_prefix") + if _path is None or old_sha256 is None: + continue + + file_location = prefix / _path + if not file_location.is_file(): + continue + + try: + new_sha256 = compute_sum(file_location, "sha256") + except OSError as err: + raise CondaError( + f"Could not generate checksum for file {file_location} " + f"because of the following error: {err}." + ) + + if old_sha256 != new_sha256: + altered_packages.setdefault(file.stem, []).append(_path) + + return altered_packages + + +def altered_files(prefix: str, verbose: bool) -> None: + """Health check action: Report packages with altered files.""" + altered = find_altered_packages(prefix) + if altered: + print(f"{X_MARK} Altered Files:\n") + for package_name, files in altered.items(): + if verbose: + delimiter = "\n " + print(f"{package_name}:{delimiter}{delimiter.join(files)}\n") + else: + print(f"{package_name}: {len(files)}\n") + else: + print(f"{OK_MARK} There are no packages with altered files.\n") + + +def fix_altered_files(prefix: str, args: Namespace, confirm: ConfirmCallback) -> int: + """Fix altered files by reinstalling affected packages.""" + altered = find_altered_packages(prefix) + + if not altered: + print("No packages with altered files found.") + return 0 + + print(f"Found {len(altered)} package(s) with altered files:") + for pkg_name, files in sorted(altered.items()): + print(f" {pkg_name}: {len(files)} altered file(s)") + + print() + confirm("Reinstall these packages to restore original files?") + + specs = list(altered.keys()) + return reinstall_packages(args, specs, force_reinstall=True) + + +@hookimpl +def conda_health_checks() -> Iterable[CondaHealthCheck]: + """Register the altered files health check.""" + yield CondaHealthCheck( + name="altered-files", + action=altered_files, + fixer=fix_altered_files, + summary="Detect packages with modified files", + fix="Reinstall affected packages", + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/consistency.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/consistency.py new file mode 100644 index 0000000000000000000000000000000000000000..43552e390aeb26cd00e5213272e86ffd059f4314 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/consistency.py @@ -0,0 +1,135 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health check: Environment consistency (dependencies).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .....base.constants import OK_MARK, X_MARK +from .....base.context import context +from .....cli.install import reinstall_packages +from .....common.serialize import yaml +from .....core.prefix_data import PrefixData +from .....models.match_spec import MatchSpec +from .... import hookimpl +from ....types import CondaHealthCheck + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Iterable + + from ....types import ConfirmCallback + + +def find_inconsistent_packages( + prefix_data: PrefixData, +) -> tuple[dict[str, dict[str, list]], set[str]]: + """Find packages with missing or inconsistent dependencies. + + Returns a tuple of (issues dict, missing dependency names set). + The issues dict maps package name -> {"missing": [...], "inconsistent": [...]}. + """ + pm = context.plugin_manager + virtual_packages = { + record.name: record for record in pm.get_virtual_package_records() + } + + issues = {} + missing_deps = set() + + for record in prefix_data.iter_records(): + for dependency in record.depends: + match_spec = MatchSpec(dependency) + dep_record = prefix_data.get( + match_spec.name, default=virtual_packages.get(match_spec.name) + ) + if dep_record is None: + issues.setdefault(record.name, {}).setdefault("missing", []).append( + str(match_spec) + ) + missing_deps.add(match_spec.name) + elif not match_spec.match(dep_record): + issues.setdefault(record.name, {}).setdefault( + "inconsistent", [] + ).append({"expected": str(match_spec), "installed": str(dep_record)}) + + for constrain in record.constrains: + package_found = prefix_data.get( + MatchSpec(constrain).name, + default=virtual_packages.get(MatchSpec(constrain).name), + ) + if package_found is not None and not MatchSpec(constrain).match( + package_found + ): + issues.setdefault(record.name, {}).setdefault( + "inconsistent", [] + ).append( + { + "expected": str(MatchSpec(constrain)), + "installed": f"{package_found.name}[version='{package_found.version}']", + } + ) + + return issues, missing_deps + + +def consistent_env_check(prefix: str, verbose: bool) -> None: + """Health check action: Check environment consistency.""" + pd = PrefixData(prefix) + issues, _ = find_inconsistent_packages(pd) + + if issues: + print(f"{X_MARK} The environment is not consistent.\n") + if verbose: + print(yaml.dumps(issues)) + else: + print(f"{OK_MARK} The environment is consistent.\n") + + +def fix_inconsistent_packages( + prefix: str, args: Namespace, confirm: ConfirmCallback +) -> int: + """Fix inconsistent packages by updating the environment.""" + prefix_data = PrefixData(prefix) + issues, missing_deps = find_inconsistent_packages(prefix_data) + + if not issues: + print("No inconsistent packages found.") + return 0 + + print(f"Found {len(issues)} package(s) with dependency issues:") + for pkg_name, pkg_issues in sorted(issues.items()): + missing = pkg_issues.get("missing", []) + inconsistent = pkg_issues.get("inconsistent", []) + print(f" {pkg_name}:", end="") + if missing: + print(f" {len(missing)} missing", end="") + if inconsistent: + print(f" {len(inconsistent)} inconsistent", end="") + print() + + print() + confirm("Attempt to resolve these dependency issues?") + + # Install missing dependencies and update inconsistent ones + specs = list(missing_deps) if missing_deps else [] + + # Also add packages with inconsistent deps to trigger solver + for pkg_name in issues: + if pkg_name not in specs: + specs.append(pkg_name) + + return reinstall_packages(args, specs, update_deps=True) + + +@hookimpl +def conda_health_checks() -> Iterable[CondaHealthCheck]: + """Register the consistency health check.""" + yield CondaHealthCheck( + name="consistency", + action=consistent_env_check, + fixer=fix_inconsistent_packages, + summary="Check for missing or inconsistent dependencies", + fix="Install missing dependencies", + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/environment_txt.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/environment_txt.py new file mode 100644 index 0000000000000000000000000000000000000000..560c89eaff376488ccc3095000fcd7ef2faa5264 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/environment_txt.py @@ -0,0 +1,85 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health check: Environment listed in environments.txt.""" + +from __future__ import annotations + +from logging import getLogger +from pathlib import Path +from typing import TYPE_CHECKING + +from .....base.constants import OK_MARK, X_MARK +from .....core.envs_manager import get_user_environments_txt_file, register_env +from .... import hookimpl +from ....types import CondaHealthCheck + +if TYPE_CHECKING: + import os + from argparse import Namespace + from collections.abc import Iterable + + from ....types import ConfirmCallback + +logger = getLogger(__name__) + + +def check_envs_txt_file(prefix: str | os.PathLike | Path) -> bool: + """Checks whether the environment is listed in the environments.txt file.""" + prefix = Path(prefix) + envs_txt_file = Path(get_user_environments_txt_file()) + + def samefile(path1: Path, path2: Path) -> bool: + try: + return path1.samefile(path2) + except FileNotFoundError: + return path1 == path2 + + try: + for line in envs_txt_file.read_text().splitlines(): + stripped_line = line.strip() + if stripped_line and samefile(prefix, Path(stripped_line)): + return True + except (IsADirectoryError, FileNotFoundError, PermissionError) as err: + logger.error( + f"{envs_txt_file} could not be " + f"accessed because of the following error: {err}" + ) + return False + + +def env_txt_check(prefix: str, verbose: bool) -> None: + """Health check action: Check if environment is in environments.txt.""" + if check_envs_txt_file(prefix): + print(f"{OK_MARK} The environment is listed in the environments.txt file.\n") + else: + print(f"{X_MARK} The environment is not listed in the environments.txt file.\n") + + +def fix_env_txt(prefix: str, args: Namespace, confirm: ConfirmCallback) -> int: + """Register environment in environments.txt.""" + if check_envs_txt_file(prefix): + print(f"Environment is already registered in environments.txt: {prefix}") + return 0 + + envs_txt = get_user_environments_txt_file() + print(f"Environment not found in {envs_txt}") + print(f" Environment: {prefix}") + + print() + confirm("Register this environment?") + + register_env(prefix) + print(f"Environment registered: {prefix}") + return 0 + + +@hookimpl +def conda_health_checks() -> Iterable[CondaHealthCheck]: + """Register the environment.txt health check.""" + yield CondaHealthCheck( + name="environment-txt", + action=env_txt_check, + fixer=fix_env_txt, + summary="Verify environment is registered in environments.txt", + fix="Add environment to environments.txt", + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/file_locking.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/file_locking.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf27c87bbb8b9479edc774823dcc88e2bd3be87 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/file_locking.py @@ -0,0 +1,39 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health check: File locking support.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .....base.constants import OK_MARK, X_MARK +from .....base.context import context +from .....gateways.disk.lock import locking_supported +from .... import hookimpl +from ....types import CondaHealthCheck + +if TYPE_CHECKING: + from collections.abc import Iterable + + +def file_locking_check(prefix: str, verbose: bool) -> None: + """Health check action: Report if file locking is supported.""" + if locking_supported(): + if context.no_lock: + print( + f"{X_MARK} File locking is supported but currently disabled using the CONDA_NO_LOCK=1 setting.\n" + ) + else: + print(f"{OK_MARK} File locking is supported.\n") + else: + print(f"{X_MARK} File locking is not supported.\n") + + +@hookimpl +def conda_health_checks() -> Iterable[CondaHealthCheck]: + """Register the file locking health check.""" + yield CondaHealthCheck( + name="file-locking", + action=file_locking_check, + summary="Check if file locking is supported", + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/missing_files.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/missing_files.py new file mode 100644 index 0000000000000000000000000000000000000000..809dff6f4c3ba60e38de23b0b3beeee6322bea61 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/missing_files.py @@ -0,0 +1,86 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health check: Missing files in packages.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from .....base.constants import OK_MARK, X_MARK +from .....cli.install import reinstall_packages +from .....common.serialize import json +from .... import hookimpl +from ....types import CondaHealthCheck + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Iterable + + from ....types import ConfirmCallback + + +def excluded_files_check(filename: str) -> bool: + """Check if a file should be excluded from health checks.""" + excluded_extensions = (".pyc", ".pyo") + return filename.endswith(excluded_extensions) + + +def find_packages_with_missing_files(prefix: str | Path) -> dict[str, list[str]]: + """Finds packages listed in conda-meta which have missing files.""" + packages_with_missing_files = {} + prefix = Path(prefix) + for file in (prefix / "conda-meta").glob("*.json"): + for file_name in json.loads(file.read_text()).get("files", []): + if ( + not excluded_files_check(file_name) + and not (prefix / file_name).exists() + ): + packages_with_missing_files.setdefault(file.stem, []).append(file_name) + return packages_with_missing_files + + +def missing_files(prefix: str, verbose: bool) -> None: + """Health check action: Report packages with missing files.""" + missing = find_packages_with_missing_files(prefix) + if missing: + print(f"{X_MARK} Missing Files:\n") + for package_name, files in missing.items(): + if verbose: + delimiter = "\n " + print(f"{package_name}:{delimiter}{delimiter.join(files)}") + else: + print(f"{package_name}: {len(files)}\n") + else: + print(f"{OK_MARK} There are no packages with missing files.\n") + + +def fix_missing_files(prefix: str, args: Namespace, confirm: ConfirmCallback) -> int: + """Fix missing files by reinstalling affected packages.""" + packages_with_missing = find_packages_with_missing_files(prefix) + + if not packages_with_missing: + print("No packages with missing files found.") + return 0 + + print(f"Found {len(packages_with_missing)} package(s) with missing files:") + for pkg_name, files in sorted(packages_with_missing.items()): + print(f" {pkg_name}: {len(files)} missing file(s)") + + print() + confirm("Reinstall these packages to restore missing files?") + + specs = list(packages_with_missing.keys()) + return reinstall_packages(args, specs, force_reinstall=True) + + +@hookimpl +def conda_health_checks() -> Iterable[CondaHealthCheck]: + """Register the missing files health check.""" + yield CondaHealthCheck( + name="missing-files", + action=missing_files, + fixer=fix_missing_files, + summary="Detect packages with missing files", + fix="Reinstall affected packages", + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/pinned.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/pinned.py new file mode 100644 index 0000000000000000000000000000000000000000..10432d508bdeaddf73cff5567340cacd3f6d76b8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/pinned.py @@ -0,0 +1,131 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health check: Pinned file format.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from .....base.constants import OK_MARK, PREFIX_PINNED_FILE, X_MARK +from .....common.io import dashlist +from .....core.prefix_data import PrefixData +from .....models.match_spec import MatchSpec +from .... import hookimpl +from ....types import CondaHealthCheck + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Iterable + + from ....types import ConfirmCallback + + +def find_malformed_pinned_specs(prefix_data: PrefixData) -> list[MatchSpec]: + """Find pinned specs that reference packages not installed in the environment. + + Returns a list of MatchSpec objects for packages that might be typos. + """ + try: + pinned_specs = prefix_data.get_pinned_specs() + except Exception: + return [] + + if not pinned_specs: + return [] + + return [ + pinned for pinned in pinned_specs if not any(prefix_data.query(pinned.name)) + ] + + +def pinned_well_formatted_check(prefix: str, verbose: bool) -> None: + """Health check action: Check pinned file format.""" + prefix_data = PrefixData(prefix_path=prefix) + pinned_file = prefix_data.prefix_path / PREFIX_PINNED_FILE + + try: + pinned_specs = prefix_data.get_pinned_specs() + except OSError as err: + print(f"{X_MARK} Unable to open pinned file at {pinned_file}:\n\t{err}") + return + except Exception as err: + print( + f"{X_MARK} An error occurred trying to read pinned file at {pinned_file}:\n\t{err}" + ) + return + + if not pinned_specs: + print(f"{OK_MARK} No pinned specs found in {pinned_file}.") + return + + maybe_malformed = find_malformed_pinned_specs(prefix_data) + + if maybe_malformed: + print(f"{X_MARK} The following specs in {pinned_file} are maybe malformed:") + print(dashlist((spec.name for spec in maybe_malformed), indent=4)) + return + + print(f"{OK_MARK} The pinned file in {pinned_file} seems well formatted.") + + +def fix_malformed_pinned(prefix: str, args: Namespace, confirm: ConfirmCallback) -> int: + """Clean up malformed specs in pinned file.""" + prefix_data = PrefixData(prefix) + pinned_file = Path(prefix) / PREFIX_PINNED_FILE + + if not pinned_file.exists(): + print(f"No pinned file found at {pinned_file}") + return 0 + + malformed = find_malformed_pinned_specs(prefix_data) + + if not malformed: + print("No malformed specs found in pinned file.") + return 0 + + print(f"Found {len(malformed)} potentially malformed spec(s) in {pinned_file}:") + for spec in malformed: + print(f" {spec} (package not installed)") + + print() + confirm("Remove these specs from the pinned file?") + + # Read the current file and filter out malformed specs + malformed_names = {spec.name for spec in malformed} + lines = pinned_file.read_text().splitlines() + new_lines = [] + + for line in lines: + stripped = line.strip() + if not stripped or stripped.startswith("#"): + new_lines.append(line) + continue + + # Parse the spec to get the name + try: + spec = MatchSpec(stripped) + if spec.name not in malformed_names: + new_lines.append(line) + else: + print(f"Removing: {stripped}") + except Exception: + # Keep lines we can't parse + new_lines.append(line) + + # Write back + pinned_file.write_text("\n".join(new_lines) + "\n" if new_lines else "") + print(f"Updated {pinned_file}") + return 0 + + +@hookimpl +def conda_health_checks() -> Iterable[CondaHealthCheck]: + """Register the pinned file health check.""" + yield CondaHealthCheck( + name="pinned", + action=pinned_well_formatted_check, + fixer=fix_malformed_pinned, + summary="Validate format of the pinned file", + fix="Remove invalid specs from pinned file", + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/requests_ca_bundle.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/requests_ca_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..1935a0137e45e00dc5eaffb00afb27516bcba991 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks/requests_ca_bundle.py @@ -0,0 +1,55 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Health check: REQUESTS_CA_BUNDLE environment variable.""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import TYPE_CHECKING + +from requests.exceptions import RequestException + +from .....base.constants import OK_MARK, X_MARK +from .....base.context import context +from .....gateways.connection.session import get_session +from .... import hookimpl +from ....types import CondaHealthCheck + +if TYPE_CHECKING: + from collections.abc import Iterable + + +def requests_ca_bundle_check(prefix: str, verbose: bool) -> None: + """Health check action: Verify REQUESTS_CA_BUNDLE environment variable.""" + # Use a channel aliases url since users may be on an intranet and + # have customized their conda setup to point to an internal mirror. + ca_bundle_test_url = context.channel_alias.urls()[0] + + requests_ca_bundle = os.getenv("REQUESTS_CA_BUNDLE") + if not requests_ca_bundle: + return + elif not Path(requests_ca_bundle).exists(): + print( + f"{X_MARK} Env var `REQUESTS_CA_BUNDLE` is pointing to a non existent file.\n" + ) + else: + session = get_session(ca_bundle_test_url) + try: + response = session.get(ca_bundle_test_url) + response.raise_for_status() + print(f"{OK_MARK} `REQUESTS_CA_BUNDLE` was verified.\n") + except (OSError, RequestException) as e: + print( + f"{X_MARK} The following error occured while verifying `REQUESTS_CA_BUNDLE`: {e}\n" + ) + + +@hookimpl +def conda_health_checks() -> Iterable[CondaHealthCheck]: + """Register the REQUESTS_CA_BUNDLE health check.""" + yield CondaHealthCheck( + name="requests-ca-bundle", + action=requests_ca_bundle_check, + summary="Check REQUESTS_CA_BUNDLE environment variable", + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/types.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/types.py new file mode 100644 index 0000000000000000000000000000000000000000..93928605b528e388b618e57b42a1d99c66375c0a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/types.py @@ -0,0 +1,671 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Definition of specific return types for use when defining a conda plugin hook. + +Each type corresponds to the plugin hook for which it is used. + +""" + +from __future__ import annotations + +import os +from abc import ABC, abstractmethod +from collections.abc import Callable +from contextlib import nullcontext +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +from requests.auth import AuthBase + +from ..auxlib import NULL +from ..auxlib.type_coercion import maybecall +from ..base.constants import APP_NAME +from ..exceptions import PluginError +from ..models.records import PackageRecord + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace + from collections.abc import Callable, Iterable + from contextlib import AbstractContextManager + from typing import Any, ClassVar, Literal, TypeAlias + + from ..auxlib import _Null + from ..common.configuration import Parameter + from ..common.path import PathType + from ..core.path_actions import Action + from ..core.solve import Solver + from ..models.environment import Environment + from ..models.match_spec import MatchSpec + from ..models.records import PrefixRecord + + CondaPrefixDataLoaderCallable: TypeAlias = Callable[ + [PathType, dict[str, PrefixRecord]], + dict[str, PrefixRecord], + ] + + PackageExtract: TypeAlias = Callable[ + [PathType, PathType], # (source_path, destination_directory) + None, + ] + + SinglePlatformEnvironmentExport = Callable[[Environment], str] + MultiPlatformEnvironmentExport = Callable[[Iterable[Environment]], str] + + # Callback type for health check fixer confirmation prompts. + # Raises CondaSystemExit if user declines, or DryRunExit in dry-run mode. + ConfirmCallback: TypeAlias = Callable[[str], None] + + +@dataclass +class CondaPlugin: + """ + Base class for all conda plugins. + """ + + name: str + """User-facing name of the plugin used for selecting & filtering plugins and error messages.""" + + def __post_init__(self): + try: + self.name = self.name.lower().strip() + except AttributeError: + # AttributeError: name is not a string + raise PluginError(f"Invalid plugin name for {self!r}") + + +@dataclass +class CondaSubcommand(CondaPlugin): + """ + Return type to use when defining a conda subcommand plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_subcommands`. + + :param name: Subcommand name (e.g., ``conda my-subcommand-name``). + :param summary: Subcommand summary, will be shown in ``conda --help``. + :param action: Callable that will be run when the subcommand is invoked. + :param configure_parser: Callable that will be run when the subcommand parser is initialized. + """ + + name: str + summary: str + action: Callable[ + [Namespace | tuple[str]], # arguments + int | None, # return code + ] + configure_parser: Callable[[ArgumentParser], None] | None = field(default=None) + + +@dataclass +class CondaVirtualPackage(CondaPlugin): + """ + Return type to use when defining a conda virtual package plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_virtual_packages`. + + .. note:: + The ``version`` and ``build`` parameters can be provided in two ways: + + 1. Direct values: a string or ``None`` (where ``None`` translates to ``0``) + 2. Deferred callables: functions that return either a string, ``None`` (translates to ``0``), + or ``NULL`` (indicates the virtual package should not be exported) + + :param name: Virtual package name (e.g., ``my_custom_os``). + :param version: Virtual package version (e.g., ``1.2.3``). + :param build: Virtual package build string (e.g., ``x86_64``). + :param override_entity: Can be set to either to "version" or "build", the corresponding + value will be overridden if the environment variable + ``CONDA_OVERRIDE_`` is set. + :param empty_override: Value to use for version or build if the override + environment variable is set to an empty string. By default, + this is ``NULL``. + :param version_validation: Optional version validation function to ensure that the override version follows a certain pattern. + """ + + name: str + version: str | None | Callable[[], str | None | _Null] + build: str | None | Callable[[], str | None | _Null] + override_entity: Literal["version", "build"] | None = None + empty_override: None | _Null = NULL + version_validation: Callable[[str], str | None] | None = None + + def to_virtual_package(self) -> PackageRecord | _Null: + # Take the raw version and build as they are. + # At this point, they may be callables (evaluated later) or direct values. + from conda.base.context import context + + version = self.version + build = self.build + + # Check for environment overrides. + # Overrides always yield a concrete value (string, NULL, or None), + # so after this step, version/build will no longer be callables if they were overridden. + if self.override_entity: + # environment variable has highest precedence + override_value = os.getenv(f"{APP_NAME}_OVERRIDE_{self.name}".upper()) + # fallback to context + if override_value is None and context.override_virtual_packages: + override_value = context.override_virtual_packages.get(f"{self.name}") + if override_value is not None: + override_value = override_value.strip() or self.empty_override + if self.override_entity == "version": + version = override_value + elif self.override_entity == "build": + build = override_value + + # If version/build were not overridden and are callables, evaluate them now. + version = maybecall(version) + build = maybecall(build) + + if version is NULL or build is NULL: + return NULL + + if self.version_validation and version is not None: + version = self.version_validation(version) + + return PackageRecord.virtual_package(f"__{self.name}", version, build) + + +@dataclass +class CondaSolver(CondaPlugin): + """ + Return type to use when defining a conda solver plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_solvers`. + + :param name: Solver name (e.g., ``custom-solver``). + :param backend: Type that will be instantiated as the solver backend. + """ + + name: str + backend: type[Solver] + + +@dataclass +class CondaPreCommand(CondaPlugin): + """ + Return type to use when defining a conda pre-command plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_pre_commands`. + + :param name: Pre-command name (e.g., ``custom_plugin_pre_commands``). + :param action: Callable which contains the code to be run. + :param run_for: Represents the command(s) this will be run on (e.g. ``install`` or ``create``). + """ + + name: str + action: Callable[[str], None] + run_for: set[str] + + +@dataclass +class CondaPostCommand(CondaPlugin): + """ + Return type to use when defining a conda post-command plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_post_commands`. + + :param name: Post-command name (e.g., ``custom_plugin_post_commands``). + :param action: Callable which contains the code to be run. + :param run_for: Represents the command(s) this will be run on (e.g. ``install`` or ``create``). + """ + + name: str + action: Callable[[str], None] + run_for: set[str] + + +class ChannelNameMixin: + """ + Class mixin to make all plugin implementations compatible, e.g. when they + use an existing (e.g. 3rd party) requests authentication handler. + + Please use the concrete :class:`~conda.plugins.types.ChannelAuthBase` + in case you're creating an own implementation. + """ + + def __init__(self, channel_name: str, *args, **kwargs): + self.channel_name = channel_name + super().__init__(*args, **kwargs) + + +class ChannelAuthBase(ChannelNameMixin, AuthBase): + """ + Base class that we require all plugin implementations to use to be compatible. + + Authentication is tightly coupled with individual channels. Therefore, an additional + ``channel_name`` property must be set on the ``requests.auth.AuthBase`` based class. + """ + + +@dataclass +class CondaAuthHandler(CondaPlugin): + """ + Return type to use when the defining the conda auth handlers hook. + + :param name: Name (e.g., ``basic-auth``). This name should be unique + and only one may be registered at a time. + :param handler: Type that will be used as the authentication handler + during network requests. + """ + + name: str + handler: type[ChannelAuthBase] + + +@dataclass +class CondaHealthCheck(CondaPlugin): + """ + Return type to use when defining conda health checks plugin hook. + + Health checks are diagnostic actions that report on the state of a conda + environment. They are invoked via ``conda doctor``. + + Health checks can optionally provide a fix capability, which is invoked + via ``conda doctor --fix`` or ``conda doctor --fix ``. + + **Fixer guidelines:** + + Fixers receive a ``confirm`` function that handles user confirmation and + dry-run mode automatically. Simply call it with your message: + + - In normal mode: Prompts the user for confirmation (default: no). + - In dry-run mode: Raises ``DryRunExit`` (handled by the framework). + - If user declines: Raises ``CondaSystemExit`` (handled by the framework). + + Example:: + + from conda.plugins.types import ConfirmCallback + + def my_fixer(prefix: str, args: Namespace, confirm: ConfirmCallback) -> int: + issues = find_issues(prefix) + if not issues: + print("No issues found.") + return 0 + + print(f"Found {len(issues)} issues") + confirm("Fix these issues?") + # ... perform fix ... + return 0 + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_health_checks`. + + :param name: Health check identifier (e.g., ``missing-files``). + :param action: Callable that performs the check: ``action(prefix, verbose) -> None``. + :param fixer: Optional callable that fixes issues: + ``fixer(prefix, args, confirm) -> int``. + The ``confirm`` parameter is a function to call for user confirmation. + It raises an exception if the user declines or in dry-run mode. + :param summary: Short description of what the check detects (shown in ``--list``). + :param fix: Short description of what the fix does (shown in ``--list``). + """ + + name: str + action: Callable[[str, bool], None] + fixer: Callable[[str, Namespace, ConfirmCallback], int] | None = None + summary: str | None = None + fix: str | None = None + + +@dataclass +class CondaPreSolve(CondaPlugin): + """ + Return type to use when defining a conda pre-solve plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_pre_solves`. + + :param name: Pre-solve name (e.g., ``custom_plugin_pre_solve``). + :param action: Callable which contains the code to be run. + """ + + name: str + action: Callable[[frozenset[MatchSpec], frozenset[MatchSpec]], None] + + +@dataclass +class CondaPostSolve(CondaPlugin): + """ + Return type to use when defining a conda post-solve plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_post_solves`. + + :param name: Post-solve name (e.g., ``custom_plugin_post_solve``). + :param action: Callable which contains the code to be run. + """ + + name: str + action: Callable[[str, tuple[PackageRecord, ...], tuple[PackageRecord, ...]], None] + + +@dataclass +class CondaSetting(CondaPlugin): + """ + Return type to use when defining a conda setting plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_settings`. + + :param name: name of the setting (e.g., ``config_param``) + :param description: description of the setting that should be targeted + towards users of the plugin + :param parameter: Parameter instance containing the setting definition + :param aliases: alternative names of the setting + """ + + name: str + description: str + parameter: Parameter + aliases: tuple[str, ...] = tuple() + + +class ProgressBarBase(ABC): + def __init__( + self, + description: str, + **kwargs, + ): + self.description = description + + @abstractmethod + def update_to(self, fraction) -> None: ... + + @abstractmethod + def refresh(self) -> None: ... + + @abstractmethod + def close(self) -> None: ... + + def finish(self): + self.update_to(1) + + @classmethod + def get_lock(cls): + pass + + +class SpinnerBase(ABC): + def __init__(self, message: str, fail_message: str = "failed\n"): + self.message = message + self.fail_message = fail_message + + @abstractmethod + def __enter__(self): ... + + @abstractmethod + def __exit__(self, exc_type, exc_val, exc_tb): ... + + +class ReporterRendererBase(ABC): + """ + Base class for all reporter renderers. + """ + + def render(self, data: Any, **kwargs) -> str: + return str(data) + + @abstractmethod + def detail_view(self, data: dict[str, str | int | bool], **kwargs) -> str: + """ + Render the output in a "tabular" format. + """ + + @abstractmethod + def envs_list( + self, data: Iterable[str] | dict[str, dict[str, str | bool | None]], **kwargs + ) -> str: + """ + Render a list of environments + """ + + @abstractmethod + def progress_bar( + self, + description: str, + **kwargs, + ) -> ProgressBarBase: + """ + Return a :class:`~conda.plugins.types.ProgressBarBase~` object to use as a progress bar + """ + + @classmethod + def progress_bar_context_manager(cls) -> AbstractContextManager: + """ + Returns a null context by default but allows plugins to define their own if necessary + """ + return nullcontext() + + @abstractmethod + def spinner(self, message, failed_message) -> SpinnerBase: + """ + Return a :class:`~conda.plugins.types.SpinnerBase~` object to use as a spinner (i.e. + loading dialog) + """ + + @abstractmethod + def prompt( + self, + message: str = "Proceed", + choices=("yes", "no"), + default: str = "yes", + ) -> str: + """ + Allows for defining an implementation of a "yes/no" confirmation function + """ + + +@dataclass +class CondaReporterBackend(CondaPlugin): + """ + Return type to use when defining a conda reporter backend plugin hook. + + For details on how this is used, see: + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_reporter_backends`. + + :param name: name of the reporter backend (e.g., ``email_reporter``) + This is how the reporter backend with be references in configuration files. + :param description: short description of what the reporter handler does + :param renderer: implementation of ``ReporterRendererBase`` that will be used as the + reporter renderer + """ + + name: str + description: str + renderer: type[ReporterRendererBase] + + +@dataclass +class CondaRequestHeader(CondaPlugin): + """ + Define vendor specific headers to include HTTP requests + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_request_headers` and + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_session_headers`. + + :param name: name of the header used in the HTTP request + :param value: value of the header used in the HTTP request + """ + + name: str + value: str + + +@dataclass +class CondaPreTransactionAction(CondaPlugin): + """ + Return type to use when defining a pre-transaction action hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_pre_transaction_actions`. + + :param name: Pre transaction name (this is just a label) + :param action: Action class which implements + plugin behavior. See + :class:`~conda.core.path_actions.Action` for + implementation details + """ + + name: str + action: type[Action] + + +@dataclass +class CondaPostTransactionAction(CondaPlugin): + """ + Return type to use when defining a post-transaction action hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_post_transaction_actions`. + + :param name: Post transaction name (this is just a label) + :param action: Action class which implements + plugin behavior. See + :class:`~conda.core.path_actions.Action` for + implementation details + """ + + name: str + action: type[Action] + + +@dataclass +class CondaPrefixDataLoader(CondaPlugin): + """ + Define new loaders to expose non-conda packages in a given prefix + as ``PrefixRecord`` objects. + + :param name: name of the loader + :param loader: a function that takes a prefix and a dictionary that maps + package names to ``PrefixRecord`` objects. The newly loaded packages + must be inserted in the passed dictionary accordingly, and also + returned as a separate dictionary. + """ + + name: str + loader: CondaPrefixDataLoaderCallable + + +class EnvironmentSpecBase(ABC): + """ + **EXPERIMENTAL** + + Base class for all environment specifications. + + Environment specs parse different types of environment definition files + (environment.yml, requirements.txt, pyproject.toml, etc.) into a common + Environment object model. + """ + + # Determines if the EnvSpec plugin should be included in the set + # of available plugins checked during environment_spec plugin detection. + # If set to False, the only way to use the plugin will be through explicitly + # requesting it as a cli argument or setting in .condarc. By default, + # autodetection is enabled. + detection_supported: ClassVar[bool] = True + + @abstractmethod + def can_handle(self) -> bool: + """ + Determines if the EnvSpec plugin can read and operate on the + environment described by the `filename`. + + :returns bool: returns True, if the plugin can interpret the file. + """ + raise NotImplementedError() + + @property + @abstractmethod + def env(self) -> Environment: + """ + Express the provided environment file as a conda environment object. + + :returns Environment: the conda environment represented by the file. + """ + raise NotImplementedError() + + +@dataclass +class CondaEnvironmentSpecifier(CondaPlugin): + """ + **EXPERIMENTAL** + + Return type to use when defining a conda env spec plugin hook. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_environment_specifiers`. + + :param name: name of the spec (e.g., ``environment_yaml``) + :param environment_spec: EnvironmentSpecBase subclass handler + """ + + name: str + environment_spec: type[EnvironmentSpecBase] + + +@dataclass +class CondaEnvironmentExporter(CondaPlugin): + """ + **EXPERIMENTAL** + + Return type to use when defining a conda environment exporter plugin hook supporting a single platform. + + :param name: name of the exporter (e.g., ``environment-yaml``) + :param aliases: user-friendly format aliases (e.g., ("yaml",)) + :param default_filenames: default filenames this exporter handles (e.g., ("environment.yml", "environment.yaml")) + :param export: callable that exports an Environment to string format + """ + + name: str + aliases: tuple[str, ...] + default_filenames: tuple[str, ...] + export: SinglePlatformEnvironmentExport | None = None + multiplatform_export: MultiPlatformEnvironmentExport | None = None + + def __post_init__(self): + super().__post_init__() # Handle name normalization + # Normalize aliases using same pattern as name normalization + try: + self.aliases = tuple( + dict.fromkeys(alias.lower().strip() for alias in self.aliases) + ) + except AttributeError: + # AttributeError: alias is not a string + raise PluginError(f"Invalid plugin aliases for {self!r}") + + if bool(self.export) == bool(self.multiplatform_export): + raise PluginError( + f"Exactly one of export or multiplatform_export must be set for {self!r}" + ) + + +@dataclass +class CondaPackageExtractor(CondaPlugin): + """ + Return type to use when defining a conda package extractor plugin hook. + + Package extractors handle the extraction of different package archive formats. + Each extractor specifies which file extensions it supports and provides an + extraction function to unpack the archive. + + For details on how this is used, see + :meth:`~conda.plugins.hookspec.CondaSpecs.conda_package_extractors`. + + :param name: Extractor name (e.g., ``conda-package``, ``wheel-package``). + :param extensions: List of file extensions this extractor handles + (e.g., ``[".conda", ".tar.bz2"]`` or ``[".whl"]``). + :param extract: Callable that extracts the package archive. Takes the source + archive path and the destination directory where the package + contents should be extracted. + """ + + name: str + extensions: list[str] + extract: PackageExtract diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0849ed3d3d2651a393f61c4dd36dc838d8689a63 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/__init__.py @@ -0,0 +1,8 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from __future__ import annotations + +from . import archspec, conda, cuda, freebsd, linux, osx, windows + +plugins = [archspec, conda, cuda, freebsd, linux, osx, windows] +"""The list of virtual package plugins for easier registration with pluggy.""" diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/archspec.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/archspec.py new file mode 100644 index 0000000000000000000000000000000000000000..0496aad5b9cddd8d1c3b06413b74947c92405b3f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/archspec.py @@ -0,0 +1,33 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Detect archspec name.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ...auxlib import NULL +from .. import hookimpl +from ..types import CondaVirtualPackage + +if TYPE_CHECKING: + from collections.abc import Iterable + + +def archspec_build(): + from ...core.index import get_archspec_name + + build_num = get_archspec_name() + return build_num or NULL + + +@hookimpl +def conda_virtual_packages() -> Iterable[CondaVirtualPackage]: + # 1: __archspec==1=BUILD + yield CondaVirtualPackage( + name="archspec", + version="1", + build=archspec_build, + override_entity="build", + # empty_override=NULL, # falsy override → skip __archspec + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/conda.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/conda.py new file mode 100644 index 0000000000000000000000000000000000000000..76f3d6194ac1b15b13ae06e20f8a99b079a27558 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/conda.py @@ -0,0 +1,26 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Expose conda version.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .. import hookimpl +from ..types import CondaVirtualPackage + +if TYPE_CHECKING: + from collections.abc import Iterable + + +@hookimpl +def conda_virtual_packages() -> Iterable[CondaVirtualPackage]: + from ... import __version__ + + # 1: __conda==VERSION=0 (always exported) + yield CondaVirtualPackage( + name="conda", + version=__version__, + build=None, + # override_entity=None, # no override allowed + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/cuda.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..45f0ccddc5db7209f06aa6f7617354fa3a2cabbc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/cuda.py @@ -0,0 +1,164 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Detect CUDA version.""" + +from __future__ import annotations + +import ctypes +import functools +import itertools +import multiprocessing +import os +import platform +from contextlib import suppress +from typing import TYPE_CHECKING + +from ...auxlib import NULL +from .. import hookimpl +from ..types import CondaVirtualPackage + +if TYPE_CHECKING: + from collections.abc import Iterable + + +def cuda_version(): + """ + Attempt to detect the version of CUDA present in the operating system. + + On Windows and Linux, the CUDA library is installed by the NVIDIA + driver package, and is typically found in the standard library path, + rather than with the CUDA SDK (which is optional for running CUDA apps). + + On macOS, the CUDA library is only installed with the CUDA SDK, and + might not be in the library path. + + Returns: version string (e.g., '9.2') or None if CUDA is not found. + """ + + # Do not inherit file descriptors and handles from the parent process. + # The `fork` start method should be considered unsafe as it can lead to + # crashes of the subprocess. The `spawn` start method is preferred. + context = multiprocessing.get_context("spawn") + queue = context.SimpleQueue() + try: + # Spawn a subprocess to detect the CUDA version + detector = context.Process( + target=_cuda_driver_version_detector_target, + args=(queue,), + name="CUDA driver version detector", + daemon=True, + ) + detector.start() + detector.join(timeout=60.0) + finally: + # Always cleanup the subprocess + detector.kill() # requires Python 3.7+ + + if queue.empty(): + return NULL + + result = queue.get() + return result if result is not None else NULL + + +@functools.cache +def cached_cuda_version(): + """A cached version of the cuda detection system.""" + return cuda_version() + + +@hookimpl +def conda_virtual_packages() -> Iterable[CondaVirtualPackage]: + # 1: __cuda==VERSION=0 + yield CondaVirtualPackage( + name="cuda", + version=cached_cuda_version, + build=None, + override_entity="version", + # empty_override=NULL, # falsy override → skip __cuda + ) + + +def _cuda_driver_version_detector_target(queue): + """ + Attempt to detect the version of CUDA present in the operating system in a + subprocess. + + On Windows and Linux, the CUDA library is installed by the NVIDIA + driver package, and is typically found in the standard library path, + rather than with the CUDA SDK (which is optional for running CUDA apps). + + On macOS, the CUDA library is only installed with the CUDA SDK, and + might not be in the library path. + + Returns: version string (e.g., '9.2') or None if CUDA is not found. + The result is put in the queue rather than a return value. + """ + # Platform-specific libcuda location + system = platform.system() + if system == "Darwin": + lib_filenames = [ + "libcuda.1.dylib", # check library path first + "libcuda.dylib", + "/usr/local/cuda/lib/libcuda.1.dylib", + "/usr/local/cuda/lib/libcuda.dylib", + ] + elif system == "Linux": + lib_filenames = [ + "libcuda.so", # check library path first + "/usr/lib64/nvidia/libcuda.so", # RHEL/Centos/Fedora + "/usr/lib/x86_64-linux-gnu/libcuda.so", # Ubuntu + "/usr/lib/wsl/lib/libcuda.so", # WSL + ] + # Also add libraries with version suffix `.1` + lib_filenames = list( + itertools.chain.from_iterable((f"{lib}.1", lib) for lib in lib_filenames) + ) + elif system == "Windows": + bits = platform.architecture()[0].replace("bit", "") # e.g. "64" or "32" + lib_filenames = [f"nvcuda{bits}.dll", "nvcuda.dll"] + else: + queue.put(None) # CUDA not available for other operating systems + return + + # Open library + if system == "Windows": + dll = ctypes.windll + else: + dll = ctypes.cdll + for lib_filename in lib_filenames: + with suppress(Exception): + libcuda = dll.LoadLibrary(lib_filename) + break + else: + queue.put(None) + return + + # Empty `CUDA_VISIBLE_DEVICES` can cause `cuInit()` returns `CUDA_ERROR_NO_DEVICE` + # Invalid `CUDA_VISIBLE_DEVICES` can cause `cuInit()` returns `CUDA_ERROR_INVALID_DEVICE` + # Unset this environment variable to avoid these errors + os.environ.pop("CUDA_VISIBLE_DEVICES", None) + + # Get CUDA version + try: + cuInit = libcuda.cuInit + flags = ctypes.c_uint(0) + ret = cuInit(flags) + if ret != 0: + queue.put(None) + return + + cuDriverGetVersion = libcuda.cuDriverGetVersion + version_int = ctypes.c_int(0) + ret = cuDriverGetVersion(ctypes.byref(version_int)) + if ret != 0: + queue.put(None) + return + + # Convert version integer to version string + value = version_int.value + queue.put(f"{value // 1000}.{(value % 1000) // 10}") + return + except Exception: + queue.put(None) + return diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/freebsd.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/freebsd.py new file mode 100644 index 0000000000000000000000000000000000000000..5936f304ed65f9649354facbc292935f8a739012 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/freebsd.py @@ -0,0 +1,28 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Detect whether this is FeeBSD.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ...base.context import context +from .. import hookimpl +from ..types import CondaVirtualPackage + +if TYPE_CHECKING: + from collections.abc import Iterable + + +@hookimpl +def conda_virtual_packages() -> Iterable[CondaVirtualPackage]: + if not context.subdir.startswith("freebsd-"): + return + + # 1: __unix==0=0 (always exported if target subdir is freebsd-*) + yield CondaVirtualPackage( + name="unix", + version=None, + build=None, + # override_entity=None, # no override allowed + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/linux.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/linux.py new file mode 100644 index 0000000000000000000000000000000000000000..8091686099e78dd15fb08d8c63f720a3d3b63986 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/linux.py @@ -0,0 +1,76 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Detect whether this is Linux.""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from ...base.context import context +from ...common._os.linux import linux_get_libc_version +from .. import hookimpl +from ..types import CondaVirtualPackage + +if TYPE_CHECKING: + from collections.abc import Iterable + + +LINUX_VERSION_PATTERN = re.compile(r"\d+\.\d+(\.\d+)?(\.\d+)?") + + +def linux_version() -> str | None: + dist_name, dist_version = context.platform_system_release + if dist_name != "Linux": + # dist_version is only valid if we are on Linux + # this happens with `CONDA_SUBDIR=linux-*`/`--platform=linux-*` on a non-Linux machine + dist_version = None + return dist_version + + +def linux_version_validate(version: str) -> str | None: + # By convention, the kernel release string should be three or four + # numeric components, separated by dots, followed by vendor-specific + # bits. For the purposes of versioning the `__linux` virtual package, + # discard everything after the last digit of the third or fourth + # numeric component; note that this breaks version ordering for + # development (`-rcN`) kernels, but that can be a TODO for later. + match = LINUX_VERSION_PATTERN.match(version) + return match.group() if match else None + + +@hookimpl +def conda_virtual_packages() -> Iterable[CondaVirtualPackage]: + if not context.subdir.startswith("linux-"): + return + + # 1: __unix==0=0 (always exported if target subdir is linux-*) + yield CondaVirtualPackage( + name="unix", + version=None, + build=None, + # override_entity=None, # no override allowed + ) + + # 2: __linux==VERSION=0 (always exported if target subdir is linux-*) + yield CondaVirtualPackage( + name="linux", + version=linux_version, + build=None, + override_entity="version", + empty_override=None, # falsy override → __linux==0=0 + version_validation=linux_version_validate, + ) + + # 3: __glibc==VERSION=0 (or another applicable libc) + libc_family, libc_version = linux_get_libc_version() + if not (libc_family and libc_version): + # Default to glibc when using CONDA_SUBDIR var + libc_family = "glibc" + yield CondaVirtualPackage( + name=libc_family, + version=libc_version, + build=None, + override_entity="version", + # empty_override=NULL, # falsy override → skip __glibc + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/osx.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/osx.py new file mode 100644 index 0000000000000000000000000000000000000000..7754ca8ef62f66453f53e39d5059f5eca7b49a11 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/osx.py @@ -0,0 +1,46 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Detect whether this is macOS.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ...base.context import context +from .. import hookimpl +from ..types import CondaVirtualPackage + +if TYPE_CHECKING: + from collections.abc import Iterable + + +def osx_version() -> str | None: + dist_name, dist_version = context.os_distribution_name_version + if dist_name != "OSX": + # dist_version is only valid if we are on macOS + # this happens with `CONDA_SUBDIR=osx-*`/`--platform=osx-*` on a non-macOS machine + dist_version = None + return dist_version + + +@hookimpl +def conda_virtual_packages() -> Iterable[CondaVirtualPackage]: + if not context.subdir.startswith("osx-"): + return + + # 1: __unix==0=0 (always exported if the target subdir is osx-*) + yield CondaVirtualPackage( + name="unix", + version=None, + build=None, + # override_entity=None, # no override allowed + ) + + # 2: __osx==VERSION=0 + yield CondaVirtualPackage( + name="osx", + version=osx_version, + build=None, + override_entity="version", + # empty_override=NULL, # falsy override → skip __osx + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/windows.py b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..70b04c02410538f137fdf707384b734160e6a12e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/plugins/virtual_packages/windows.py @@ -0,0 +1,38 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Detect whether this is Windows.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ...base.context import context +from .. import hookimpl +from ..types import CondaVirtualPackage + +if TYPE_CHECKING: + from collections.abc import Iterable + + +def win_version() -> str | None: + dist_name, dist_version = context.os_distribution_name_version + if dist_name != "Windows": + # dist_version is only valid if we are on Windows + # this happens with `CONDA_SUBDIR=win-*`/`--platform=win-*` on a non-Windows machine + dist_version = None + return dist_version + + +@hookimpl +def conda_virtual_packages() -> Iterable[CondaVirtualPackage]: + if not context.subdir.startswith("win-"): + return + + # 1: __win==VERSION=0 + yield CondaVirtualPackage( + name="win", + version=win_version, + build=None, + override_entity="version", + # empty_override=NULL, # falsy override → skip __win + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/py.typed b/miniconda3/lib/python3.13/site-packages/conda/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda/reporters.py b/miniconda3/lib/python3.13/site-packages/conda/reporters.py new file mode 100644 index 0000000000000000000000000000000000000000..34e02d881084e66a3e471aebf4f6d077129da594 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/reporters.py @@ -0,0 +1,103 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +Holds functions for output rendering in conda +""" + +from __future__ import annotations + +import logging +import sys +from functools import cache +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from contextlib import AbstractContextManager + +from .base.context import context +from .exceptions import CondaSystemExit, DryRunExit + +if TYPE_CHECKING: + from collections.abc import Callable + + from .plugins.types import ProgressBarBase, SpinnerBase + +logger = logging.getLogger(__name__) + + +@cache +def _get_render_func(style: str | None = None) -> Callable: + """ + Retrieves the render function to use + """ + backend = context.console + reporter = context.plugin_manager.get_reporter_backend(backend) + + renderer = reporter.renderer() + + if style is not None: + render_func = getattr(renderer, style, None) + if render_func is None: + raise AttributeError(f"'{style}' is not a valid reporter backend style") + else: + render_func = getattr(renderer, "render") + + return render_func + + +def render(data, style: str | None = None, **kwargs) -> None: + """ + Used to render output in conda + + The output will either be rendered as "json" or normal "console" output to stdout. + This function allows us to configure different reporter backends for these two types + of output. + """ + render_func = _get_render_func(style) + data_str = render_func(data, **kwargs) + sys.stdout.write(data_str) + + +def get_progress_bar(description: str, **kwargs) -> ProgressBarBase: + """ + Retrieve the progress bar for the currently configured reporter backend + """ + return _get_render_func("progress_bar")(description, **kwargs) + + +def get_progress_bar_context_manager() -> AbstractContextManager: + """ + Retrieve progress bar context manager to use with registered reporter + """ + return _get_render_func("progress_bar_context_manager")() + + +def get_spinner(message: str, fail_message: str = "failed\n") -> SpinnerBase: + """ + Retrieve spinner to use with registered reporter + """ + return _get_render_func("spinner")(message, fail_message) + + +def confirm_yn(message: str = "Proceed", default="yes", dry_run=None) -> bool: + """ + Display a "yes/no" confirmation input + """ + if (dry_run is None and context.dry_run) or dry_run: + raise DryRunExit() + + if context.always_yes: + return True + + try: + choice = _get_render_func("prompt")( + message, choices=("yes", "no"), default=default + ) + + except KeyboardInterrupt: # pragma: no cover + raise CondaSystemExit("\nOperation aborted. Exiting.") + + if choice == "no": + raise CondaSystemExit("Exiting.") + + return True diff --git a/miniconda3/lib/python3.13/site-packages/conda/resolve.py b/miniconda3/lib/python3.13/site-packages/conda/resolve.py new file mode 100644 index 0000000000000000000000000000000000000000..42ee26e0c77a75b45d6c8db2450137234a8039e6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/resolve.py @@ -0,0 +1,1677 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level SAT solver wrapper/interface for the classic solver. + +See conda.core.solver.Solver for the high-level API. +""" + +from __future__ import annotations + +import copy +import itertools +from collections import defaultdict, deque +from functools import cache +from logging import DEBUG, getLogger +from typing import TYPE_CHECKING + +from frozendict import frozendict +from tqdm import tqdm + +from .auxlib.decorators import memoizemethod +from .base.constants import MAX_CHANNEL_PRIORITY, ChannelPriority, SatSolverChoice +from .base.context import context +from .common.compat import on_win +from .common.io import dashlist, time_recorder +from .common.iterators import groupby_to_dict as groupby +from .common.logic import ( + TRUE, + Clauses, + PycoSatSolver, + PyCryptoSatSolver, + PySatSolver, + minimal_unsatisfiable_subset, +) +from .common.toposort import toposort +from .exceptions import ( + CondaDependencyError, + InvalidSpec, + ResolvePackageNotFound, + UnsatisfiableError, +) +from .models.channel import Channel +from .models.enums import NoarchType, PackageType +from .models.match_spec import MatchSpec +from .models.records import PackageRecord +from .models.version import VersionOrder + +if TYPE_CHECKING: + from collections.abc import Iterable + +log = getLogger(__name__) +stdoutlog = getLogger("conda.stdoutlog") + +# used in conda build +Unsatisfiable = UnsatisfiableError +ResolvePackageNotFound = ResolvePackageNotFound + +_sat_solvers = { + SatSolverChoice.PYCOSAT: PycoSatSolver, + SatSolverChoice.PYCRYPTOSAT: PyCryptoSatSolver, + SatSolverChoice.PYSAT: PySatSolver, +} + + +@cache +def _get_sat_solver_cls(sat_solver_choice=SatSolverChoice.PYCOSAT): + def try_out_solver(sat_solver): + c = Clauses(sat_solver=sat_solver) + required = {c.new_var(), c.new_var()} + c.Require(c.And, *required) + solution = set(c.sat()) + if not required.issubset(solution): + raise RuntimeError(f"Wrong SAT solution: {solution}. Required: {required}") + + sat_solver = _sat_solvers[sat_solver_choice] + try: + try_out_solver(sat_solver) + except Exception as e: + log.warning( + "Could not run SAT solver through interface '%s'.", sat_solver_choice + ) + log.debug("SAT interface error due to: %s", e, exc_info=True) + else: + log.debug("Using SAT solver interface '%s'.", sat_solver_choice) + return sat_solver + for sat_solver in _sat_solvers.values(): + try: + try_out_solver(sat_solver) + except Exception as e: + log.debug( + "Attempted SAT interface '%s' but unavailable due to: %s", + sat_solver_choice, + e, + ) + else: + log.debug("Falling back to SAT solver interface '%s'.", sat_solver_choice) + return sat_solver + raise CondaDependencyError( + "Cannot run solver. No functioning SAT implementations available." + ) + + +def exactness_and_number_of_deps(resolve_obj, ms): + """Sorting key to emphasize packages that have more strict + requirements. More strict means the reduced index can be reduced + more, so we want to consider these more constrained deps earlier in + reducing the index. + """ + if ms.strictness == 3: + prec = resolve_obj.find_matches(ms) + value = 3 + if prec: + for dep in prec[0].depends: + value += MatchSpec(dep).strictness + else: + value = ms.strictness + return value + + +class Resolve: + def __init__(self, index, processed=False, channels=()): + self.index = index + + self.channels = channels + self._channel_priorities_map = ( + self._make_channel_priorities(channels) if channels else {} + ) + self._channel_priority = context.channel_priority + self._solver_ignore_timestamps = context.solver_ignore_timestamps + + groups = groupby(lambda x: x.name, index.values()) + trackers = defaultdict(list) + + for name in groups: + unmanageable_precs = [prec for prec in groups[name] if prec.is_unmanageable] + if unmanageable_precs: + log.debug("restricting to unmanageable packages: %s", name) + groups[name] = unmanageable_precs + tf_precs = (prec for prec in groups[name] if prec.track_features) + for prec in tf_precs: + for feature_name in prec.track_features: + trackers[feature_name].append(prec) + + self.groups = groups # dict[package_name, list[PackageRecord]] + self.trackers = trackers # dict[track_feature, set[PackageRecord]] + self._cached_find_matches = {} # dict[MatchSpec, set[PackageRecord]] + self.ms_depends_ = {} # dict[PackageRecord, list[MatchSpec]] + self._reduced_index_cache = {} + self._pool_cache = {} + self._strict_channel_cache = {} + + self._system_precs = { + _ + for _ in index + if ( + hasattr(_, "package_type") + and _.package_type == PackageType.VIRTUAL_SYSTEM + ) + } + + # sorting these in reverse order is effectively prioritizing + # constraint behavior from newer packages. It is applying broadening + # reduction based on the latest packages, which may reduce the space + # more, because more modern packages utilize constraints in more sane + # ways (for example, using run_exports in conda-build 3) + for name, group in self.groups.items(): + self.groups[name] = sorted(group, key=self.version_key, reverse=True) + + def __hash__(self): + return ( + super().__hash__() + ^ hash(frozenset(self.channels)) + ^ hash(frozendict(self._channel_priorities_map)) + ^ hash(self._channel_priority) + ^ hash(self._solver_ignore_timestamps) + ^ hash(frozendict((k, tuple(v)) for k, v in self.groups.items())) + ^ hash(frozendict((k, tuple(v)) for k, v in self.trackers.items())) + ^ hash(frozendict((k, tuple(v)) for k, v in self.ms_depends_.items())) + ) + + def default_filter(self, features=None, filter=None): + if filter is None: + filter = {} + else: + filter.clear() + + filter.update( + {PackageRecord.feature(name): False for name in self.trackers.keys()} + ) + if features: + filter.update({PackageRecord.feature(name): True for name in features}) + return filter + + def valid(self, spec_or_prec, filter, optional=True): + """Tests if a package, MatchSpec, or a list of both has satisfiable + dependencies, assuming cyclic dependencies are always valid. + + Args: + spec_or_prec: a package record, a MatchSpec, or an iterable of these. + filter: a dictionary of (fkey,valid) pairs, used to consider a subset + of dependencies, and to eliminate repeated searches. + optional: if True (default), do not enforce optional specifications + when considering validity. If False, enforce them. + + Returns: + True if the full set of dependencies can be satisfied; False otherwise. + If filter is supplied and update is True, it will be updated with the + search results. + """ + + def v_(spec): + return v_ms_(spec) if isinstance(spec, MatchSpec) else v_fkey_(spec) + + def v_ms_(ms): + return ( + optional + and ms.optional + or any(v_fkey_(fkey) for fkey in self.find_matches(ms)) + ) + + def v_fkey_(prec): + val = filter.get(prec) + if val is None: + filter[prec] = True + try: + depends = self.ms_depends(prec) + except InvalidSpec: + val = filter[prec] = False + else: + val = filter[prec] = all(v_ms_(ms) for ms in depends) + return val + + result = v_(spec_or_prec) + return result + + def valid2(self, spec_or_prec, filter_out, optional=True): + def is_valid(_spec_or_prec): + if isinstance(_spec_or_prec, MatchSpec): + return is_valid_spec(_spec_or_prec) + else: + return is_valid_prec(_spec_or_prec) + + @memoizemethod + def is_valid_spec(_spec): + return ( + optional + and _spec.optional + or any(is_valid_prec(_prec) for _prec in self.find_matches(_spec)) + ) + + def is_valid_prec(prec): + val = filter_out.get(prec) + if val is None: + filter_out[prec] = False + try: + has_valid_deps = all( + is_valid_spec(ms) for ms in self.ms_depends(prec) + ) + except InvalidSpec: + val = filter_out[prec] = "invalid dep specs" + else: + val = filter_out[prec] = ( + False if has_valid_deps else "invalid depends specs" + ) + return not val + + return is_valid(spec_or_prec) + + def invalid_chains(self, spec, filter, optional=True): + """Constructs a set of 'dependency chains' for invalid specs. + + A dependency chain is a tuple of MatchSpec objects, starting with + the requested spec, proceeding down the dependency tree, ending at + a specification that cannot be satisfied. + + Args: + spec: a package key or MatchSpec + filter: a dictionary of (prec, valid) pairs to be used when + testing for package validity. + + Returns: + A tuple of tuples, empty if the MatchSpec is valid. + """ + + def chains_(spec, names): + if spec.name in names: + return + names.add(spec.name) + if self.valid(spec, filter, optional): + return + precs = self.find_matches(spec) + found = False + + conflict_deps = set() + for prec in precs: + for m2 in self.ms_depends(prec): + for x in chains_(m2, names): + found = True + yield (spec,) + x + else: + conflict_deps.add(m2) + if not found: + conflict_groups = groupby(lambda x: x.name, conflict_deps) + for group in conflict_groups.values(): + yield (spec,) + MatchSpec.union(group) + + return chains_(spec, set()) + + def verify_specs(self, specs): + """Perform a quick verification that specs and dependencies are reasonable. + + Args: + specs: An iterable of strings or MatchSpec objects to be tested. + + Returns: + Nothing, but if there is a conflict, an error is thrown. + + Note that this does not attempt to resolve circular dependencies. + """ + non_tf_specs = [] + bad_deps = [] + feature_names = set() + for ms in specs: + _feature_names = ms.get_exact_value("track_features") + if _feature_names: + feature_names.update(_feature_names) + else: + non_tf_specs.append(ms) + bad_deps.extend( + (spec,) + for spec in non_tf_specs + if (not spec.optional and not self.find_matches(spec)) + ) + if bad_deps: + raise ResolvePackageNotFound(bad_deps) + return tuple(non_tf_specs), feature_names + + def _classify_bad_deps( + self, bad_deps, specs_to_add, history_specs, strict_channel_priority + ): + classes = { + "python": set(), + "request_conflict_with_history": set(), + "direct": set(), + "virtual_package": set(), + } + specs_to_add = {MatchSpec(_) for _ in specs_to_add or []} + history_specs = {MatchSpec(_) for _ in history_specs or []} + for chain in bad_deps: + # sometimes chains come in as strings + if ( + len(chain) > 1 + and chain[-1].name == "python" + and not any(_.name == "python" for _ in specs_to_add) + and any(_[0] for _ in bad_deps if _[0].name == "python") + ): + python_first_specs = [_[0] for _ in bad_deps if _[0].name == "python"] + if python_first_specs: + python_spec = python_first_specs[0] + if not ( + set(self.find_matches(python_spec)) + & set(self.find_matches(chain[-1])) + ): + classes["python"].add( + ( + tuple([chain[0], chain[-1]]), + str(MatchSpec(python_spec, target=None)), + ) + ) + elif chain[-1].name.startswith("__"): + version = [_ for _ in self._system_precs if _.name == chain[-1].name] + virtual_package_version = ( + version[0].version if version else "not available" + ) + classes["virtual_package"].add((tuple(chain), virtual_package_version)) + elif chain[0] in specs_to_add: + match = False + for spec in history_specs: + if spec.name == chain[-1].name: + classes["request_conflict_with_history"].add( + (tuple(chain), str(MatchSpec(spec, target=None))) + ) + match = True + + if not match: + classes["direct"].add( + (tuple(chain), str(MatchSpec(chain[0], target=None))) + ) + else: + if len(chain) > 1 or any( + len(c) >= 1 and c[0] == chain[0] for c in bad_deps + ): + classes["direct"].add( + (tuple(chain), str(MatchSpec(chain[0], target=None))) + ) + + if classes["python"]: + # filter out plain single-entry python conflicts. The python section explains these. + classes["direct"] = [ + _ + for _ in classes["direct"] + if _[1].startswith("python ") or len(_[0]) > 1 + ] + return classes + + def find_matches_with_strict(self, ms, strict_channel_priority): + matches = self.find_matches(ms) + if not strict_channel_priority: + return matches + sole_source_channel_name = self._get_strict_channel(ms.name) + return tuple(f for f in matches if f.channel.name == sole_source_channel_name) + + def find_conflicts(self, specs, specs_to_add=None, history_specs=None): + if context.unsatisfiable_hints: + if not context.json: + print( + "\nFound conflicts! Looking for incompatible packages.\n" + "This can take several minutes. Press CTRL-C to abort." + ) + bad_deps = self.build_conflict_map(specs, specs_to_add, history_specs) + else: + bad_deps = {} + strict_channel_priority = context.channel_priority == ChannelPriority.STRICT + raise UnsatisfiableError(bad_deps, strict=strict_channel_priority) + + def breadth_first_search_for_dep_graph( + self, root_spec, target_name, dep_graph, num_targets=1 + ): + """Return shorted path from root_spec to target_name""" + queue = [] + queue.append([root_spec]) + visited = [] + target_paths = [] + while queue: + path = queue.pop(0) + node = path[-1] + if node in visited: + continue + visited.append(node) + if node.name == target_name: + if len(target_paths) == 0: + target_paths.append(path) + if len(target_paths[-1]) == len(path): + last_spec = MatchSpec.union((path[-1], target_paths[-1][-1]))[0] + target_paths[-1][-1] = last_spec + else: + target_paths.append(path) + + found_all_targets = len(target_paths) == num_targets and any( + len(_) != len(path) for _ in queue + ) + if len(queue) == 0 or found_all_targets: + return target_paths + sub_graph = dep_graph + for p in path[0:-1]: + sub_graph = sub_graph[p] + children = [_ for _ in sub_graph.get(node, {})] + if children is None: + continue + for adj in children: + if len(target_paths) < num_targets: + new_path = list(path) + new_path.append(adj) + queue.append(new_path) + return target_paths + + def build_graph_of_deps(self, spec): + dep_graph = {spec: {}} + all_deps = set() + queue = [[spec]] + while queue: + path = queue.pop(0) + sub_graph = dep_graph + for p in path: + sub_graph = sub_graph[p] + parent_node = path[-1] + matches = self.find_matches(parent_node) + for mat in matches: + if len(mat.depends) > 0: + for i in mat.depends: + new_node = MatchSpec(i) + sub_graph.update({new_node: {}}) + all_deps.add(new_node) + new_path = list(path) + new_path.append(new_node) + if len(new_path) <= context.unsatisfiable_hints_check_depth: + queue.append(new_path) + return dep_graph, all_deps + + def build_conflict_map(self, specs, specs_to_add=None, history_specs=None): + """Perform a deeper analysis on conflicting specifications, by attempting + to find the common dependencies that might be the cause of conflicts. + + Args: + specs: An iterable of strings or MatchSpec objects to be tested. + It is assumed that the specs conflict. + + Returns: + bad_deps: A list of lists of bad deps + + Strategy: + If we're here, we know that the specs conflict. This could be because: + - One spec conflicts with another; e.g. + ['numpy 1.5*', 'numpy >=1.6'] + - One spec conflicts with a dependency of another; e.g. + ['numpy 1.5*', 'scipy 0.12.0b1'] + - Each spec depends on *the same package* but in a different way; e.g., + ['A', 'B'] where A depends on numpy 1.5, and B on numpy 1.6. + Technically, all three of these cases can be boiled down to the last + one if we treat the spec itself as one of the "dependencies". There + might be more complex reasons for a conflict, but this code only + considers the ones above. + + The purpose of this code, then, is to identify packages (like numpy + above) that all of the specs depend on *but in different ways*. We + then identify the dependency chains that lead to those packages. + """ + # if only a single package matches the spec use the packages depends + # rather than the spec itself + strict_channel_priority = context.channel_priority == ChannelPriority.STRICT + + specs = set(specs) | (specs_to_add or set()) + # Remove virtual packages + specs = {spec for spec in specs if not spec.name.startswith("__")} + if len(specs) == 1: + matches = self.find_matches(next(iter(specs))) + if len(matches) == 1: + specs = set(self.ms_depends(matches[0])) + specs.update({_.to_match_spec() for _ in self._system_precs}) + for spec in specs: + self._get_package_pool((spec,)) + + dep_graph = {} + dep_list = {} + with tqdm( + total=len(specs), + desc="Building graph of deps", + leave=False, + disable=context.json, + ) as t: + for spec in specs: + t.set_description(f"Examining {spec}") + t.update() + dep_graph_for_spec, all_deps_for_spec = self.build_graph_of_deps(spec) + dep_graph.update(dep_graph_for_spec) + if dep_list.get(spec.name): + dep_list[spec.name].append(spec) + else: + dep_list[spec.name] = [spec] + for dep in all_deps_for_spec: + if dep_list.get(dep.name): + dep_list[dep.name].append(spec) + else: + dep_list[dep.name] = [spec] + + chains = [] + conflicting_pkgs_pkgs = {} + for k, v in dep_list.items(): + set_v = frozenset(v) + # Packages probably conflicts if many specs depend on it + if len(set_v) > 1: + if conflicting_pkgs_pkgs.get(set_v) is None: + conflicting_pkgs_pkgs[set_v] = [k] + else: + conflicting_pkgs_pkgs[set_v].append(k) + # Conflict if required virtual package is not present + elif k.startswith("__") and any(s for s in set_v if s.name != k): + conflicting_pkgs_pkgs[set_v] = [k] + + with tqdm( + total=len(specs), + desc="Determining conflicts", + leave=False, + disable=context.json, + ) as t: + for roots, nodes in conflicting_pkgs_pkgs.items(): + t.set_description( + "Examining conflict for {}".format(" ".join(_.name for _ in roots)) + ) + t.update() + lroots = [_ for _ in roots] + current_shortest_chain = [] + shortest_node = None + requested_spec_unsat = frozenset(nodes).intersection( + {_.name for _ in roots} + ) + if requested_spec_unsat: + chains.append([_ for _ in roots if _.name in requested_spec_unsat]) + shortest_node = chains[-1][0] + for root in roots: + if root != chains[0][0]: + search_node = shortest_node.name + num_occurances = dep_list[search_node].count(root) + c = self.breadth_first_search_for_dep_graph( + root, search_node, dep_graph, num_occurances + ) + chains.extend(c) + else: + for node in nodes: + num_occurances = dep_list[node].count(lroots[0]) + chain = self.breadth_first_search_for_dep_graph( + lroots[0], node, dep_graph, num_occurances + ) + chains.extend(chain) + if len(current_shortest_chain) == 0 or len(chain) < len( + current_shortest_chain + ): + current_shortest_chain = chain + shortest_node = node + for root in lroots[1:]: + num_occurances = dep_list[shortest_node].count(root) + c = self.breadth_first_search_for_dep_graph( + root, shortest_node, dep_graph, num_occurances + ) + chains.extend(c) + + bad_deps = self._classify_bad_deps( + chains, specs_to_add, history_specs, strict_channel_priority + ) + return bad_deps + + def _get_strict_channel(self, package_name): + channel_name = None + try: + channel_name = self._strict_channel_cache[package_name] + except KeyError: + if package_name in self.groups: + all_channel_names = { + prec.channel.name for prec in self.groups[package_name] + } + by_cp = { + self._channel_priorities_map.get(cn, 1): cn + for cn in all_channel_names + } + highest_priority = sorted(by_cp)[ + 0 + ] # highest priority is the lowest number + channel_name = self._strict_channel_cache[package_name] = by_cp[ + highest_priority + ] + return channel_name + + @memoizemethod + def _broader(self, ms, specs_by_name): + """Prevent introduction of matchspecs that broaden our selection of choices.""" + if not specs_by_name: + return False + return ms.strictness < specs_by_name[0].strictness + + def _get_package_pool(self, specs): + specs = frozenset(specs) + if specs in self._pool_cache: + pool = self._pool_cache[specs] + else: + pool = self.get_reduced_index(specs) + grouped_pool = groupby(lambda x: x.name, pool) + pool = {k: set(v) for k, v in grouped_pool.items()} + self._pool_cache[specs] = pool + return pool + + @time_recorder(module_name=__name__) + def get_reduced_index( + self, explicit_specs, sort_by_exactness=True, exit_on_conflict=False + ): + strict_channel_priority = context.channel_priority == ChannelPriority.STRICT + + cache_key = strict_channel_priority, tuple(explicit_specs) + if cache_key in self._reduced_index_cache: + return self._reduced_index_cache[cache_key] + + if log.isEnabledFor(DEBUG): + log.debug( + "Retrieving packages for: %s", + dashlist(sorted(str(s) for s in explicit_specs)), + ) + + explicit_specs, features = self.verify_specs(explicit_specs) + filter_out = { + prec: False if val else "feature not enabled" + for prec, val in self.default_filter(features).items() + } + snames = set() + top_level_spec = None + cp_filter_applied = set() # values are package names + if sort_by_exactness: + # prioritize specs that are more exact. Exact specs will evaluate to 3, + # constrained specs will evaluate to 2, and name only will be 1 + explicit_specs = sorted( + list(explicit_specs), + key=lambda x: (exactness_and_number_of_deps(self, x), x.dist_str()), + reverse=True, + ) + # tuple because it needs to be hashable + explicit_specs = tuple(explicit_specs) + + explicit_spec_package_pool = {} + for s in explicit_specs: + explicit_spec_package_pool[s.name] = explicit_spec_package_pool.get( + s.name, set() + ) | set(self.find_matches(s)) + + def filter_group(_specs): + # all _specs should be for the same package name + name = next(iter(_specs)).name + group = self.groups.get(name, ()) + + # implement strict channel priority + if group and strict_channel_priority and name not in cp_filter_applied: + sole_source_channel_name = self._get_strict_channel(name) + for prec in group: + if prec.channel.name != sole_source_channel_name: + filter_out[prec] = "removed due to strict channel priority" + cp_filter_applied.add(name) + + # Prune packages that don't match any of the patterns, + # have unsatisfiable dependencies, or conflict with the explicit specs + nold = nnew = 0 + for prec in group: + if not filter_out.setdefault(prec, False): + nold += 1 + if (not self.match_any(_specs, prec)) or ( + explicit_spec_package_pool.get(name) + and prec not in explicit_spec_package_pool[name] + ): + filter_out[prec] = ( + f"incompatible with required spec {top_level_spec}" + ) + continue + unsatisfiable_dep_specs = set() + for ms in self.ms_depends(prec): + if not ms.optional and not any( + rec + for rec in self.find_matches(ms) + if not filter_out.get(rec, False) + ): + unsatisfiable_dep_specs.add(ms) + if unsatisfiable_dep_specs: + filter_out[prec] = "unsatisfiable dependencies {}".format( + " ".join(str(s) for s in unsatisfiable_dep_specs) + ) + continue + filter_out[prec] = False + nnew += 1 + + reduced = nnew < nold + if reduced: + log.debug("%s: pruned from %d -> %d" % (name, nold, nnew)) + if any(ms.optional for ms in _specs): + return reduced + elif nnew == 0: + # Indicates that a conflict was found; we can exit early + return None + + # Perform the same filtering steps on any dependencies shared across + # *all* packages in the group. Even if just one of the packages does + # not have a particular dependency, it must be ignored in this pass. + # Otherwise, we might do more filtering than we should---and it is + # better to have extra packages here than missing ones. + if reduced or name not in snames: + snames.add(name) + + _dep_specs = groupby( + lambda s: s.name, + ( + dep_spec + for prec in group + if not filter_out.get(prec, False) + for dep_spec in self.ms_depends(prec) + if not dep_spec.optional + ), + ) + _dep_specs.pop("*", None) # discard track_features specs + + for deps_name, deps in sorted( + _dep_specs.items(), key=lambda x: any(_.optional for _ in x[1]) + ): + if len(deps) >= nnew: + res = filter_group(set(deps)) + if res: + reduced = True + elif res is None: + # Indicates that a conflict was found; we can exit early + return None + + return reduced + + # Iterate on pruning until no progress is made. We've implemented + # what amounts to "double-elimination" here; packages get one additional + # chance after their first "False" reduction. This catches more instances + # where one package's filter affects another. But we don't have to be + # perfect about this, so performance matters. + pruned_to_zero = set() + for _ in range(2): + snames.clear() + slist = deque(explicit_specs) + while slist: + s = slist.popleft() + if filter_group([s]): + slist.append(s) + else: + pruned_to_zero.add(s) + + if pruned_to_zero and exit_on_conflict: + return {} + + # Determine all valid packages in the dependency graph + reduced_index2 = { + prec: prec for prec in (PackageRecord.feature(name) for name in features) + } + specs_by_name_seed = {} + for s in explicit_specs: + specs_by_name_seed[s.name] = specs_by_name_seed.get(s.name, []) + [s] + for explicit_spec in explicit_specs: + add_these_precs2 = tuple( + prec + for prec in self.find_matches(explicit_spec) + if prec not in reduced_index2 and self.valid2(prec, filter_out) + ) + + if strict_channel_priority and add_these_precs2: + strict_channel_name = self._get_strict_channel(add_these_precs2[0].name) + + add_these_precs2 = tuple( + prec + for prec in add_these_precs2 + if prec.channel.name == strict_channel_name + ) + reduced_index2.update((prec, prec) for prec in add_these_precs2) + + for pkg in add_these_precs2: + # what we have seen is only relevant within the context of a single package + # that is picked up because of an explicit spec. We don't want the + # broadening check to apply across packages at the explicit level; only + # at the level of deps below that explicit package. + seen_specs = set() + specs_by_name = copy.deepcopy(specs_by_name_seed) + + dep_specs = set(self.ms_depends(pkg)) + for dep in dep_specs: + specs = specs_by_name.get(dep.name, []) + if dep not in specs and ( + not specs or dep.strictness >= specs[0].strictness + ): + specs.insert(0, dep) + specs_by_name[dep.name] = specs + + while dep_specs: + # used for debugging + # size_index = len(reduced_index2) + # specs_added = [] + ms = dep_specs.pop() + seen_specs.add(ms) + for dep_pkg in ( + _ for _ in self.find_matches(ms) if _ not in reduced_index2 + ): + if not self.valid2(dep_pkg, filter_out): + continue + + # expand the reduced index if not using strict channel priority, + # or if using it and this package is in the appropriate channel + if not strict_channel_priority or ( + self._get_strict_channel(dep_pkg.name) + == dep_pkg.channel.name + ): + reduced_index2[dep_pkg] = dep_pkg + + # recurse to deps of this dep + new_specs = set(self.ms_depends(dep_pkg)) - seen_specs + for new_ms in new_specs: + # We do not pull packages into the reduced index due + # to a track_features dependency. Remember, a feature + # specifies a "soft" dependency: it must be in the + # environment, but it is not _pulled_ in. The SAT + # logic doesn't do a perfect job of capturing this + # behavior, but keeping these packags out of the + # reduced index helps. Of course, if _another_ + # package pulls it in by dependency, that's fine. + if "track_features" not in new_ms and not self._broader( + new_ms, + tuple(specs_by_name.get(new_ms.name, ())), + ): + dep_specs.add(new_ms) + # if new_ms not in dep_specs: + # specs_added.append(new_ms) + else: + seen_specs.add(new_ms) + # debugging info - see what specs are bringing in the largest blobs + # if size_index != len(reduced_index2): + # print("MS {} added {} pkgs to index".format(ms, + # len(reduced_index2) - size_index)) + # if specs_added: + # print("MS {} added {} specs to further examination".format(ms, + # specs_added)) + + reduced_index2 = frozendict(reduced_index2) + self._reduced_index_cache[cache_key] = reduced_index2 + return reduced_index2 + + def match_any(self, mss, prec): + return any(ms.match(prec) for ms in mss) + + def find_matches(self, spec: MatchSpec) -> tuple[PackageRecord]: + res = self._cached_find_matches.get(spec, None) + if res is not None: + return res + + spec_name = spec.get_exact_value("name") + if spec_name: + candidate_precs = self.groups.get(spec_name, ()) + elif spec.get_exact_value("track_features"): + feature_names = spec.get_exact_value("track_features") + candidate_precs = itertools.chain.from_iterable( + self.trackers.get(feature_name, ()) for feature_name in feature_names + ) + else: + candidate_precs = self.index.values() + + res = tuple(p for p in candidate_precs if spec.match(p)) + self._cached_find_matches[spec] = res + return res + + def ms_depends(self, prec: PackageRecord) -> list[MatchSpec]: + deps = self.ms_depends_.get(prec) + if deps is None: + deps = [MatchSpec(d) for d in prec.combined_depends] + deps.extend(MatchSpec(track_features=feat) for feat in prec.features) + self.ms_depends_[prec] = deps + return deps + + def version_key(self, prec, vtype=None): + channel = prec.channel + channel_priority = self._channel_priorities_map.get( + channel.name, 1 + ) # TODO: ask @mcg1969 why the default value is 1 here + valid = 1 if channel_priority < MAX_CHANNEL_PRIORITY else 0 + version_comparator = VersionOrder(prec.get("version", "")) + build_number = prec.get("build_number", 0) + build_string = prec.get("build") + noarch = -int(prec.subdir == "noarch") + if self._channel_priority != ChannelPriority.DISABLED: + vkey = [valid, -channel_priority, version_comparator, build_number, noarch] + else: + vkey = [valid, version_comparator, -channel_priority, build_number, noarch] + if self._solver_ignore_timestamps: + vkey.append(build_string) + else: + vkey.extend((prec.get("timestamp", 0), build_string)) + return vkey + + @staticmethod + def _make_channel_priorities(channels: Iterable[Channel | str]) -> dict[str, int]: + priorities_map = {} + """Make a dictionary of channel priorities. + + Maps channel names to priorities, e.g.: + + .. code-block:: pycon + + >>> Resolve._make_channel_priorities(["conda-canary", "defaults", "conda-forge"]) + { + 'conda-canary': 0, + 'pkgs/main': 1, + 'pkgs/r': 2, + 'conda-forge': 3, + } + + Compare with ``conda.models.channel.prioritize_channels``. + """ + channel_names = ( + channel.name for name in channels for channel in Channel(name).channels + ) + for priority_counter, channel_name in enumerate(channel_names): + if channel_name in priorities_map: + continue + priorities_map[channel_name] = min( + priority_counter, MAX_CHANNEL_PRIORITY - 1 + ) + return priorities_map + + def get_pkgs(self, ms, emptyok=False): # pragma: no cover + # legacy method for conda-build + ms = MatchSpec(ms) + precs = self.find_matches(ms) + if not precs and not emptyok: + raise ResolvePackageNotFound([(ms,)]) + return sorted(precs, key=self.version_key) + + @staticmethod + def to_sat_name(val): + # val can be a PackageRecord or MatchSpec + if isinstance(val, PackageRecord): + return val.dist_str() + elif isinstance(val, MatchSpec): + return "@s@" + str(val) + ("?" if val.optional else "") + else: + raise NotImplementedError() + + @staticmethod + def to_feature_metric_id(prec_dist_str, feat): + return f"@fm@{prec_dist_str}@{feat}" + + def push_MatchSpec(self, C, spec): + spec = MatchSpec(spec) + sat_name = self.to_sat_name(spec) + m = C.from_name(sat_name) + if m is not None: + # the spec has already been pushed onto the clauses stack + return sat_name + + simple = spec._is_single() + nm = spec.get_exact_value("name") + tf = frozenset( + _tf + for _tf in (f.strip() for f in spec.get_exact_value("track_features") or ()) + if _tf + ) + + if nm: + tgroup = libs = self.groups.get(nm, []) + elif tf: + if len(tf) != 1: + raise RuntimeError + k = next(iter(tf)) + tgroup = libs = self.trackers.get(k, []) + else: + tgroup = libs = self.index.keys() + simple = False + if not simple: + libs = [fkey for fkey in tgroup if spec.match(fkey)] + if len(libs) == len(tgroup): + if spec.optional: + m = TRUE + elif not simple: + ms2 = MatchSpec(track_features=tf) if tf else MatchSpec(nm) + m = C.from_name(self.push_MatchSpec(C, ms2)) + if m is None: + sat_names = [self.to_sat_name(prec) for prec in libs] + if spec.optional: + ms2 = MatchSpec(track_features=tf) if tf else MatchSpec(nm) + sat_names.append("!" + self.to_sat_name(ms2)) + m = C.Any(sat_names) + C.name_var(m, sat_name) + return sat_name + + @time_recorder(module_name=__name__) + def gen_clauses(self): + C = Clauses(sat_solver=_get_sat_solver_cls(context.sat_solver)) + for name, group in self.groups.items(): + group = [self.to_sat_name(prec) for prec in group] + # Create one variable for each package + for sat_name in group: + C.new_var(sat_name) + # Create one variable for the group + m = C.new_var(self.to_sat_name(MatchSpec(name))) + + # Exactly one of the package variables, OR + # the negation of the group variable, is true + C.Require(C.ExactlyOne, group + [C.Not(m)]) + + # If a package is installed, its dependencies must be as well + for prec in self.index.values(): + nkey = C.Not(self.to_sat_name(prec)) + for ms in self.ms_depends(prec): + # Virtual packages can't be installed, we ignore them + if not ms.name.startswith("__"): + C.Require(C.Or, nkey, self.push_MatchSpec(C, ms)) + + if log.isEnabledFor(DEBUG): + log.debug( + "gen_clauses returning with clause count: %d", C.get_clause_count() + ) + return C + + def generate_spec_constraints(self, C, specs): + result = [(self.push_MatchSpec(C, ms),) for ms in specs] + if log.isEnabledFor(DEBUG): + log.debug( + "generate_spec_constraints returning with clause count: %d", + C.get_clause_count(), + ) + return result + + def generate_feature_count(self, C): + result = { + self.push_MatchSpec(C, MatchSpec(track_features=name)): 1 + for name in self.trackers.keys() + } + if log.isEnabledFor(DEBUG): + log.debug( + "generate_feature_count returning with clause count: %d", + C.get_clause_count(), + ) + return result + + def generate_update_count(self, C, specs): + return { + "!" + ms.target: 1 for ms in specs if ms.target and C.from_name(ms.target) + } + + def generate_feature_metric(self, C): + eq = {} # a C.minimize() objective: dict[varname, coeff] + # Given a pair (prec, feature), assign a "1" score IF: + # - The prec is installed + # - The prec does NOT require the feature + # - At least one package in the group DOES require the feature + # - A package that tracks the feature is installed + for name, group in self.groups.items(): + prec_feats = {self.to_sat_name(prec): set(prec.features) for prec in group} + active_feats = set.union(*prec_feats.values()).intersection(self.trackers) + for feat in active_feats: + clause_id_for_feature = self.push_MatchSpec( + C, MatchSpec(track_features=feat) + ) + for prec_sat_name, features in prec_feats.items(): + if feat not in features: + feature_metric_id = self.to_feature_metric_id( + prec_sat_name, feat + ) + C.name_var( + C.And(prec_sat_name, clause_id_for_feature), + feature_metric_id, + ) + eq[feature_metric_id] = 1 + return eq + + def generate_removal_count(self, C, specs): + return {"!" + self.push_MatchSpec(C, ms.name): 1 for ms in specs} + + def generate_install_count(self, C, specs): + return {self.push_MatchSpec(C, ms.name): 1 for ms in specs if ms.optional} + + def generate_package_count(self, C, missing): + return {self.push_MatchSpec(C, nm): 1 for nm in missing} + + def generate_version_metrics(self, C, specs, include0=False): + # each of these are weights saying how well packages match the specs + # format for each: a C.minimize() objective: dict[varname, coeff] + eqc = {} # channel + eqv = {} # version + eqb = {} # build number + eqa = {} # arch/noarch + eqt = {} # timestamp + + sdict = {} # dict[package_name, PackageRecord] + + for s in specs: + s = MatchSpec(s) # needed for testing + sdict.setdefault(s.name, []) + # # TODO: this block is important! can't leave it commented out + # rec = sdict.setdefault(s.name, []) + # if s.target: + # dist = Dist(s.target) + # if dist in self.index: + # if self.index[dist].get('priority', 0) < MAX_CHANNEL_PRIORITY: + # rec.append(dist) + + for name, targets in sdict.items(): + pkgs = [(self.version_key(p), p) for p in self.groups.get(name, [])] + pkey = None + # keep in mind that pkgs is already sorted according to version_key (a tuple, + # so composite sort key). Later entries in the list are, by definition, + # greater in some way, so simply comparing with != suffices. + for version_key, prec in pkgs: + if targets and any(prec == t for t in targets): + continue + if pkey is None: + ic = iv = ib = it = ia = 0 + # valid package, channel priority + elif pkey[0] != version_key[0] or pkey[1] != version_key[1]: + ic += 1 + iv = ib = it = ia = 0 + # version + elif pkey[2] != version_key[2]: + iv += 1 + ib = it = ia = 0 + # build number + elif pkey[3] != version_key[3]: + ib += 1 + it = ia = 0 + # arch/noarch + elif pkey[4] != version_key[4]: + ia += 1 + it = 0 + elif not self._solver_ignore_timestamps and pkey[5] != version_key[5]: + it += 1 + + prec_sat_name = self.to_sat_name(prec) + if ic or include0: + eqc[prec_sat_name] = ic + if iv or include0: + eqv[prec_sat_name] = iv + if ib or include0: + eqb[prec_sat_name] = ib + if ia or include0: + eqa[prec_sat_name] = ia + if it or include0: + eqt[prec_sat_name] = it + pkey = version_key + + return eqc, eqv, eqb, eqa, eqt + + def dependency_sort( + self, + must_have: dict[str, PackageRecord], + ) -> list[PackageRecord]: + if not isinstance(must_have, dict): + raise TypeError("'must_have' must be a dict.") + + digraph = {} # dict[str, set[dependent_package_names]] + for package_name, prec in must_have.items(): + if prec in self.index: + digraph[package_name] = {ms.name for ms in self.ms_depends(prec)} + + # There are currently at least three special cases to be aware of. + # 1. The `toposort()` function, called below, contains special case code to remove + # any circular dependency between python and pip. + # 2. conda/plan.py has special case code for menuinst + # Always link/unlink menuinst first/last on windows in case a subsequent + # package tries to import it to create/remove a shortcut + # 3. On windows, python noarch packages need an implicit dependency on conda added, if + # conda is in the list of packages for the environment. Python noarch packages + # that have entry points use conda's own conda.exe python entry point binary. If conda + # is going to be updated during an operation, the unlink / link order matters. + # See issue #6057. + + if on_win and "conda" in digraph: + for package_name, dist in must_have.items(): + record = self.index.get(prec) + if hasattr(record, "noarch") and record.noarch == NoarchType.python: + digraph[package_name].add("conda") + + sorted_keys = toposort(digraph) + must_have = must_have.copy() + # Take all of the items in the sorted keys + # Don't fail if the key does not exist + result = [must_have.pop(key) for key in sorted_keys if key in must_have] + # Take any key that were not sorted + result.extend(must_have.values()) + return result + + def environment_is_consistent(self, installed): + log.debug("Checking if the current environment is consistent") + if not installed: + return None, [] + sat_name_map = {} # dict[sat_name, PackageRecord] + specs = [] + for prec in installed: + sat_name_map[self.to_sat_name(prec)] = prec + specs.append(MatchSpec(f"{prec.name} {prec.version} {prec.build}")) + r2 = Resolve({prec: prec for prec in installed}, True, channels=self.channels) + C = r2.gen_clauses() + constraints = r2.generate_spec_constraints(C, specs) + solution = C.sat(constraints) + return bool(solution) + + def get_conflicting_specs(self, specs, explicit_specs): + if not specs: + return () + + all_specs = set(specs) | set(explicit_specs) + reduced_index = self.get_reduced_index(all_specs) + + # Check if satisfiable + def mysat(specs, add_if=False): + constraints = r2.generate_spec_constraints(C, specs) + return C.sat(constraints, add_if) + + if reduced_index: + r2 = Resolve(reduced_index, True, channels=self.channels) + C = r2.gen_clauses() + solution = mysat(all_specs, True) + else: + solution = None + + if solution: + final_unsat_specs = () + elif context.unsatisfiable_hints: + r2 = Resolve(self.index, True, channels=self.channels) + C = r2.gen_clauses() + # This first result is just a single unsatisfiable core. There may be several. + final_unsat_specs = tuple( + minimal_unsatisfiable_subset( + specs, sat=mysat, explicit_specs=explicit_specs + ) + ) + else: + final_unsat_specs = None + return final_unsat_specs + + def bad_installed(self, installed, new_specs): + log.debug("Checking if the current environment is consistent") + if not installed: + return None, [] + sat_name_map = {} # dict[sat_name, PackageRecord] + specs = [] + for prec in installed: + sat_name_map[self.to_sat_name(prec)] = prec + specs.append(MatchSpec(f"{prec.name} {prec.version} {prec.build}")) + new_index = {prec: prec for prec in sat_name_map.values()} + name_map = {p.name: p for p in new_index} + if "python" in name_map and "pip" not in name_map: + python_prec = new_index[name_map["python"]] + if "pip" in python_prec.depends: + # strip pip dependency from python if not installed in environment + new_deps = [d for d in python_prec.depends if d != "pip"] + python_prec.depends = new_deps + r2 = Resolve(new_index, True, channels=self.channels) + C = r2.gen_clauses() + constraints = r2.generate_spec_constraints(C, specs) + solution = C.sat(constraints) + limit = xtra = None + if not solution or xtra: + + def get_(name, snames): + if name not in snames: + snames.add(name) + for fn in self.groups.get(name, []): + for ms in self.ms_depends(fn): + get_(ms.name, snames) + + # New addition: find the largest set of installed packages that + # are consistent with each other, and include those in the + # list of packages to maintain consistency with + snames = set() + eq_optional_c = r2.generate_removal_count(C, specs) + solution, _ = C.minimize(eq_optional_c, C.sat()) + snames.update( + sat_name_map[sat_name]["name"] + for sat_name in (C.from_index(s) for s in solution) + if sat_name and sat_name[0] != "!" and "@" not in sat_name + ) + # Existing behavior: keep all specs and their dependencies + for spec in new_specs: + get_(MatchSpec(spec).name, snames) + if len(snames) < len(sat_name_map): + limit = snames + xtra = [ + rec + for sat_name, rec in sat_name_map.items() + if rec["name"] not in snames + ] + log.debug( + "Limiting solver to the following packages: %s", ", ".join(limit) + ) + if xtra: + log.debug("Packages to be preserved: %s", xtra) + return limit, xtra + + def restore_bad(self, pkgs, preserve): + if preserve: + sdict = {prec.name: prec for prec in pkgs} + pkgs.extend(p for p in preserve if p.name not in sdict) + + def install_specs(self, specs, installed, update_deps=True): + specs = list(map(MatchSpec, specs)) + snames = {s.name for s in specs} + log.debug("Checking satisfiability of current install") + limit, preserve = self.bad_installed(installed, specs) + for prec in installed: + if prec not in self.index: + continue + name, version, build = prec.name, prec.version, prec.build + schannel = prec.channel.canonical_name + if name in snames or limit is not None and name not in limit: + continue + # If update_deps=True, set the target package in MatchSpec so that + # the solver can minimize the version change. If update_deps=False, + # fix the version and build so that no change is possible. + if update_deps: + # TODO: fix target here + spec = MatchSpec(name=name, target=prec.dist_str()) + else: + spec = MatchSpec( + name=name, version=version, build=build, channel=schannel + ) + specs.insert(0, spec) + return tuple(specs), preserve + + def install(self, specs, installed=None, update_deps=True, returnall=False): + specs, preserve = self.install_specs(specs, installed or [], update_deps) + pkgs = [] + if specs: + pkgs = self.solve(specs, returnall=returnall, _remove=False) + self.restore_bad(pkgs, preserve) + return pkgs + + def remove_specs(self, specs, installed): + nspecs = [] + # There's an imperfect thing happening here. "specs" nominally contains + # a list of package names or track_feature values to be removed. But + # because of add_defaults_to_specs it may also contain version constraints + # like "python 2.7*", which are *not* asking for python to be removed. + # We need to separate these two kinds of specs here. + for s in map(MatchSpec, specs): + # Since '@' is an illegal version number, this ensures that all of + # these matches will never match an actual package. Combined with + # optional=True, this has the effect of forcing their removal. + if s._is_single(): + nspecs.append(MatchSpec(s, version="@", optional=True)) + else: + nspecs.append(MatchSpec(s, optional=True)) + snames = {s.name for s in nspecs if s.name} + limit, _ = self.bad_installed(installed, nspecs) + preserve = [] + for prec in installed: + nm, ver = prec.name, prec.version + if nm in snames: + continue + elif limit is not None: + preserve.append(prec) + else: + # TODO: fix target here + nspecs.append( + MatchSpec( + name=nm, + version=">=" + ver if ver else None, + optional=True, + target=prec.dist_str(), + ) + ) + return nspecs, preserve + + def remove(self, specs, installed): + specs, preserve = self.remove_specs(specs, installed) + pkgs = self.solve(specs, _remove=True) + self.restore_bad(pkgs, preserve) + return pkgs + + @time_recorder(module_name=__name__) + def solve( + self, + specs: list, + returnall: bool = False, + _remove=False, + specs_to_add=None, + history_specs=None, + should_retry_solve=False, + ) -> list[PackageRecord]: + if specs and not isinstance(specs[0], MatchSpec): + specs = tuple(MatchSpec(_) for _ in specs) + + specs = set(specs) + if log.isEnabledFor(DEBUG): + dlist = dashlist( + str("%i: %s target=%s optional=%s" % (i, s, s.target, s.optional)) + for i, s in enumerate(specs) + ) + log.debug("Solving for: %s", dlist) + + if not specs: + return () + + # Find the compliant packages + log.debug("Solve: Getting reduced index of compliant packages") + len0 = len(specs) + + reduced_index = self.get_reduced_index( + specs, exit_on_conflict=not context.unsatisfiable_hints + ) + if not reduced_index: + # something is intrinsically unsatisfiable - either not found or + # not the right version + not_found_packages = set() + wrong_version_packages = set() + for s in specs: + if not self.find_matches(s): + if s.name in self.groups: + wrong_version_packages.add(s) + else: + not_found_packages.add(s) + if not_found_packages: + raise ResolvePackageNotFound(not_found_packages) + elif wrong_version_packages: + raise UnsatisfiableError( + [[d] for d in wrong_version_packages], chains=False + ) + if should_retry_solve: + # We don't want to call find_conflicts until our last try. + # This jumps back out to conda/cli/install.py, where the + # retries happen + raise UnsatisfiableError({}) + else: + self.find_conflicts(specs, specs_to_add, history_specs) + + # Check if satisfiable + log.debug("Solve: determining satisfiability") + + def mysat(specs, add_if=False): + constraints = r2.generate_spec_constraints(C, specs) + return C.sat(constraints, add_if) + + # Return a solution of packages + def clean(sol): + return [ + q + for q in (C.from_index(s) for s in sol) + if q and q[0] != "!" and "@" not in q + ] + + def is_converged(solution): + """Determine if the SAT problem has converged to a single solution. + + This is determined by testing for a SAT solution with the current + clause set and a clause in which at least one of the packages in + the current solution is excluded. If a solution exists the problem + has not converged as multiple solutions still exist. + """ + psolution = clean(solution) + nclause = tuple(C.Not(C.from_name(q)) for q in psolution) + if C.sat((nclause,), includeIf=False) is None: + return True + return False + + r2 = Resolve(reduced_index, True, channels=self.channels) + C = r2.gen_clauses() + solution = mysat(specs, True) + if not solution: + if should_retry_solve: + # we don't want to call find_conflicts until our last try + raise UnsatisfiableError({}) + else: + self.find_conflicts(specs, specs_to_add, history_specs) + + speco = [] # optional packages + specr = [] # requested packages + speca = [] # all other packages + specm = set(r2.groups) # missing from specs + for k, s in enumerate(specs): + if s.name in specm: + specm.remove(s.name) + if not s.optional: + (speca if s.target or k >= len0 else specr).append(s) + elif any(r2.find_matches(s)): + s = MatchSpec(s.name, optional=True, target=s.target) + speco.append(s) + speca.append(s) + speca.extend(MatchSpec(s) for s in specm) + + if log.isEnabledFor(DEBUG): + log.debug("Requested specs: %s", dashlist(sorted(str(s) for s in specr))) + log.debug("Optional specs: %s", dashlist(sorted(str(s) for s in speco))) + log.debug("All other specs: %s", dashlist(sorted(str(s) for s in speca))) + log.debug("missing specs: %s", dashlist(sorted(str(s) for s in specm))) + + # Removed packages: minimize count + log.debug("Solve: minimize removed packages") + if _remove: + eq_optional_c = r2.generate_removal_count(C, speco) + solution, obj7 = C.minimize(eq_optional_c, solution) + log.debug("Package removal metric: %d", obj7) + + # Requested packages: maximize versions + log.debug("Solve: maximize versions of requested packages") + eq_req_c, eq_req_v, eq_req_b, eq_req_a, eq_req_t = r2.generate_version_metrics( + C, specr + ) + solution, obj3a = C.minimize(eq_req_c, solution) + solution, obj3 = C.minimize(eq_req_v, solution) + log.debug("Initial package channel/version metric: %d/%d", obj3a, obj3) + + # Track features: minimize feature count + log.debug("Solve: minimize track_feature count") + eq_feature_count = r2.generate_feature_count(C) + solution, obj1 = C.minimize(eq_feature_count, solution) + log.debug("Track feature count: %d", obj1) + + # Featured packages: minimize number of featureless packages + # installed when a featured alternative is feasible. + # For example, package name foo exists with two built packages. One with + # 'track_features: 'feat1', and one with 'track_features': 'feat2'. + # The previous "Track features" minimization pass has chosen 'feat1' for the + # environment, but not 'feat2'. In this case, the 'feat2' version of foo is + # considered "featureless." + eq_feature_metric = r2.generate_feature_metric(C) + solution, obj2 = C.minimize(eq_feature_metric, solution) + log.debug("Package misfeature count: %d", obj2) + + # Requested packages: maximize builds + log.debug("Solve: maximize build numbers of requested packages") + solution, obj4 = C.minimize(eq_req_b, solution) + log.debug("Initial package build metric: %d", obj4) + + # prefer arch packages where available for requested specs + log.debug("Solve: prefer arch over noarch for requested packages") + solution, noarch_obj = C.minimize(eq_req_a, solution) + log.debug("Noarch metric: %d", noarch_obj) + + # Optional installations: minimize count + if not _remove: + log.debug("Solve: minimize number of optional installations") + eq_optional_install = r2.generate_install_count(C, speco) + solution, obj49 = C.minimize(eq_optional_install, solution) + log.debug("Optional package install metric: %d", obj49) + + # Dependencies: minimize the number of packages that need upgrading + log.debug("Solve: minimize number of necessary upgrades") + eq_u = r2.generate_update_count(C, speca) + solution, obj50 = C.minimize(eq_u, solution) + log.debug("Dependency update count: %d", obj50) + + # Remaining packages: maximize versions, then builds + log.debug( + "Solve: maximize versions and builds of indirect dependencies. " + "Prefer arch over noarch where equivalent." + ) + eq_c, eq_v, eq_b, eq_a, eq_t = r2.generate_version_metrics(C, speca) + solution, obj5a = C.minimize(eq_c, solution) + solution, obj5 = C.minimize(eq_v, solution) + solution, obj6 = C.minimize(eq_b, solution) + solution, obj6a = C.minimize(eq_a, solution) + log.debug( + "Additional package channel/version/build/noarch metrics: %d/%d/%d/%d", + obj5a, + obj5, + obj6, + obj6a, + ) + + # Prune unnecessary packages + log.debug("Solve: prune unnecessary packages") + eq_c = r2.generate_package_count(C, specm) + solution, obj7 = C.minimize(eq_c, solution, trymax=True) + log.debug("Weak dependency count: %d", obj7) + + if not is_converged(solution): + # Maximize timestamps + eq_t.update(eq_req_t) + solution, obj6t = C.minimize(eq_t, solution) + log.debug("Timestamp metric: %d", obj6t) + + log.debug("Looking for alternate solutions") + nsol = 1 + psolutions = [] + psolution = clean(solution) + psolutions.append(psolution) + while True: + nclause = tuple(C.Not(C.from_name(q)) for q in psolution) + solution = C.sat((nclause,), True) + if solution is None: + break + nsol += 1 + if nsol > 10: + log.debug("Too many solutions; terminating") + break + psolution = clean(solution) + psolutions.append(psolution) + + if nsol > 1: + psols2 = list(map(set, psolutions)) + common = set.intersection(*psols2) + diffs = [sorted(set(sol) - common) for sol in psols2] + if not context.json: + stdoutlog.info( + "\nWarning: {} possible package resolutions " + "(only showing differing packages):{}{}".format( + ">10" if nsol > 10 else nsol, + dashlist(", ".join(diff) for diff in diffs), + "\n ... and others" if nsol > 10 else "", + ) + ) + + # def stripfeat(sol): + # return sol.split('[')[0] + + new_index = {self.to_sat_name(prec): prec for prec in self.index.values()} + + if returnall: + if len(psolutions) > 1: + raise RuntimeError() + # TODO: clean up this mess + # return [sorted(Dist(stripfeat(dname)) for dname in psol) for psol in psolutions] + # return [sorted((new_index[sat_name] for sat_name in psol), key=lambda x: x.name) + # for psol in psolutions] + + # return sorted(Dist(stripfeat(dname)) for dname in psolutions[0]) + return sorted( + (new_index[sat_name] for sat_name in psolutions[0]), key=lambda x: x.name + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat new file mode 100644 index 0000000000000000000000000000000000000000..c8ee68989b53660ff2016bac41cd2d6fdc920fb4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat @@ -0,0 +1,3 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +@CALL "%~dp0..\..\condabin\conda.bat" %* diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/Scripts/activate.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/Scripts/activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..99a7d88a79d24ca40a7da6c16482af6f6167435b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/Scripts/activate.bat @@ -0,0 +1,28 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +:: Test first character and last character of %1 to see if first character is a " +:: but the last character isn't. +:: This was a bug as described in https://github.com/ContinuumIO/menuinst/issues/60 +:: When Anaconda Prompt has the form +:: %windir%\system32\cmd.exe "/K" "C:\Users\builder\Miniconda3\Scripts\activate.bat" "C:\Users\builder\Miniconda3" +:: Rather than the correct +:: %windir%\system32\cmd.exe /K ""C:\Users\builder\Miniconda3\Scripts\activate.bat" "C:\Users\builder\Miniconda3"" +:: this solution taken from https://stackoverflow.com/a/31359867 +@SET "_args1=%1" +@SET _args1_first=%_args1:~0,1% +@SET _args1_last=%_args1:~-1% +@SET _args1_first=%_args1_first:"=+% +@SET _args1_last=%_args1_last:"=+% +@SET _args1= + +@IF "%_args1_first%"=="+" IF NOT "%_args1_last%"=="+" @( + @CALL "%~dp0..\condabin\conda.bat" activate + @GOTO :CLEANUP +) + +:: This may work if there are spaces in anything in %* +@CALL "%~dp0..\condabin\conda.bat" activate %* + +:CLEANUP +@SET _args1_first= +@SET _args1_last= diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/bin/activate b/miniconda3/lib/python3.13/site-packages/conda/shell/bin/activate new file mode 100644 index 0000000000000000000000000000000000000000..4cebf4d7698577655a38e1823a3a2c4631ebc99b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/bin/activate @@ -0,0 +1,4 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +\. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $? +conda activate "$@" diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/bin/deactivate b/miniconda3/lib/python3.13/site-packages/conda/shell/bin/deactivate new file mode 100644 index 0000000000000000000000000000000000000000..116a6f5798c242699130ab91ad4edb85ac39235a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/bin/deactivate @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +\echo >&2 "DeprecationWarning: 'source deactivate' is deprecated. Use 'conda deactivate'." +\. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $? +conda deactivate diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/cli-32.exe b/miniconda3/lib/python3.13/site-packages/conda/shell/cli-32.exe new file mode 100644 index 0000000000000000000000000000000000000000..4e6d4af282b035a588c68ed9364d1f0ef2f53f63 Binary files /dev/null and b/miniconda3/lib/python3.13/site-packages/conda/shell/cli-32.exe differ diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/cli-64.exe b/miniconda3/lib/python3.13/site-packages/conda/shell/cli-64.exe new file mode 100644 index 0000000000000000000000000000000000000000..c62a80ce33c321e43566bc1a5a6731248b4b5ff9 Binary files /dev/null and b/miniconda3/lib/python3.13/site-packages/conda/shell/cli-64.exe differ diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/conda.xsh b/miniconda3/lib/python3.13/site-packages/conda/shell/conda.xsh new file mode 100644 index 0000000000000000000000000000000000000000..088ccab454a981897d58e4157958317230b2e4f9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/conda.xsh @@ -0,0 +1,204 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +# Much of this forked from https://github.com/gforsyth/xonda +# Copyright (c) 2016, Gil Forsyth, All rights reserved. +# Original code licensed under BSD-3-Clause. + +try: + # xonsh >= 0.18.0 + from xonsh.lib.lazyasd import lazyobject +except: + # xonsh < 0.18.0 + from xonsh.lazyasd import lazyobject + +if 'CONDA_EXE' not in ${...}: + ![python -m conda init --dev out> conda-dev-init.sh] + source-bash conda-dev-init.sh + import os + os.remove("conda-dev-init.sh") + +_REACTIVATE_COMMANDS = ('install', 'update', 'upgrade', 'remove', 'uninstall') + + +@lazyobject +def Env(): + from collections import namedtuple + return namedtuple('Env', ['name', 'path', 'bin_dir', 'envs_dir']) + + +def _parse_args(args=None): + from argparse import ArgumentParser + p = ArgumentParser(add_help=False) + p.add_argument('command', nargs='?') + p.add_argument('-h', '--help', dest='help', action='store_true', default=False) + p.add_argument('-v', '--version', dest='version', action='store_true', default=False) + ns, _ = p.parse_known_args(args) + if ns.command == 'activate': + p.add_argument('env_name_or_prefix', default='base') + elif ns.command in _REACTIVATE_COMMANDS: + p.add_argument('-n', '--name') + p.add_argument('-p', '--prefix') + parsed_args, _ = p.parse_known_args(args) + return parsed_args + + +def _raise_pipeline_error(pipeline): + stdout = pipeline.out + stderr = pipeline.err + if pipeline.returncode != 0: + message = ("exited with %s\nstdout: %s\nstderr: %s\n" + "" % (pipeline.returncode, stdout, stderr)) + raise RuntimeError(message) + return stdout.strip() + + +def _conda_activate_handler(env_name_or_prefix): + import os + + __xonsh__.execer.exec($($CONDA_EXE shell.xonsh activate @(env_name_or_prefix)), + glbs=__xonsh__.ctx, + filename="$(conda shell.xonsh activate " + env_name_or_prefix + ")") + if $CONDA_DEFAULT_ENV != os.path.split(env_name_or_prefix)[1]: + import sys as _sys + + print("WARNING: conda environment not activated properly. " + "This is likely because you have a conda init inside of your " + "~/.bashrc (unix) or *.bat activation file (windows). This is " + "causing conda to activate twice in xonsh. Please remove the conda " + "init block from your other shell.", file=_sys.stderr) + + +def _conda_deactivate_handler(): + __xonsh__.execer.exec($($CONDA_EXE shell.xonsh deactivate), + glbs=__xonsh__.ctx, + filename="$(conda shell.xonsh deactivate)") + + +def _conda_passthrough_handler(args): + pipeline = ![$CONDA_EXE @(args)] + _raise_pipeline_error(pipeline) + + +def _conda_reactivate_handler(args, name_or_prefix_given): + pipeline = ![$CONDA_EXE @(args)] + _raise_pipeline_error(pipeline) + if not name_or_prefix_given: + __xonsh__.execer.exec($($CONDA_EXE shell.xonsh reactivate), + glbs=__xonsh__.ctx, + filename="$(conda shell.xonsh reactivate)") + + +def _conda_main(args=None): + parsed_args = _parse_args(args) + if parsed_args.command == 'activate': + _conda_activate_handler(parsed_args.env_name_or_prefix) + elif parsed_args.command == 'deactivate': + _conda_deactivate_handler() + elif parsed_args.command in _REACTIVATE_COMMANDS: + name_or_prefix_given = bool(parsed_args.name or parsed_args.prefix) + _conda_reactivate_handler(args, name_or_prefix_given) + else: + _conda_passthrough_handler(args) + + +if 'CONDA_SHLVL' not in ${...}: + $CONDA_SHLVL = '0' + import os as _os + import sys as _sys + _sys.path.insert(0, _os.path.join(_os.path.dirname(_os.path.dirname($CONDA_EXE)), "condabin")) + del _os, _sys + +aliases['conda'] = _conda_main + + +def _list_dirs(path): + """Generator that lists the directories in a given path.""" + import os + for entry in os.scandir(path): + if not entry.name.startswith('.') and entry.is_dir(): + yield entry.name + + +def _get_envs_unfiltered(): + """Grab a list of all conda env dirs from conda, allowing all warnings.""" + import os + import importlib + + try: + # breaking changes introduced in Anaconda 4.4.7 + # try to import newer library structure first + context = importlib.import_module('conda.base.context') + config = context.context + except ModuleNotFoundError: + config = importlib.import_module('conda.config') + + # create the list of environments + env_list = [] + for envs_dir in config.envs_dirs: + # skip non-existing environments directories + if not os.path.exists(envs_dir): + continue + # for each environment in the environments directory + for env_name in _list_dirs(envs_dir): + # check for duplicates names + if env_name in [env.name for env in env_list]: + raise ValueError('Multiple environments with the same name ' + "in the system is not supported by conda's xonsh tools.") + # add the environment to the list + env_list.append(Env(name=env_name, + path=os.path.join(envs_dir, env_name), + bin_dir=os.path.join(envs_dir, env_name, 'bin'), + envs_dir=envs_dir, + )) + return env_list + + +def _get_envs(): + """Grab a list of all conda env dirs from conda, ignoring all warnings.""" + import warnings + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return _get_envs_unfiltered() + + +def _conda_completer(prefix, line, start, end, ctx): + """Completion for conda.""" + args = line.split(' ') + possible = set() + if len(args) == 0 or args[0] not in ['xonda', 'conda']: + return None + curix = args.index(prefix) + if curix == 1: + possible = {'activate', 'deactivate', 'install', 'remove', 'info', + 'help', 'list', 'search', 'update', 'upgrade', 'uninstall', + 'config', 'init', 'clean', 'package', 'bundle', 'env', + 'select', 'create', '-h', '--help', '-V', '--version'} + + elif curix == 2: + if args[1] in ['activate', 'select']: + possible = set([env.name for env in _get_envs()]) + elif args[1] == 'create': + possible = {'-p', '-n'} + elif args[1] == 'env': + possible = {'attach', 'create', 'export', 'list', 'remove', + 'upload', 'update'} + + elif curix == 3: + if args[2] == 'export': + possible = {'-n', '--name'} + elif args[2] == 'create': + possible = {'-h', '--help', '-f', '--file', '-n', '--name', '-p', + '--prefix', '-q', '--quiet', '--force', '--json', + '--debug', '-v', '--verbose'} + + elif curix == 4: + if args[2] == 'export' and args[3] in ['-n','--name']: + possible = set([env.name for env in _get_envs()]) + + return {i for i in possible if i.startswith(prefix)} + + +# add _xonda_completer to list of completers +__xonsh__.completers['conda'] = _conda_completer +# bump to top of list +__xonsh__.completers.move_to_end('conda', last=False) diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/Conda.psm1 b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/Conda.psm1 new file mode 100644 index 0000000000000000000000000000000000000000..64f51c1d0c9f04e04658172b606ab4a13ce7a084 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/Conda.psm1 @@ -0,0 +1,266 @@ +param([parameter(Position=0,Mandatory=$false)] [Hashtable] $CondaModuleArgs=@{}) + +# Defaults from before we had arguments. +if (-not $CondaModuleArgs.ContainsKey('ChangePs1')) { + $CondaModuleArgs.ChangePs1 = $True +} + +## ENVIRONMENT MANAGEMENT ###################################################### + +<# + .SYNOPSIS + Obtains a list of valid conda environments. + + .EXAMPLE + Get-CondaEnvironment + + .EXAMPLE + genv +#> +function Get-CondaEnvironment { + [CmdletBinding()] + param(); + + begin {} + + process { + # NB: the JSON output of conda env list does not include the names + # of each env, so we need to parse the fragile output instead. + & $Env:CONDA_EXE $Env:_CE_M $Env:_CE_CONDA env list | ` + Where-Object { -not $_.StartsWith("#") } | ` + Where-Object { -not $_.Trim().Length -eq 0 } | ` + ForEach-Object { + $envLine = $_ -split "\s+"; + $Active = $envLine[1] -eq "*"; + [PSCustomObject] @{ + Name = $envLine[0]; + Active = $Active; + Path = if ($Active) {$envLine[2]} else {$envLine[1]}; + } | Write-Output; + } + } + + end {} +} + +<# + .SYNOPSIS + Activates a conda environment, placing its commands and packages at + the head of $Env:PATH. + + .EXAMPLE + Enter-CondaEnvironment my-env + + .EXAMPLE + etenv my-env + + .NOTES + This command does not currently support activating environments stored + in a non-standard location. +#> +function Enter-CondaEnvironment { + [CmdletBinding()] + param( + [Parameter(Mandatory=$false)][switch]$Stack, + [Parameter(Position=0)][string]$Name + ); + + begin { + If ($Stack) { + $activateCommand = (& $Env:CONDA_EXE $Env:_CE_M $Env:_CE_CONDA shell.powershell activate --stack $Name | Out-String); + } Else { + $activateCommand = (& $Env:CONDA_EXE $Env:_CE_M $Env:_CE_CONDA shell.powershell activate $Name | Out-String); + } + + Write-Verbose "[conda shell.powershell activate $Name]`n$activateCommand"; + Invoke-Expression -Command $activateCommand; + } + + process {} + + end {} + +} + +<# + .SYNOPSIS + Deactivates the current conda environment, if any. + + .EXAMPLE + Exit-CondaEnvironment + + .EXAMPLE + exenv +#> +function Exit-CondaEnvironment { + [CmdletBinding()] + param(); + + begin { + $deactivateCommand = (& $Env:CONDA_EXE $Env:_CE_M $Env:_CE_CONDA shell.powershell deactivate | Out-String); + + # If deactivate returns an empty string, we have nothing more to do, + # so return early. + if ($deactivateCommand.Trim().Length -eq 0) { + return; + } + Write-Verbose "[conda shell.powershell deactivate]`n$deactivateCommand"; + Invoke-Expression -Command $deactivateCommand; + } + process {} + end {} +} + +## CONDA WRAPPER ############################################################### + +<# + .SYNOPSIS + conda is a tool for managing and deploying applications, environments + and packages. + + .PARAMETER Command + Subcommand to invoke. + + .EXAMPLE + conda install toolz +#> +function Invoke-Conda() { + # Don't use any explicit args here, we'll use $args and tab completion + # so that we can capture everything, INCLUDING short options (e.g. -n). + if ($Args.Count -eq 0) { + # No args, just call the underlying conda executable. + & $Env:CONDA_EXE $Env:_CE_M $Env:_CE_CONDA; + } + else { + $Command = $Args[0]; + if ($Args.Count -ge 2) { + $OtherArgs = $Args[1..($Args.Count - 1)]; + } else { + $OtherArgs = @(); + } + switch ($Command) { + "activate" { + Enter-CondaEnvironment @OtherArgs; + } + "deactivate" { + Exit-CondaEnvironment; + } + + default { + # There may be a command we don't know want to handle + # differently in the shell wrapper, pass it through + # verbatim. + & $Env:CONDA_EXE $Env:_CE_M $Env:_CE_CONDA $Command @OtherArgs; + } + } + } +} + +## TAB COMPLETION ############################################################## +# We borrow the approach used by posh-git, in which we override any existing +# functions named TabExpansion, look for commands we can complete on, and then +# default to the previously defined TabExpansion function for everything else. + +if (Test-Path Function:\TabExpansion) { + # Since this technique is common, we encounter an infinite loop if it's + # used more than once unless we give our backup a unique name. + Rename-Item Function:\TabExpansion CondaTabExpansionBackup +} + +function Expand-CondaEnv() { + param( + [string] + $Filter + ); + + $ValidEnvs = Get-CondaEnvironment; + $ValidEnvs ` + | Where-Object { $_.Name -like "$filter*" } ` + | ForEach-Object { $_.Name } ` + | Write-Output; + $ValidEnvs ` + | Where-Object { $_.Path -like "$filter*" } ` + | ForEach-Object { $_.Path } ` + | Write-Output; + +} + +function Expand-CondaSubcommands() { + param( + [string] + $Filter + ); + + # Filter and output applicable subcommands + Invoke-Conda commands | Where-Object { $_ -like "$Filter*" } | Write-Output; + +} + +function TabExpansion($line, $lastWord) { + $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart() + + switch -regex ($lastBlock) { + # Pull out conda commands we recognize first before falling through + # to the general patterns for conda itself. + "^conda activate (.*)" { Expand-CondaEnv $lastWord; break; } + "^etenv (.*)" { Expand-CondaEnv $lastWord; break; } + + # If we got down to here, check arguments to conda itself. + "^conda (.*)" { Expand-CondaSubcommands $lastWord; break; } + + # Finally, fall back on existing tab expansion. + default { + if (Test-Path Function:\CondaTabExpansionBackup) { + CondaTabExpansionBackup $line $lastWord + } + } + } +} + +## PROMPT MANAGEMENT ########################################################### + +<# + .SYNOPSIS + Modifies the current prompt to show the currently activated conda + environment, if any. + .EXAMPLE + Add-CondaEnvironmentToPrompt + + Causes the current session's prompt to display the currently activated + conda environment. +#> +if ($CondaModuleArgs.ChangePs1) { + # We use the same procedure to nest prompts as we did for nested tab completion. + if (Test-Path Function:\prompt) { + Rename-Item Function:\prompt CondaPromptBackup + } else { + function CondaPromptBackup() { + # Restore a basic prompt if the definition is missing. + "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "; + } + } + + function global:prompt() { + if ($Env:CONDA_PROMPT_MODIFIER) { + $Env:CONDA_PROMPT_MODIFIER | Write-Host -NoNewline + } + CondaPromptBackup; + } +} + +## ALIASES ##################################################################### + +New-Alias conda Invoke-Conda -Force +New-Alias genv Get-CondaEnvironment -Force +New-Alias etenv Enter-CondaEnvironment -Force +New-Alias exenv Exit-CondaEnvironment -Force + +## EXPORTS ################################################################### + +Export-ModuleMember ` + -Alias * ` + -Function ` + Invoke-Conda, ` + Get-CondaEnvironment, ` + Enter-CondaEnvironment, Exit-CondaEnvironment, ` + TabExpansion, prompt diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/_conda_activate.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/_conda_activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..15201f718dccf3cfafaa9af571bf1ac30318565e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/_conda_activate.bat @@ -0,0 +1,73 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +:: Helper routine for activation, deactivation, and reactivation. +@ECHO OFF +SETLOCAL + +:: Generate a unique temporary filename using a GUID to support parallel workflows +:: (e.g., `start /b conda run ...`). %RANDOM% is insufficient because processes +:: started simultaneously get identical time-based seeds, producing collisions. +:: See: https://devblogs.microsoft.com/oldnewthing/20100617-00/?p=13673 +FOR /F "delims=" %%G IN ('powershell -NoProfile -Command "[guid]::NewGuid()"') DO SET "__conda_guid=%%G" +SET "__conda_tmp=%TEMP%\__conda_tmp_%__conda_guid%.txt" + +:: Run conda command and get its output +:: WARNING: This cannot be simplified into a FOR /F parsing loop because of the way +:: MSDOS associates the outer quotes for usebackq. E.g., the following: +:: `"%CONDA_EXE%" shell.cmd.exe activate "name"` +:: Which results in the following gibberish being run: +:: %CONDA_EXE%" shell.cmd.exe activate "environment +:: Producing an error like: +:: The filename, directory name, or volume label syntax is incorrect. +:: Instead we run the command and store the output for subsequent processing. +"%CONDA_EXE%" %_CE_M% %_CE_CONDA% shell.cmd.exe %* > "%__conda_tmp%" +IF NOT EXIST "%__conda_tmp%" ( + ECHO ERROR: Failed to create temp file for 'conda %*'.>&2 + ECHO.>&2 + ECHO This is likely a TEMP directory issue>&2 + ECHO ^(permissions, disk space, or invalid path^).>&2 + ECHO.>&2 + ECHO Ensure TEMP or TMP environment variables point to a writable location.>&2 + ECHO See: https://docs.conda.io/projects/conda/en/stable/user-guide/troubleshooting.html#temp-file-errors>&2 + ENDLOCAL & EXIT /B 1 +) ELSE IF %ERRORLEVEL% NEQ 0 ( + ECHO ERROR: 'conda %*' exited with code %ERRORLEVEL%.>&2 + DEL /F /Q "%__conda_tmp%" 2>NUL + ENDLOCAL & EXIT /B 2 +) + +:: Check if conda produced output +FOR /F "delims=" %%T IN (%__conda_tmp%) DO ( + IF NOT EXIST "%%T" ( + ECHO ERROR: Activation file missing for 'conda %*'.>&2 + DEL /F /Q "%__conda_tmp%" 2>NUL + ENDLOCAL & EXIT /B 3 + ) ELSE ENDLOCAL & ( + FOR /F "tokens=1,* delims==" %%A IN (%%T) DO ( + IF "%%A"=="_CONDA_SCRIPT" ( + :: Script execution, fast exit if activation scripts fail + CALL "%%B" || ( + ECHO ERROR: Activation script '%%B' failed with code %ERRORLEVEL%.>&2 + DEL /F /Q "%%T" 2>NUL + DEL /F /Q "%__conda_tmp%" 2>NUL + EXIT /B 4 + ) + ) ELSE IF "%%B"=="" ( + :: Unset variable + SET "%%A=" + ) ELSE ( + :: Set variable + SET "%%A=%%B" + ) + ) + :: Clean up + DEL /F /Q "%%T" 2>NUL + DEL /F /Q "%__conda_tmp%" 2>NUL + EXIT /B 0 + ) +) + +:: If we get here, the FOR loop never ran which means no output +ECHO ERROR: No output from 'conda %*'.>&2 +IF EXIST "%__conda_tmp%" DEL /F /Q "%__conda_tmp%" 2>NUL +ENDLOCAL & EXIT /B 5 diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/activate.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..c49a240735327f9c393839c4bcc0920a391543cf --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/activate.bat @@ -0,0 +1,4 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +@CALL "%~dp0..\condabin\conda_hook.bat" +conda.bat activate %* diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda-hook.ps1 b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda-hook.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..65a911f92ee3debad596dc3e02822978c05c372d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda-hook.ps1 @@ -0,0 +1 @@ +Import-Module "$Env:_CONDA_ROOT\shell\condabin\Conda.psm1" -ArgumentList $CondaModuleArgs diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda.bat new file mode 100644 index 0000000000000000000000000000000000000000..383f50eb60c52f401812acf3d06f615bde9491aa --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda.bat @@ -0,0 +1,23 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause + +@IF NOT DEFINED CONDA_EXE @( + @SET "CONDA_EXE=%~dp0..\Scripts\conda.exe" + @SET _CE_M= + @SET _CE_CONDA= +) +@IF [%1]==[activate] "%~dp0_conda_activate" %* +@IF [%1]==[deactivate] "%~dp0_conda_activate" %* + +@SET CONDA_EXES="%CONDA_EXE%" %_CE_M% %_CE_CONDA% +@CALL %CONDA_EXES% %* + +@IF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL% + +@IF [%1]==[install] "%~dp0_conda_activate" reactivate +@IF [%1]==[update] "%~dp0_conda_activate" reactivate +@IF [%1]==[upgrade] "%~dp0_conda_activate" reactivate +@IF [%1]==[remove] "%~dp0_conda_activate" reactivate +@IF [%1]==[uninstall] "%~dp0_conda_activate" reactivate + +@EXIT /B %ERRORLEVEL% diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda_auto_activate.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda_auto_activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..6e78551fc6b51e3ed53de8e6a8d84ab51d854616 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda_auto_activate.bat @@ -0,0 +1,10 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +:: Helper script to conda_hook.bat. This is a separate script so that the Anaconda Prompt +:: can enable this option while only conda_hook.bat can be used in AutoRun. + +@FOR /F "delims=" %%i IN ('@CALL "%CONDA_EXE%" config --show auto_activate') DO @SET "__conda_auto_activate=%%i" +@FOR /F "delims=" %%i IN ('@CALL "%CONDA_EXE%" config --show default_activation_env') DO @SET "__conda_auto_activate_name=%%i" +@IF NOT "x%__conda_auto_activate:True=%"=="x%__conda_auto_activate%" @CALL "%CONDA_BAT%" activate "%__conda_auto_activate_name:default_activation_env: =%" +@SET "__conda_auto_activate=" +@SET "__conda_auto_activate_name=" diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda_hook.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda_hook.bat new file mode 100644 index 0000000000000000000000000000000000000000..4df22f14af50b0cf6a3f4baeb9892049b5490e46 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/conda_hook.bat @@ -0,0 +1,19 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +:: The file name is conda_hook.bat rather than conda-hook.bat because conda will see +:: the latter as a 'conda hook' command. + +@IF DEFINED CONDA_SHLVL GOTO :EOF + +@FOR %%F IN ("%~dp0") DO @SET "__condabin_dir=%%~dpF" +@SET "__condabin_dir=%__condabin_dir:~0,-1%" +@SET "PATH=%__condabin_dir%;%PATH%" +@SET "CONDA_BAT=%__condabin_dir%\conda.bat" +@FOR %%F IN ("%__condabin_dir%") DO @SET "__conda_root=%%~dpF" +@SET "CONDA_EXE=%__conda_root%Scripts\conda.exe" +@SET __condabin_dir= +@SET __conda_root= + +@DOSKEY conda="%CONDA_BAT%" $* + +@SET CONDA_SHLVL=0 diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/deactivate.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/deactivate.bat new file mode 100644 index 0000000000000000000000000000000000000000..7bf8f53adf2ab0e25e9a08920e48c266410d57b2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/deactivate.bat @@ -0,0 +1,4 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +@ECHO DeprecationWarning: 'deactivate' is deprecated. Use 'conda deactivate'. 1>&2 +conda.bat deactivate %* diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/rename_tmp.bat b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/rename_tmp.bat new file mode 100644 index 0000000000000000000000000000000000000000..417d8fc170fd3a6a8ff3ca89b5916c5d0e7fd312 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/condabin/rename_tmp.bat @@ -0,0 +1,6 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause + +:: Rename src to dest +@PUSHD "%1" +@RENAME "%2" "%3" > NUL 2> NUL diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish b/miniconda3/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish new file mode 100644 index 0000000000000000000000000000000000000000..ea27d135ac1466eecde4d75b4d6305857ca490b0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish @@ -0,0 +1,133 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +# +# INSTALL +# +# Run 'conda init fish' and restart your shell. +# + +if not set -q CONDA_SHLVL + set -gx CONDA_SHLVL 0 + set -g _CONDA_ROOT (dirname (dirname $CONDA_EXE)) + set -gx PATH $_CONDA_ROOT/condabin $PATH +end + +function __conda_add_prompt + if set -q CONDA_PROMPT_MODIFIER + set_color -o green + echo -n $CONDA_PROMPT_MODIFIER + set_color normal + end +end + +if functions -q fish_prompt + if not functions -q __fish_prompt_orig + functions -c fish_prompt __fish_prompt_orig + end + functions -e fish_prompt +else + function __fish_prompt_orig + end +end + +function return_last_status + return $argv +end + +function fish_prompt + set -l last_status $status + if set -q CONDA_LEFT_PROMPT + __conda_add_prompt + end + return_last_status $last_status + __fish_prompt_orig +end + +if functions -q fish_right_prompt + if not functions -q __fish_right_prompt_orig + functions -c fish_right_prompt __fish_right_prompt_orig + end + functions -e fish_right_prompt +else + function __fish_right_prompt_orig + end +end + +function fish_right_prompt + if not set -q CONDA_LEFT_PROMPT + __conda_add_prompt + end + __fish_right_prompt_orig +end + + +function conda --inherit-variable CONDA_EXE + if [ (count $argv) -lt 1 ] + $CONDA_EXE + else + set -l cmd $argv[1] + set -e argv[1] + switch $cmd + case activate deactivate + eval ($CONDA_EXE shell.fish $cmd $argv) + case install update upgrade remove uninstall + $CONDA_EXE $cmd $argv + and eval ($CONDA_EXE shell.fish reactivate) + case '*' + $CONDA_EXE $cmd $argv + end + end +end + + + + +# Autocompletions below + + +function __fish_conda_commands + conda commands +end + +function __fish_conda_env_commands + string replace -r '.*_([a-z]+)\.py$' '$1' $_CONDA_ROOT/lib/python*/site-packages/conda_env/cli/main_*.py +end + +function __fish_conda_envs + conda config --json --show envs_dirs | python -c "import json, os, sys; from os.path import isdir, join; print('\n'.join(d for ed in json.load(sys.stdin)['envs_dirs'] if isdir(ed) for d in os.listdir(ed) if isdir(join(ed, d))))" +end + +function __fish_conda_packages + conda list | awk 'NR > 3 {print $1}' +end + +function __fish_conda_needs_command + set cmd (commandline -opc) + if [ (count $cmd) -eq 1 -a $cmd[1] = conda ] + return 0 + end + return 1 +end + +function __fish_conda_using_command + set cmd (commandline -opc) + if [ (count $cmd) -gt 1 ] + if [ $argv[1] = $cmd[2] ] + return 0 + end + end + return 1 +end + +# Conda commands +complete -f -c conda -n __fish_conda_needs_command -a '(__fish_conda_commands)' +complete -f -c conda -n '__fish_conda_using_command env' -a '(__fish_conda_env_commands)' + +# Commands that need environment as parameter +complete -f -c conda -n '__fish_conda_using_command activate' -a '(__fish_conda_envs)' + +# Commands that need package as parameter +complete -f -c conda -n '__fish_conda_using_command remove' -a '(__fish_conda_packages)' +complete -f -c conda -n '__fish_conda_using_command uninstall' -a '(__fish_conda_packages)' +complete -f -c conda -n '__fish_conda_using_command upgrade' -a '(__fish_conda_packages)' +complete -f -c conda -n '__fish_conda_using_command update' -a '(__fish_conda_packages)' diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh b/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh new file mode 100644 index 0000000000000000000000000000000000000000..7e48cc9cfd8408d6d8665c02ac8f39d0b783fa53 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh @@ -0,0 +1,55 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +if (! $?_CONDA_EXE) then + set _CONDA_EXE="${PWD}/conda/shell/bin/conda" +else + if ("$_CONDA_EXE" == "") then + set _CONDA_EXE="${PWD}/conda/shell/bin/conda" + endif +endif + +if ("`alias conda`" == "") then + if ($?_CONDA_EXE) then + # _CONDA_PFX is named so as not to cause confusion with CONDA_PREFIX + # If nested backticks were possible we wouldn't use any variables here. + set _CONDA_PFX=`dirname "${_CONDA_EXE}"` + set _CONDA_PFX=`dirname "${_CONDA_PFX}"` + alias conda source "${_CONDA_PFX}/etc/profile.d/conda.csh" + # And for good measure, get rid of it afterwards. + unset _CONDA_PFX + else + alias conda source "${PWD}/conda/shell/etc/profile.d/conda.csh" + endif + setenv CONDA_SHLVL 0 + if (! $?prompt) then + set prompt="" + endif +else + switch ( "${1}" ) + case "activate": + set ask_conda="`(setenv prompt '${prompt}' ; '${_CONDA_EXE}' shell.csh activate '${2}' ${argv[3-]})`" + set conda_tmp_status=$status + if( $conda_tmp_status != 0 ) exit ${conda_tmp_status} + eval "${ask_conda}" + rehash + breaksw + case "deactivate": + set ask_conda="`(setenv prompt '${prompt}' ; '${_CONDA_EXE}' shell.csh deactivate '${2}' ${argv[3-]})`" + set conda_tmp_status=$status + if( $conda_tmp_status != 0 ) exit ${conda_tmp_status} + eval "${ask_conda}" + rehash + breaksw + case "install" | "update" | "upgrade" | "remove" | "uninstall": + $_CONDA_EXE $argv[1-] + set ask_conda="`(setenv prompt '${prompt}' ; '${_CONDA_EXE}' shell.csh reactivate)`" + set conda_tmp_status=$status + if( $conda_tmp_status != 0 ) exit ${conda_tmp_status} + eval "${ask_conda}" + rehash + breaksw + default: + $_CONDA_EXE $argv[1-] + breaksw + endsw +endif diff --git a/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh b/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a24b3a97f2489a2be04b0810d324efaa8f4cbf7 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh @@ -0,0 +1,74 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +__conda_exe() ( + if [ -n "${_CE_M:+x}" ] && [ -n "${_CE_CONDA:+x}" ]; then + # only use _CE_M/_CE_CONDA when defined to avoid issues when run with `set -u` + "$CONDA_EXE" $_CE_M $_CE_CONDA "$@" + else + "$CONDA_EXE" "$@" + fi +) + +__conda_hashr() { + if [ -n "${ZSH_VERSION:+x}" ]; then + \rehash + elif [ -n "${POSH_VERSION:+x}" ]; then + : # pass + else + \hash -r + fi +} + +__conda_activate() { + if [ -n "${CONDA_PS1_BACKUP:+x}" ]; then + # Handle transition from shell activated with conda <= 4.3 to a subsequent activation + # after conda updated to >= 4.4. See issue #6173. + PS1="$CONDA_PS1_BACKUP" + \unset CONDA_PS1_BACKUP + fi + \local ask_conda + ask_conda="$(PS1="${PS1:-}" __conda_exe shell.posix "$@")" || \return + \eval "$ask_conda" + __conda_hashr +} + +__conda_reactivate() { + # FUTURE: conda 25.9, remove this function + echo "'__conda_reactivate' is deprecated and will be removed in 25.9. Use '__conda_activate reactivate' instead." 1>&2 + __conda_activate reactivate +} + +conda() { + \local cmd="${1-__missing__}" + case "$cmd" in + activate|deactivate) + __conda_activate "$@" + ;; + install|update|upgrade|remove|uninstall) + __conda_exe "$@" || \return + __conda_activate reactivate + ;; + *) + __conda_exe "$@" + ;; + esac +} + +if [ -z "${CONDA_SHLVL+x}" ]; then + \export CONDA_SHLVL=0 + # In dev-mode CONDA_EXE is python.exe and on Windows + # it is in a different relative location to condabin. + if [ -n "${_CE_CONDA:+x}" ] && [ -n "${WINDIR+x}" ]; then + PATH="$(\dirname "$CONDA_EXE")/condabin${PATH:+":${PATH}"}" + else + PATH="$(\dirname "$(\dirname "$CONDA_EXE")")/condabin${PATH:+":${PATH}"}" + fi + \export PATH + + # We're not allowing PS1 to be unbound. It must at least be set. + # However, we're not exporting it, which can cause problems when starting a second shell + # via a first shell (i.e. starting zsh from bash). + if [ -z "${PS1+x}" ]; then + PS1= + fi +fi diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..095db5a22e3cdb8486ff519a62578aed85e5ed73 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/__init__.py @@ -0,0 +1,69 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +# Attempt to move any conda entries in PATH to the front of it. +# IDEs have their own ideas about how PATH should be managed and +# they do dumb stuff like add /usr/bin to the front of it +# meaning conda takes a submissive role and the wrong stuff +# runs (when other conda prefixes get activated they replace +# the wrongly placed entries with newer wrongly placed entries). +# +# Note, there's still condabin to worry about here, and also should +# we not remove all traces of conda instead of just this fixup? +# Ideally we'd have two modes, 'removed' and 'fixed'. I have seen +# condabin come from an entirely different installation than +# CONDA_PREFIX too in some instances and that really needs fixing. +from __future__ import annotations + +import os +import sys +from logging import getLogger +from os.path import join + +log = getLogger(__name__) + + +def conda_move_to_front_of_PATH(): + if "CONDA_PREFIX" in os.environ: + from ..activate import CmdExeActivator, PosixActivator + + if os.name == "nt": + activator_cls = CmdExeActivator + else: + activator_cls = PosixActivator + activator = activator_cls() + # But why not just use _replace_prefix_in_path? => because moving + # the entries to the front of PATH is the goal here, not swapping + # x for x (which would be pointless anyway). + p = None + # It might be nice to have a parameterised fixture with choices of: + # 'System default PATH', + # 'IDE default PATH', + # 'Fully activated conda', + # 'PATHly activated conda' + # This will do for now => Note, if you have conda activated multiple + # times it could mask some test failures but _remove_prefix_from_path + # cannot be used multiple times; it will only remove *one* conda + # prefix from the *original* value of PATH, calling it N times will + # just return the same value every time, even if you update PATH. + p = activator._remove_prefix_from_path(os.environ["CONDA_PREFIX"]) + + # Replace any non sys.prefix condabin with sys.prefix condabin + new_p = [] + found_condabin = False + for pe in p: + if pe.endswith("condabin"): + if not found_condabin: + found_condabin = True + if join(sys.prefix, "condabin") != pe: + condabin_path = join(sys.prefix, "condabin") + print(f"Incorrect condabin, swapping {pe} to {condabin_path}") + new_p.append(condabin_path) + else: + new_p.append(pe) + else: + new_p.append(pe) + + os.environ["PATH"] = os.pathsep.join(new_p) + activator = activator_cls() + p = activator._add_prefix_to_path(os.environ["CONDA_PREFIX"]) + os.environ["PATH"] = os.pathsep.join(p) diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/cases.py b/miniconda3/lib/python3.13/site-packages/conda/testing/cases.py new file mode 100644 index 0000000000000000000000000000000000000000..c1fa7fddff22fe3bbb158781218433df5cceaf91 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/cases.py @@ -0,0 +1,17 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Extends unittest.TestCase to include select pytest fixtures.""" + +import unittest + +import pytest + + +class BaseTestCase(unittest.TestCase): + fixture_names = ("tmpdir",) + + @pytest.fixture(autouse=True) + def auto_injector_fixture(self, request): + names = self.fixture_names + for name in names: + setattr(self, name, request.getfixturevalue(name)) diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/fixtures.py b/miniconda3/lib/python3.13/site-packages/conda/testing/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..89f4ddcce3c6a5dc5f1b031d4461dfc75ee6a36f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/fixtures.py @@ -0,0 +1,770 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of pytest fixtures used in conda tests.""" + +from __future__ import annotations + +import os +import subprocess +import uuid +import warnings +from contextlib import contextmanager, nullcontext +from dataclasses import dataclass +from itertools import chain +from logging import getLogger +from pathlib import Path +from shutil import copyfile +from typing import TYPE_CHECKING, Literal, TypeVar, overload + +import py +import pytest + +from conda.deprecations import deprecated + +from .. import CONDA_SOURCE_ROOT +from ..auxlib.ish import dals +from ..base.constants import PACKAGE_CACHE_MAGIC_FILE, PREFIX_MAGIC_FILE +from ..base.context import context, reset_context +from ..cli.main import main_subshell +from ..common.configuration import YamlRawParameter +from ..common.serialize import json, yaml +from ..common.url import path_to_url +from ..core.package_cache_data import PackageCacheData +from ..core.subdir_data import SubdirData +from ..exceptions import CondaExitZero +from ..gateways.disk.create import TemporaryDirectory +from ..models.records import PackageRecord +from .integration import PYTHON_BINARY + +if TYPE_CHECKING: + import http.server + from collections.abc import Iterable, Iterator + + from _pytest.capture import MultiCapture + from pytest import ( + CaptureFixture, + ExceptionInfo, + FixtureRequest, + MonkeyPatch, + TempPathFactory, + ) + from pytest_mock import MockerFixture + + from ..common.path import PathType + + +log = getLogger(__name__) + + +TEST_CONDARC = dals( + """ + custom_channels: + darwin: https://some.url.somewhere/stuff + chuck: http://another.url:8080/with/path + custom_multichannels: + michele: + - https://do.it.with/passion + - learn_from_every_thing + steve: + - more-downloads + channel_settings: + - channel: darwin + param_one: value_one + param_two: value_two + - channel: "http://localhost" + param_one: value_one + param_two: value_two + migrated_custom_channels: + darwin: s3://just/cant + chuck: file:///var/lib/repo/ + migrated_channel_aliases: + - https://conda.anaconda.org + channel_alias: ftp://new.url:8082 + conda-build: + root-dir: /some/test/path + proxy_servers: + http: http://user:pass@corp.com:8080 + https: none + ftp: + sftp: '' + ftps: false + rsync: 'false' + aggressive_update_packages: [] + channel_priority: false + """ +) + + +@pytest.fixture(autouse=True) +def suppress_resource_warning(): + """ + Suppress `Unclosed Socket Warning` + + It seems urllib3 keeps a socket open to avoid costly recreation costs. + + xref: https://github.com/kennethreitz/requests/issues/1882 + """ + warnings.filterwarnings("ignore", category=ResourceWarning) + + +@pytest.fixture(scope="function") +def tmpdir(tmpdir, request): + tmpdir = TemporaryDirectory(dir=str(tmpdir)) + request.addfinalizer(tmpdir.cleanup) + return py.path.local(tmpdir.name) + + +@pytest.fixture(autouse=True) +def clear_subdir_cache(): + SubdirData.clear_cached_local_channel_data() + + +@pytest.fixture(scope="function") +def reset_conda_context(): + """Resets the context object after each test function is run.""" + yield + + reset_context() + + +@pytest.fixture() +def temp_package_cache(tmp_path_factory, monkeypatch: MonkeyPatch) -> Iterator[Path]: + """ + Used to isolate package or index cache from other tests. + """ + pkgs_dir = tmp_path_factory.mktemp("pkgs") + monkeypatch.setenv("CONDA_PKGS_DIRS", str(pkgs_dir)) + reset_context() + yield pkgs_dir + + +@pytest.fixture( + # allow CI to set the solver backends via the CONDA_TEST_SOLVERS env var + params=os.environ.get("CONDA_TEST_SOLVERS", "libmamba,classic").split(",") +) +def parametrized_solver_fixture( + request: FixtureRequest, +) -> Iterable[Literal["libmamba", "classic"]]: + """ + A parameterized fixture that sets the solver backend to (1) libmamba + and (2) classic for each test. It's using autouse=True, so only import it in + modules that actually need it. + + Note that skips and xfails need to be done _inside_ the test body. + Decorators can't be used because they are evaluated before the + fixture has done its work! + + So, instead of: + + @pytest.mark.skipif(context.solver == "libmamba", reason="...") + def test_foo(): + ... + + Do: + + def test_foo(): + if context.solver == "libmamba": + pytest.skip("...") + ... + """ + yield from _solver_helper(request, request.param) + + +@pytest.fixture +def solver_classic( + request: FixtureRequest, +) -> Iterable[Literal["classic"]]: + yield from _solver_helper(request, "classic") + + +@pytest.fixture +def solver_libmamba( + request: FixtureRequest, +) -> Iterable[Literal["libmamba"]]: + yield from _solver_helper(request, "libmamba") + + +Solver = TypeVar("Solver", Literal["libmamba"], Literal["classic"]) + + +def _solver_helper( + request: FixtureRequest, + solver: Solver, +) -> Iterable[Solver]: + # clear cached solver backends before & after each test + context.plugin_manager.get_cached_solver_backend.cache_clear() + request.addfinalizer(context.plugin_manager.get_cached_solver_backend.cache_clear) + + mp = request.getfixturevalue("monkeypatch") + + mp.setenv("CONDA_SOLVER", solver) + reset_context() + assert context.solver == solver + + yield solver + + +@pytest.fixture(scope="session") +@deprecated("25.9", "26.3") +def session_capsys(request) -> Iterator[MultiCapture]: + # https://github.com/pytest-dev/pytest/issues/2704#issuecomment-603387680 + capmanager = request.config.pluginmanager.getplugin("capturemanager") + with capmanager.global_and_fixture_disabled(): + yield capmanager._global_capturing + + +@dataclass +class CondaCLIFixture: + capsys: CaptureFixture | None + + @overload + def __call__( + self, + *argv: PathType, + raises: type[Exception] | tuple[type[Exception], ...], + ) -> tuple[str, str, ExceptionInfo]: ... + + @overload + def __call__( + self, + *argv: PathType, + ) -> tuple[str, str, int]: ... + + def __call__( + self, + *argv: PathType, + raises: type[Exception] | tuple[type[Exception], ...] | None = None, + ) -> tuple[str | None, str | None, int | ExceptionInfo]: + """Test conda CLI. Mimic what is done in `conda.cli.main.main`. + + `conda ...` == `conda_cli(...)` + + :param argv: Arguments to parse. + :param raises: Expected exception to intercept. If provided, the raised exception + will be returned instead of exit code (see pytest.raises and pytest.ExceptionInfo). + :return: Command results (stdout, stderr, exit code or pytest.ExceptionInfo). + """ + # clear output + if self.capsys: + self.capsys.readouterr() + + # run command + code = None + with pytest.raises(raises) if raises else nullcontext() as exception: + code = main_subshell(*self._cast_args(argv)) + # capture output + if self.capsys: + out, err = self.capsys.readouterr() + else: + out = err = None + + # restore to prior state + reset_context() + + return out, err, exception if raises else code + + @staticmethod + def _cast_args(argv: tuple[PathType, ...]) -> Iterable[str]: + """Cast args to string and inspect for `conda run`. + + `conda run` is a unique case that requires `--dev` to use the src shell scripts + and not the shell scripts provided by the installer. + """ + # TODO: Refactor this so we don't expose testing infrastructure to the user + # (i.e., deprecate `conda run --dev`). + argv = map(str, argv) + for arg in argv: + yield arg + + # detect if arg is the command (the first positional) + if arg[0] != "-": + # this is the first positional, return remaining arguments + + # if this happens to be the `conda run` command, add --dev + if arg == "run": + yield "--dev" # use src, not installer's shell scripts + + yield from argv + + +@pytest.fixture +def conda_cli(capsys: CaptureFixture) -> Iterator[CondaCLIFixture]: + """A function scoped fixture returning CondaCLIFixture instance. + + Use this for any commands that are local to the current test (e.g., creating a + conda environment only used in the test). + """ + yield CondaCLIFixture(capsys) + + +@pytest.fixture(scope="session") +def session_conda_cli() -> Iterator[CondaCLIFixture]: + """A session scoped fixture returning CondaCLIFixture instance. + + Use this for any commands that are global to the test session (e.g., creating a + conda environment shared across tests, `conda info`, etc.). + """ + yield CondaCLIFixture(None) + + +@dataclass +class PipCLIFixture: + """Fixture for calling pip in specific conda environments.""" + + @overload + def __call__( + self, + *argv: PathType, + prefix: PathType, + raises: type[Exception] | tuple[type[Exception], ...], + ) -> tuple[str, str, ExceptionInfo]: ... + + @overload + def __call__( + self, + *argv: PathType, + prefix: PathType, + ) -> tuple[str, str, int]: ... + + def __call__( + self, + *argv: PathType, + prefix: PathType, + raises: type[Exception] | tuple[type[Exception], ...] | None = None, + ) -> tuple[str | None, str | None, int | ExceptionInfo]: + """Test pip CLI in a specific conda environment. + + `pip ...` in environment == `pip_cli(..., prefix=env_path)` + + :param argv: Arguments to pass to pip. + :param prefix: Path to the conda environment containing pip. + :param raises: Expected exception to intercept. If provided, the raised exception + will be returned instead of exit code (see pytest.raises and pytest.ExceptionInfo). + :return: Command results (stdout, stderr, exit code or pytest.ExceptionInfo). + """ + # build command using python -m pip (more reliable than finding pip executable) + prefix_path = Path(prefix) + python_exe = prefix_path / PYTHON_BINARY + cmd = [str(python_exe), "-m", "pip"] + [str(arg) for arg in argv] + + # run command + with pytest.raises(raises) if raises else nullcontext() as exception: + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + code = result.returncode + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + code = e.returncode + stdout = e.stdout + stderr = e.stderr + except FileNotFoundError: + # python executable not found + raise RuntimeError( + f"Python not found in environment {prefix_path}: {python_exe}" + ) + + return stdout, stderr, exception if raises else code + + +@pytest.fixture(scope="session") +def pip_cli() -> Iterator[PipCLIFixture]: + """A function scoped fixture returning PipCLIFixture instance. + + Use this for calling pip commands in specific conda environments during tests. + Uses `python -m pip` for reliable cross-platform execution. + + Example: + def test_pip_install(tmp_env, pip_cli): + with tmp_env("python=3.10", "pip") as prefix: + stdout, stderr, code = pip_cli("install", "requests", prefix=prefix) + assert code == 0 + """ + yield PipCLIFixture() + + +@dataclass +class PathFactoryFixture: + tmp_path: Path + + def __call__( + self, + name: str | None = None, + prefix: str | None = None, + suffix: str | None = None, + ) -> Path: + """Unique, non-existent path factory. + + Extends pytest's `tmp_path` fixture with a new unique, non-existent path for usage in cases + where we need a temporary path that doesn't exist yet. + + :param name: Path name to append to `tmp_path` + :param prefix: Prefix to prepend to unique name generated + :param suffix: Suffix to append to unique name generated + :return: A new unique path + """ + prefix = prefix or "" + name = name or uuid.uuid4().hex[:8] + suffix = suffix or "" + return self.tmp_path / (prefix + name + suffix) + + +@pytest.fixture +def path_factory(tmp_path: Path) -> Iterator[PathFactoryFixture]: + """A function scoped fixture returning PathFactoryFixture instance. + + Use this to generate any number of temporary paths for the test that are unique and + do not exist yet. + """ + yield PathFactoryFixture(tmp_path) + + +@dataclass +class TmpEnvFixture: + path_factory: PathFactoryFixture | TempPathFactory + conda_cli: CondaCLIFixture + + def get_path(self) -> Path: + if isinstance(self.path_factory, PathFactoryFixture): + # scope=function + return self.path_factory() + else: + # scope=session + return self.path_factory.mktemp("tmp_env-") + + @contextmanager + def __call__( + self, + *args: str, + prefix: str | os.PathLike | None = None, + shallow: bool | None = None, + ) -> Iterator[Path]: + """Generate a conda environment with the provided packages. + + :param args: The arguments to pass to conda create (e.g., packages, flags, etc.) + :param prefix: The prefix at which to install the conda environment + :param shallow: Whether the environment is created only on disk without call to `conda create` + :return: The conda environment's prefix + """ + if shallow and args: + raise ValueError("shallow=True cannot be used with any arguments") + + prefix = Path(prefix or self.get_path()) + + if shallow or (shallow is None and not args): + # no arguments, just create an empty environment + path = prefix / PREFIX_MAGIC_FILE + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() + else: + self.conda_cli( + "create", + f"--prefix={prefix}", + *args, + "--yes", + "--quiet", + ) + + yield prefix + + # no need to remove prefix since it is in a temporary directory + + +@pytest.fixture +def tmp_env( + path_factory: PathFactoryFixture, + conda_cli: CondaCLIFixture, +) -> Iterator[TmpEnvFixture]: + """A function scoped fixture returning TmpEnvFixture instance. + + Use this when creating a conda environment that is local to the current test. + """ + yield TmpEnvFixture(path_factory, conda_cli) + + +@pytest.fixture +def empty_env(tmp_env: TmpEnvFixture) -> Path: + """A function scoped fixture returning an empty environment. + + Use this when creating a conda environment that is empty. + """ + with tmp_env(shallow=True) as prefix: + return prefix + + +@pytest.fixture(scope="session") +def session_tmp_env( + tmp_path_factory: TempPathFactory, + session_conda_cli: CondaCLIFixture, +) -> Iterator[TmpEnvFixture]: + """A session scoped fixture returning TmpEnvFixture instance. + + Use this when creating a conda environment that is shared across tests. + """ + yield TmpEnvFixture(tmp_path_factory, session_conda_cli) + + +@dataclass +class TmpChannelFixture: + path_factory: PathFactoryFixture + conda_cli: CondaCLIFixture + + @contextmanager + def __call__(self, *specs: str) -> Iterator[tuple[Path, str]]: + # download packages + self.conda_cli( + "create", + f"--prefix={self.path_factory()}", + *specs, + "--yes", + "--quiet", + "--download-only", + raises=CondaExitZero, + ) + + pkgs_dir = Path(PackageCacheData.first_writable().pkgs_dir) + pkgs_cache = PackageCacheData(pkgs_dir) + + channel = self.path_factory() + subdir = channel / context.subdir + subdir.mkdir(parents=True) + noarch = channel / "noarch" + noarch.mkdir(parents=True) + + repodata = {"info": {}, "packages": {}} + iter_specs = list(specs) + seen: dict[str, set[str]] = {} + while iter_specs: + spec = iter_specs.pop(0) + + for package_record in pkgs_cache.query(spec): + # track which packages have already been copied to the channel + fname = package_record["fn"] + if fname in seen: + seen[fname].add(spec) + seen[fname] = {spec} + + # copy package to channel + copyfile(pkgs_dir / fname, subdir / fname) + + # add package to repodata + repodata["packages"][fname] = PackageRecord( + **{ + field: value + for field, value in package_record.dump().items() + if field not in ("url", "channel", "schannel", "channel_name") + } + ) + + iter_specs.extend(package_record.depends) + + (subdir / "repodata.json").write_text(json.dumps(repodata)) + (noarch / "repodata.json").write_text(json.dumps({})) + + # ensure all packages were copied to the channel + for spec in chain.from_iterable(seen.values()): + assert any(PackageCacheData(pkgs_dir).query(spec)) + + yield channel, path_to_url(str(channel)) + + +@pytest.fixture +def tmp_channel( + path_factory: PathFactoryFixture, + conda_cli: CondaCLIFixture, +) -> Iterator[TmpChannelFixture]: + """A function scoped fixture returning TmpChannelFixture instance.""" + yield TmpChannelFixture(path_factory, conda_cli) + + +@pytest.fixture(name="monkeypatch") +def context_aware_monkeypatch(monkeypatch: MonkeyPatch) -> MonkeyPatch: + """A monkeypatch fixture that resets context after each test.""" + yield monkeypatch + + # reset context if any CONDA_ variables were set/unset + if conda_vars := [ + name + for obj, name, _ in monkeypatch._setitem + if obj is os.environ and name.startswith("CONDA_") + ]: + log.debug(f"monkeypatch cleanup: undo & reset context: {', '.join(conda_vars)}") + monkeypatch.undo() + # reload context without search paths + reset_context([]) + + +@pytest.fixture +def tmp_pkgs_dir( + path_factory: PathFactoryFixture, mocker: MockerFixture +) -> Iterator[Path]: + """A function scoped fixture returning a temporary package cache directory.""" + pkgs_dir = path_factory() / "pkgs" + pkgs_dir.mkdir(parents=True) + (pkgs_dir / PACKAGE_CACHE_MAGIC_FILE).touch() + + mocker.patch( + "conda.base.context.Context.pkgs_dirs", + new_callable=mocker.PropertyMock, + return_value=(pkgs_dir_str := str(pkgs_dir),), + ) + assert context.pkgs_dirs == (pkgs_dir_str,) + + yield pkgs_dir + + PackageCacheData._cache_.pop(pkgs_dir_str, None) + + +@pytest.fixture +def tmp_envs_dir( + path_factory: PathFactoryFixture, mocker: MockerFixture +) -> Iterator[Path]: + """A function scoped fixture returning a temporary environment directory.""" + envs_dir = path_factory() / "envs" + envs_dir.mkdir(parents=True) + + mocker.patch( + "conda.base.context.Context.envs_dirs", + new_callable=mocker.PropertyMock, + return_value=(envs_dir_str := str(envs_dir),), + ) + assert context.envs_dirs == (envs_dir_str,) + + yield envs_dir + + +@pytest.fixture(scope="session", autouse=True) +def PYTHONPATH(): + """ + We need to set this so Python loads the dev version of 'conda', usually taken + from `conda/` in the root of the cloned repo. This root is usually the working + directory when we run `pytest`. + Otherwise, it will import the one installed in the base environment, which might + have not been overwritten with `pip install -e . --no-deps`. This doesn't happen + in other tests because they run with the equivalent of `python -m conda`. However, + some tests directly run `conda (shell function) which calls `conda` (Python entry + point). When a script is called this way, it bypasses the automatic "working directory + is first on sys.path" behavior you find in `python -m` style calls. See + https://docs.python.org/3/library/sys_path_init.html for details. + """ + if "PYTHONPATH" in os.environ: + yield + else: + with pytest.MonkeyPatch.context() as monkeypatch: + monkeypatch.setenv("PYTHONPATH", CONDA_SOURCE_ROOT) + yield + + +@pytest.fixture +def context_testdata() -> None: + reset_context() + context._set_raw_data( + { + "testdata": YamlRawParameter.make_raw_parameters( + "testdata", yaml.loads(TEST_CONDARC) + ) + } + ) + + +# HTTP Test Server Fixtures + + +@dataclass +class HttpTestServerFixture: + """Fixture providing HTTP test server for serving local files.""" + + server: http.server.ThreadingHTTPServer + host: str + port: int + url: str + directory: Path + + def __post_init__(self): + """Log server startup for debugging.""" + log.debug(f"HTTP test server started: {self.url}") + + def get_url(self, path: str = "") -> str: + """ + Get full URL for a given path on the server. + + :param path: Relative path on the server (e.g., "subdir/package.tar.bz2") + :return: Full URL + """ + path = path.lstrip("/") + return f"{self.url}/{path}" if path else self.url + + +@pytest.fixture +def http_test_server( + request: FixtureRequest, + path_factory: PathFactoryFixture, +) -> Iterator[HttpTestServerFixture]: + """ + Function-scoped HTTP test server for serving local files. + + This fixture starts an HTTP server on a random port and serves files + from a directory. The server supports both IPv4 and IPv6. + + Usage without parametrize (dynamic content): + def test_dynamic(http_test_server): + # Server uses temporary directory automatically + (http_test_server.directory / "file.txt").write_text("content") + url = http_test_server.get_url("file.txt") + response = requests.get(url) + assert response.status_code == 200 + + Usage with parametrize (pre-existing directory): + @pytest.mark.parametrize("http_test_server", ["tests/data/mock-channel"], indirect=True) + def test_existing(http_test_server): + url = http_test_server.get_url("file.txt") + response = requests.get(url) + assert response.status_code == 200 + + Use ``None`` in parametrize to mix pre-existing directories with dynamic content: + @pytest.mark.parametrize("http_test_server", ["tests/data", None], indirect=True) + + :param request: pytest fixture request object + :param path_factory: path_factory fixture for creating unique temp directories + :return: HttpTestServerFixture with server, host, port, url, and directory attributes + :raises ValueError: If parametrized directory is invalid + """ + from . import http_test_server as http_server_module + + if directory := getattr(request, "param", None): + # Parameter was provided via @pytest.mark.parametrize + # Validate the provided directory + directory_path = Path(directory) + if not directory_path.exists(): + raise ValueError(f"Directory does not exist: {directory}") + if not directory_path.is_dir(): + raise ValueError(f"Path is not a directory: {directory}") + directory = str(directory_path.resolve()) + else: + # No parameter provided or explicit None - use path_factory for unique directory + server_dir = path_factory(name="http_test_server") + server_dir.mkdir() + directory = str(server_dir) + + server = http_server_module.run_test_server(directory) + host, port = server.socket.getsockname()[:2] + url_host = f"[{host}]" if ":" in host else host + url = f"http://{url_host}:{port}" + + fixture = HttpTestServerFixture( + server=server, + host=host, + port=port, + url=url, + directory=Path(directory), + ) + + yield fixture + + # Cleanup: shutdown server + server.shutdown() diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/gateways/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/testing/gateways/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/gateways/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/gateways/fixtures.py b/miniconda3/lib/python3.13/site-packages/conda/testing/gateways/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb44ee622e395eefe7d8bf2e5623754caefd54a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/gateways/fixtures.py @@ -0,0 +1,131 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of pytest fixtures used in conda.gateways tests.""" + +import os +import socket +from pathlib import Path +from shutil import which + +import pytest +from xprocess import ProcessStarter + +from ...common.serialize import json + +MINIO_EXE = which("minio") + + +# rely on tests not requesting this fixture, and pytest not creating this if +# MINIO_EXE was not found +@pytest.fixture() +def minio_s3_server(xprocess, tmp_path): + """ + Mock a local S3 server using `minio` + + This requires: + - pytest-xprocess: runs the background process + - minio: the executable must be in PATH + + Note, the given S3 server will be EMPTY! The test function needs + to populate it. You can use + `conda.testing.helpers.populate_s3_server` for that. + """ + + class Minio: + # The 'name' below will be the name of the S3 bucket containing + # keys like `noarch/repodata.json` + # see https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html + name = "minio-s3-server" + port = 9000 + + def __init__(self): + (Path(tmp_path) / self.name).mkdir() + + @property + def server_url(self): + return f"{self.endpoint}/{self.name}" + + @property + def endpoint(self): + return f"http://localhost:{self.port}" + + def populate_bucket(self, endpoint, bucket_name, channel_dir): + """Prepare the s3 connection for our minio instance""" + from boto3.session import Session + from botocore.client import Config + + # Make the minio bucket public first + # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-example-bucket-policies.html#set-a-bucket-policy + session = Session() + client = session.client( + "s3", + endpoint_url=endpoint, + aws_access_key_id="minioadmin", + aws_secret_access_key="minioadmin", + config=Config(signature_version="s3v4"), + region_name="us-east-1", + ) + bucket_policy = json.dumps( + { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "AddPerm", + "Effect": "Allow", + "Principal": "*", + "Action": ["s3:GetObject"], + "Resource": f"arn:aws:s3:::{bucket_name}/*", + } + ], + } + ) + client.put_bucket_policy(Bucket=bucket_name, Policy=bucket_policy) + + # Minio has to start with an empty directory; once available, + # we can import all channel files by "uploading" them + for current, _, files in os.walk(channel_dir): + for f in files: + path = Path(current, f) + key = path.relative_to(channel_dir) + client.upload_file( + str(path), + bucket_name, + str(key).replace("\\", "/"), # MinIO expects Unix paths + ExtraArgs={"ACL": "public-read"}, + ) + + print("Starting mock_s3_server") + minio = Minio() + + class Starter(ProcessStarter): + pattern = "MinIO Object Storage Server" + terminate_on_interrupt = True + timeout = 10 + args = [ + MINIO_EXE, + "server", + f"--address=:{minio.port}", + tmp_path, + ] + + def startup_check(self, port=minio.port): + s = socket.socket() + address = "localhost" + error = False + try: + s.connect((address, port)) + except Exception as e: + print( + "something's wrong with %s:%d. Exception is %s" % (address, port, e) + ) + error = True + finally: + s.close() + + return not error + + # ensure process is running and return its logfile + pid, logfile = xprocess.ensure(minio.name, Starter) + print(f"Server (PID: {pid}) log file can be found here: {logfile}") + yield minio + xprocess.getinfo(minio.name).terminate() diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/helpers.py b/miniconda3/lib/python3.13/site-packages/conda/testing/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..7d821b805afae31a0e29f75c2612d3d2d0fa73d2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/helpers.py @@ -0,0 +1,764 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of helper functions used in conda tests.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from contextlib import contextmanager +from functools import cache +from os.path import abspath, dirname, join +from pathlib import Path +from tempfile import gettempdir, mkdtemp +from unittest.mock import patch +from uuid import uuid4 + +import pytest + +from ..base.constants import REPODATA_FN +from ..base.context import context +from ..common.io import captured as common_io_captured +from ..common.serialize import json +from ..core.prefix_data import PrefixData +from ..core.subdir_data import SubdirData +from ..gateways.disk.delete import rm_rf +from ..gateways.disk.read import lexists +from ..history import History +from ..models.channel import Channel +from ..models.records import PackageRecord, PrefixRecord +from ..resolve import Resolve + +# The default value will only work if we have installed conda in development mode! +TEST_DATA_DIR = os.environ.get( + "CONDA_TEST_DATA_DIR", abspath(join(dirname(__file__), "..", "..", "tests", "data")) +) +CHANNEL_DIR = CHANNEL_DIR_V1 = abspath(join(TEST_DATA_DIR, "conda_format_repo")) +CHANNEL_DIR_V2 = abspath(join(TEST_DATA_DIR, "base_url_channel")) +EXPORTED_CHANNELS_DIR = mkdtemp(suffix="-test-conda-channels") + + +expected_error_prefix = "Using Anaconda Cloud api site https://api.anaconda.org" + + +def strip_expected(stderr): + if expected_error_prefix and stderr.startswith(expected_error_prefix): + stderr = stderr[len(expected_error_prefix) :].lstrip() + return stderr + + +def raises(exception, func, string=None): + try: + a = func() + except exception as e: + if string: + assert string in e.args[0] + print(e) + return True + raise Exception(f"did not raise, gave {a}") + + +@contextmanager +def captured(disallow_stderr=True): + # same as common.io.captured but raises Exception if unexpected output was written to stderr + try: + with common_io_captured() as c: + yield c + finally: + c.stderr = strip_expected(c.stderr) + if disallow_stderr and c.stderr: + raise Exception(f"Got stderr output: {c.stderr}") + + +def assert_equals(a, b, output=""): + output = f"{a.lower()!r} != {b.lower()!r}" + "\n\n" + output + assert a.lower() == b.lower(), output + + +def assert_not_in(a, b, output=""): + assert a.lower() not in b.lower(), ( + f"{output} {a.lower()!r} should not be found in {b.lower()!r}" + ) + + +def assert_in(a, b, output=""): + assert a.lower() in b.lower(), ( + f"{output} {a.lower()!r} cannot be found in {b.lower()!r}" + ) + + +def add_subdir(dist_string): + channel_str, package_str = dist_string.split("::") + channel_str = channel_str + "/" + context.subdir + return "::".join([channel_str, package_str]) + + +def add_subdir_to_iter(iterable): + if isinstance(iterable, dict): + return {add_subdir(k): v for k, v in iterable.items()} + elif isinstance(iterable, list): + return list(map(add_subdir, iterable)) + elif isinstance(iterable, set): + return set(map(add_subdir, iterable)) + elif isinstance(iterable, tuple): + return tuple(map(add_subdir, iterable)) + else: + raise Exception("Unable to add subdir to object of unknown type.") + + +@contextmanager +def tempdir(): + tempdirdir = gettempdir() + dirname = str(uuid4())[:8] + prefix = join(tempdirdir, dirname) + try: + os.makedirs(prefix) + yield prefix + finally: + if lexists(prefix): + rm_rf(prefix) + + +def supplement_index_with_repodata(index, repodata, channel, priority): + repodata_info = repodata["info"] + arch = repodata_info.get("arch") + platform = repodata_info.get("platform") + subdir = repodata_info.get("subdir") + if not subdir: + subdir = "{}-{}".format(repodata_info["platform"], repodata_info["arch"]) + auth = channel.auth + for fn, info in repodata["packages"].items(): + rec = PackageRecord.from_objects( + info, + fn=fn, + arch=arch, + platform=platform, + channel=channel, + subdir=subdir, + # schannel=schannel, + priority=priority, + # url=join_url(channel_url, fn), + auth=auth, + ) + index[rec] = rec + + +def add_feature_records_legacy(index): + all_features = set() + for rec in index.values(): + if rec.track_features: + all_features.update(rec.track_features) + + for feature_name in all_features: + rec = PackageRecord.feature(feature_name) + index[rec] = rec + + +def _export_subdir_data_to_repodata(subdir_data: SubdirData): + """ + This function is only temporary and meant to patch wrong / undesirable + testing behaviour. It should end up being replaced with the new class-based, + backend-agnostic solver tests. + """ + state = subdir_data._internal_state + subdir = subdir_data.channel.subdir + packages = {} + packages_conda = {} + for pkg in subdir_data.iter_records(): + if pkg.timestamp: + # ensure timestamp is dumped as int in milliseconds + # (pkg.timestamp is a kept as a float in seconds) + pkg.__fields__["timestamp"]._in_dump = True + data = pkg.dump() + if subdir == "noarch" and getattr(pkg, "noarch", None): + data["subdir"] = "noarch" + data["platform"] = data["arch"] = None + if "features" in data: + # Features are deprecated, so they are not implemented + # in modern solvers like mamba. Mamba does implement + # track_features minimization, so we are exposing the + # features as track_features, which seems to make the + # tests pass + data["track_features"] = data["features"] + del data["features"] + if pkg.fn.endswith(".conda"): + packages_conda[pkg.fn] = data + else: + packages[pkg.fn] = data + return { + "_cache_control": state["_cache_control"], + "_etag": state["_etag"], + "_mod": state["_mod"], + "_url": state["_url"], + "_add_pip": state["_add_pip"], + "info": { + "subdir": subdir, + }, + "packages": packages, + "packages.conda": packages_conda, + } + + +def _sync_channel_to_disk(subdir_data: SubdirData): + """ + This function is only temporary and meant to patch wrong / undesirable + testing behaviour. It should end up being replaced with the new class-based, + backend-agnostic solver tests. + """ + base = Path(EXPORTED_CHANNELS_DIR) / subdir_data.channel.name + subdir_path = base / subdir_data.channel.subdir + subdir_path.mkdir(parents=True, exist_ok=True) + with open(subdir_path / "repodata.json", "w") as f: + json.dump( + _export_subdir_data_to_repodata(subdir_data), f, indent=2, sort_keys=True + ) + f.flush() + os.fsync(f.fileno()) + + +def _alias_canonical_channel_name_cache_to_file_prefixed(name, subdir_data=None): + """ + This function is only temporary and meant to patch wrong / undesirable + testing behaviour. It should end up being replaced with the new class-based, + backend-agnostic solver tests. + """ + # export repodata state to disk for other solvers to test + if subdir_data is None: + cache_key = Channel(name).url(with_credentials=True), "repodata.json" + subdir_data = SubdirData._cache_.get(cache_key) + if subdir_data: + local_proxy_channel = Channel(f"{EXPORTED_CHANNELS_DIR}/{name}") + SubdirData._cache_[ + (local_proxy_channel.url(with_credentials=True), "repodata.json") + ] = subdir_data + + +def _patch_for_local_exports(name, subdir_data): + """ + This function is only temporary and meant to patch wrong / undesirable + testing behaviour. It should end up being replaced with the new class-based, + backend-agnostic solver tests. + """ + _alias_canonical_channel_name_cache_to_file_prefixed(name, subdir_data) + + # we need to override the modification time here so the + # cache hits this subdir_data object from the local copy too + # - without this, the legacy solver will use the local dump too + # and there's no need for that extra work + # (check conda.core.subdir_data.SubdirDataType.__call__ for + # details) + _sync_channel_to_disk(subdir_data) + subdir_data._mtime = float("inf") + + +def _get_index_r_base( + json_filename_or_packages, + channel_name, + subdir=context.subdir, + add_pip=False, + merge_noarch=False, +): + if isinstance(json_filename_or_packages, (str, os.PathLike)): + with open(join(TEST_DATA_DIR, json_filename_or_packages)) as fi: + all_packages = json.load(fi) + elif isinstance(json_filename_or_packages, dict): + all_packages = json_filename_or_packages + else: + raise ValueError("'json_filename_or_data' must be path-like or dict") + + packages = {subdir: {}, "noarch": {}} + if merge_noarch: + packages[subdir] = all_packages + else: + for key, pkg in all_packages.items(): + if pkg.get("subdir") == "noarch" or pkg.get("noarch"): + packages["noarch"][key] = pkg + else: + packages[subdir][key] = pkg + + subdir_datas = [] + channels = [] + for subchannel, subchannel_pkgs in packages.items(): + repodata = { + "info": { + "subdir": subchannel, + "arch": context.arch_name, + "platform": context.platform, + }, + "packages": subchannel_pkgs, + } + + channel = Channel(f"https://conda.anaconda.org/{channel_name}/{subchannel}") + channels.append(channel) + sd = SubdirData(channel) + subdir_datas.append(sd) + + with context._override("add_pip_as_python_dependency", add_pip): + sd._process_raw_repodata_str(json.dumps(repodata)) + + sd._loaded = True + SubdirData._cache_[(channel.url(with_credentials=True), REPODATA_FN)] = sd + _patch_for_local_exports(channel_name, sd) + + # this is for the classic solver only, which is fine with a single collapsed index + index = {} + for sd in subdir_datas: + index.update({prec: prec for prec in sd.iter_records()}) + r = Resolve(index, channels=channels) + + return index, r + + +# this fixture appears to introduce a test-order dependency if cached +def get_index_r_1(subdir=context.subdir, add_pip=True, merge_noarch=False): + return _get_index_r_base( + "index.json", + "channel-1", + subdir=subdir, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@cache +def get_index_r_2(subdir=context.subdir, add_pip=True, merge_noarch=False): + return _get_index_r_base( + "index2.json", + "channel-2", + subdir=subdir, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@cache +def get_index_r_4(subdir=context.subdir, add_pip=True, merge_noarch=False): + return _get_index_r_base( + "index4.json", + "channel-4", + subdir=subdir, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@cache +def get_index_r_5(subdir=context.subdir, add_pip=False, merge_noarch=False): + return _get_index_r_base( + "index5.json", + "channel-5", + subdir=subdir, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@cache +def get_index_must_unfreeze(subdir=context.subdir, add_pip=True, merge_noarch=False): + repodata = { + "foobar-1.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": ["libbar 2.0.*", "libfoo 1.0.*"], + "md5": "11ec1194bcc56b9a53c127142a272772", + "name": "foobar", + "timestamp": 1562861325613, + "version": "1.0", + }, + "foobar-2.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": ["libbar 2.0.*", "libfoo 2.0.*"], + "md5": "f8eb5a7fa1ff6dead4e360631a6cd048", + "name": "foobar", + "version": "2.0", + }, + "libbar-1.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": [], + "md5": "f51f4d48a541b7105b5e343704114f0f", + "name": "libbar", + "timestamp": 1562858881022, + "version": "1.0", + }, + "libbar-2.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": [], + "md5": "27f4e717ed263f909074f64d9cbf935d", + "name": "libbar", + "timestamp": 1562858881748, + "version": "2.0", + }, + "libfoo-1.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": [], + "md5": "ad7c088566ffe2389958daedf8ff312c", + "name": "libfoo", + "timestamp": 1562858763881, + "version": "1.0", + }, + "libfoo-2.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": [], + "md5": "daf7af7086d8f22be49ae11bdc41f332", + "name": "libfoo", + "timestamp": 1562858836924, + "version": "2.0", + }, + "qux-1.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": ["libbar 2.0.*", "libfoo 1.0.*"], + "md5": "18604cbe4f789fe853232eef4babd4f9", + "name": "qux", + "timestamp": 1562861393808, + "version": "1.0", + }, + "qux-2.0-0.tar.bz2": { + "build": "0", + "build_number": 0, + "depends": ["libbar 1.0.*", "libfoo 2.0.*"], + "md5": "892aa4b9ec64b67045a46866ef1ea488", + "name": "qux", + "timestamp": 1562861394828, + "version": "2.0", + }, + } + _get_index_r_base( + repodata, + "channel-freeze", + subdir=subdir, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +# Do not memoize this get_index to allow different CUDA versions to be detected +def get_index_cuda(subdir=context.subdir, add_pip=True, merge_noarch=False): + return _get_index_r_base( + "index.json", + "channel-1", + subdir=subdir, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +def record( + name="a", + version="1.0", + depends=None, + build="0", + build_number=0, + timestamp=0, + channel=None, + **kwargs, +): + return PackageRecord( + name=name, + version=version, + depends=depends or [], + build=build, + build_number=build_number, + timestamp=timestamp, + channel=channel, + **kwargs, + ) + + +def _get_solver_base( + channel_id, + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + tmpdir = tmpdir.strpath + pd = PrefixData(tmpdir) + pd._PrefixData__prefix_records = { + rec.name: PrefixRecord.from_objects(rec) for rec in prefix_records + } + spec_map = {spec.name: spec for spec in history_specs} + if channel_id == "channel-1": + get_index_r_1(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-1") + channels = (Channel(f"{EXPORTED_CHANNELS_DIR}/channel-1"),) + elif channel_id == "channel-2": + get_index_r_2(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-2") + channels = (Channel(f"{EXPORTED_CHANNELS_DIR}/channel-2"),) + elif channel_id == "channel-4": + get_index_r_4(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-4") + channels = (Channel(f"{EXPORTED_CHANNELS_DIR}/channel-4"),) + elif channel_id == "channel-5": + get_index_r_5(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-5") + channels = (Channel(f"{EXPORTED_CHANNELS_DIR}/channel-5"),) + elif channel_id == "aggregate-1": + get_index_r_2(context.subdir, add_pip, merge_noarch) + get_index_r_4(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-2") + _alias_canonical_channel_name_cache_to_file_prefixed("channel-4") + channels = ( + Channel(f"{EXPORTED_CHANNELS_DIR}/channel-2"), + Channel(f"{EXPORTED_CHANNELS_DIR}/channel-4"), + ) + elif channel_id == "aggregate-2": + get_index_r_2(context.subdir, add_pip, merge_noarch) + get_index_r_4(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-4") + _alias_canonical_channel_name_cache_to_file_prefixed("channel-2") + # This is the only difference with aggregate-1: the priority + channels = ( + Channel(f"{EXPORTED_CHANNELS_DIR}/channel-4"), + Channel(f"{EXPORTED_CHANNELS_DIR}/channel-2"), + ) + elif channel_id == "must-unfreeze": + get_index_must_unfreeze(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-freeze") + channels = (Channel(f"{EXPORTED_CHANNELS_DIR}/channel-freeze"),) + elif channel_id == "cuda": + get_index_cuda(context.subdir, add_pip, merge_noarch) + _alias_canonical_channel_name_cache_to_file_prefixed("channel-1") + channels = (Channel(f"{EXPORTED_CHANNELS_DIR}/channel-1"),) + + subdirs = (context.subdir,) if merge_noarch else (context.subdir, "noarch") + + with context._override("add_pip_as_python_dependency", add_pip): + with patch.object(History, "get_requested_specs_map", return_value=spec_map): + # We need CONDA_ADD_PIP_AS_PYTHON_DEPENDENCY=false here again (it's also in + # get_index_r_*) to cover solver logics that need to load from disk instead of + # hitting the SubdirData cache + yield context.plugin_manager.get_solver_backend()( + tmpdir, + channels, + subdirs, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + ) + + +@contextmanager +def get_solver( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "channel-1", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@contextmanager +def get_solver_2( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "channel-2", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@contextmanager +def get_solver_4( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "channel-4", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@contextmanager +def get_solver_5( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "channel-5", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@contextmanager +def get_solver_aggregate_1( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "aggregate-1", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@contextmanager +def get_solver_aggregate_2( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "aggregate-2", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@contextmanager +def get_solver_must_unfreeze( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "must-unfreeze", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +@contextmanager +def get_solver_cuda( + tmpdir, + specs_to_add=(), + specs_to_remove=(), + prefix_records=(), + history_specs=(), + add_pip=False, + merge_noarch=False, +): + yield from _get_solver_base( + "cuda", + tmpdir, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + prefix_records=prefix_records, + history_specs=history_specs, + add_pip=add_pip, + merge_noarch=merge_noarch, + ) + + +def convert_to_dist_str(solution): + return tuple(prec.dist_str(canonical_name=False) for prec in solution) + + +@pytest.fixture() +def solver_class(): + return context.plugin_manager.get_solver_backend() + + +def in_subprocess(): + return bool(os.getenv("_RERUN_IN_SUBPROCESS")) + + +def forward_to_subprocess( + request, *cli_args, **subprocess_kwargs +) -> subprocess.CompletedProcess | None: + if in_subprocess(): + return + args = cli_args or ( + "--no-header", + "--disable-warnings", + "--color=no", + "-vvv", + ) + env = os.environ.copy() + env["_RERUN_IN_SUBPROCESS"] = "1" + env.update(subprocess_kwargs.pop("env", {})) + return subprocess.run( + [ + sys.executable, + "-m", + "pytest", + *args, + f"{request.node.path}::{request.node.name}", + ], + check=subprocess_kwargs.pop("check", True), + env=env, + **subprocess_kwargs, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/http_test_server.py b/miniconda3/lib/python3.13/site-packages/conda/testing/http_test_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3c3322ac6c02822fe12bef0a754a54183e6f21d8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/http_test_server.py @@ -0,0 +1,85 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +HTTP test server for serving local files during tests. + +This module provides a local HTTP server that can be used in pytest fixtures +to serve files from a specified directory. The server runs on a random port +and supports both IPv4 and IPv6. + +The server is commonly used for testing: +- Mock conda channels with packages and repodata +- Remote environment files (environment.yml) +- Remote configuration files +- Any scenario where conda needs to fetch files from HTTP URLs + +Example usage: + + from conda.testing import http_test_server + + def test_something(): + server = http_test_server.run_test_server("/path/to/files") + host, port = server.socket.getsockname()[:2] + url = f"http://{host}:{port}/file.txt" + + # Make HTTP requests to url... + + server.shutdown() + +For pytest fixtures that wrap this functionality, see: +- `http_test_server` - function-scoped fixture + +The fixture can be configured via `@pytest.mark.parametrize("http_test_server", [""], indirect=True)` +to specify the directory to serve, or used without parametrize (or with `None`) for dynamic content generation. +""" + +import contextlib +import http.server +import queue +import socket +import threading + + +def run_test_server(directory: str) -> http.server.ThreadingHTTPServer: + """ + Run a test server on a random port. Inspect returned server to get port, + shutdown etc. + """ + + class DualStackServer(http.server.ThreadingHTTPServer): + daemon_threads = False # These are per-request threads + allow_reuse_address = True # Good for tests + request_queue_size = 64 # Should be more than the number of test packages + + def server_bind(self): + # suppress exception when protocol is IPv4 + with contextlib.suppress(Exception): + self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) + return super().server_bind() + + def finish_request(self, request, client_address): + self.RequestHandlerClass(request, client_address, self, directory=directory) + + def start_server(queue): + with DualStackServer( + ("127.0.0.1", 0), http.server.SimpleHTTPRequestHandler + ) as httpd: + host, port = httpd.socket.getsockname()[:2] + queue.put(httpd) + url_host = f"[{host}]" if ":" in host else host + print(f"Serving HTTP on {host} port {port} (http://{url_host}:{port}/) ...") + try: + httpd.serve_forever() + except KeyboardInterrupt: + print("\nKeyboard interrupt received, exiting.") + + started = queue.Queue() + + threading.Thread(target=start_server, args=(started,), daemon=True).start() + + return started.get(timeout=1) + + +if __name__ == "__main__": + server = run_test_server(directory=".") + print(server) diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/integration.py b/miniconda3/lib/python3.13/site-packages/conda/testing/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..ff867a8d25c675449fc370cd853f1dacb60fc38a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/integration.py @@ -0,0 +1,124 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +These helpers were originally defined in tests/test_create.py, +but were refactored here so downstream projects can benefit from +them too. +""" + +from __future__ import annotations + +import os +import sys +from logging import getLogger +from os.path import join +from pathlib import Path +from typing import TYPE_CHECKING + +from ..common.compat import on_win +from ..common.io import dashlist +from ..core.prefix_data import PrefixData +from ..gateways.logging import DEBUG +from ..models.match_spec import MatchSpec + +if TYPE_CHECKING: + from ..models.records import PrefixRecord + +TEST_LOG_LEVEL = DEBUG +PYTHON_BINARY = "python.exe" if on_win else "bin/python" +UNICODE_CHARACTERS = "ōγђ家固한áêñßôç" +# UNICODE_CHARACTERS_RESTRICTED = u"áêñßôç" +UNICODE_CHARACTERS_RESTRICTED = "abcdef" +which_or_where = "which" if not on_win else "where" +cp_or_copy = "cp" if not on_win else "copy" +env_or_set = "env" if not on_win else "set" + +# UNICODE_CHARACTERS = u"12345678abcdef" +# UNICODE_CHARACTERS_RESTRICTED = UNICODE_CHARACTERS + +# When testing for bugs, you may want to change this to a _, +# for example to see if a bug is related to spaces in prefixes. +SPACER_CHARACTER = " " + +log = getLogger(__name__) + + +def escape_for_winpath(p): + return p.replace("\\", "\\\\") + + +class Commands: + COMPARE = "compare" + CONFIG = "config" + CLEAN = "clean" + CREATE = "create" + INFO = "info" + INSTALL = "install" + LIST = "list" + REMOVE = "remove" + SEARCH = "search" + UPDATE = "update" + RUN = "run" + + +def package_is_installed( + prefix: str | os.PathLike | Path, + spec: str | MatchSpec, + reload_records: bool = True, +) -> PrefixRecord | None: + spec = MatchSpec(spec) + prefix_data = PrefixData(prefix, interoperability=True) + if reload_records: + prefix_data.load() + prefix_recs = tuple(prefix_data.query(spec)) + if not prefix_recs: + return None + elif len(prefix_recs) > 1: + raise AssertionError( + f"Multiple packages installed.{dashlist(prec.dist_str() for prec in prefix_recs)}" + ) + else: + return prefix_recs[0] + + +def get_shortcut_dir(prefix_for_unix=sys.prefix): + if sys.platform == "win32": + # On Windows, .nonadmin has been historically created by constructor in sys.prefix + user_mode = "user" if Path(sys.prefix, ".nonadmin").is_file() else "system" + try: # menuinst v2 + from menuinst.platforms.win_utils.knownfolders import dirs_src + + return dirs_src[user_mode]["start"][0] + except ImportError: # older menuinst versions; TODO: remove + try: + from menuinst.win32 import dirs_src + + return dirs_src[user_mode]["start"][0] + except ImportError: + from menuinst.win32 import dirs + + return dirs[user_mode]["start"] + # on unix, .nonadmin is only created by menuinst v2 as needed on the target prefix + # it might exist, or might not; if it doesn't, we try to create it + # see https://github.com/conda/menuinst/issues/150 + non_admin_file = Path(prefix_for_unix, ".nonadmin") + if non_admin_file.is_file(): + user_mode = "user" + else: + try: + non_admin_file.touch() + except OSError: + user_mode = "system" + else: + user_mode = "user" + non_admin_file.unlink() + + if sys.platform == "darwin": + if user_mode == "user": + return join(os.environ["HOME"], "Applications") + return "/Applications" + if sys.platform == "linux": + if user_mode == "user": + return join(os.environ["HOME"], ".local", "share", "applications") + return "/usr/share/applications" + raise NotImplementedError(sys.platform) diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/notices/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/testing/notices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/notices/__init__.py @@ -0,0 +1,2 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/notices/fixtures.py b/miniconda3/lib/python3.13/site-packages/conda/testing/notices/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..b4889e062cad32fc6c48766f18049bb298c406fd --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/notices/fixtures.py @@ -0,0 +1,42 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of pytest fixtures used in conda.notices tests.""" + +from pathlib import Path +from unittest import mock + +import pytest + +from ...base.constants import DEFAULTS_CHANNEL_NAME, NOTICES_CACHE_SUBDIR +from ...base.context import reset_context +from ...cli.conda_argparse import generate_parser + + +@pytest.fixture(scope="function") +def notices_cache_dir(tmpdir): + """ + Fixture that creates the notices cache dir while also mocking + out a call to user_cache_dir. + """ + with mock.patch("conda.notices.cache.user_cache_dir") as user_cache_dir: + user_cache_dir.return_value = tmpdir + cache_dir = Path(tmpdir).joinpath(NOTICES_CACHE_SUBDIR) + cache_dir.mkdir(parents=True, exist_ok=True) + + yield cache_dir + + +@pytest.fixture(scope="function") +def notices_mock_fetch_get_session(): + with mock.patch("conda.notices.fetch.get_session") as mock_get_session: + mock_get_session.return_value = mock.MagicMock() + yield mock_get_session + + +@pytest.fixture(scope="function") +def conda_notices_args_n_parser(): + parser = generate_parser() + args = parser.parse_args(["notices", f"--channel={DEFAULTS_CHANNEL_NAME}"]) + reset_context((), args) + + return args, parser diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/notices/helpers.py b/miniconda3/lib/python3.13/site-packages/conda/testing/notices/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5e1458eddda7d28b9015f19e01e168a8f07f43 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/notices/helpers.py @@ -0,0 +1,143 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Collection of helper functions used in conda.notices tests.""" + +from __future__ import annotations + +import datetime +import os +import uuid +from itertools import chain +from pathlib import Path +from typing import TYPE_CHECKING + +from ...common.serialize import json +from ...models.channel import get_channel_objs +from ...notices.cache import get_notices_cache_file +from ...notices.core import get_channel_name_and_urls +from ...notices.types import ChannelNoticeResponse + +if TYPE_CHECKING: + from collections.abc import Sequence + from unittest import mock + + from ...base.context import Context + +DEFAULT_NOTICE_MESG = "Here is an example message that will be displayed to users" + + +def get_test_notices( + messages: Sequence[str], + level: str | None = "info", + created_at: datetime.datetime | None = None, + expired_at: datetime.datetime | None = None, +) -> dict: + created_at = created_at or datetime.datetime.now(datetime.timezone.utc) + expired_at = expired_at or created_at + datetime.timedelta(days=7) + + return { + "notices": [ + { + "id": str(uuid.uuid4()), + "message": message, + "level": level, + "created_at": created_at.isoformat(), + "expired_at": expired_at.isoformat(), + } + for message in messages + ] + } + + +def add_resp_to_mock( + mock_session: mock.MagicMock, + status_code: int, + messages_json: dict, + raise_exc: bool = False, +) -> None: + """Adds any number of MockResponse to MagicMock object as side_effects""" + + def forever_404(): + while True: + yield MockResponse(404, {}) + + def one_200(): + yield MockResponse(status_code, messages_json, raise_exc=raise_exc) + + chn = chain(one_200(), forever_404()) + mock_session().get.side_effect = tuple(next(chn) for _ in range(100)) + + +def create_notice_cache_files( + cache_dir: Path, + cache_files: Sequence[str], + messages_json_seq: Sequence[dict], +) -> None: + """Creates the cache files that we use in tests""" + for message_json, file in zip(messages_json_seq, cache_files): + with cache_dir.joinpath(file).open("w") as fp: + json.dump(message_json, fp) + + +def offset_cache_file_mtime(mtime_offset) -> None: + """ + Allows for offsetting the mtime of the notices cache file. This is often + used to mock an older creation time the cache file. + """ + cache_file = get_notices_cache_file() + os.utime( + cache_file, + times=(cache_file.stat().st_atime, cache_file.stat().st_mtime - mtime_offset), + ) + + +class DummyArgs: + """Dummy object that sets all kwargs as object properties.""" + + def __init__(self, **kwargs): + self.no_ansi_colors = True + + for key, val in kwargs.items(): + setattr(self, key, val) + + +def notices_decorator_assert_message_in_stdout( + captured, + messages: Sequence[str], + dummy_mesg: str | None = None, + not_in: bool = False, +): + """ + Tests a run of notices decorator where we expect to see the messages + print to stdout. + """ + assert captured.err == "" + assert dummy_mesg in captured.out + + for mesg in messages: + if not_in: + assert mesg not in captured.out + else: + assert mesg in captured.out + + +class MockResponse: + def __init__(self, status_code, json_data, raise_exc=False): + self.status_code = status_code + self.json_data = json_data + self.raise_exc = raise_exc + + def json(self): + if self.raise_exc: + raise ValueError("Error") + return self.json_data + + +def get_notice_cache_filenames(ctx: Context) -> tuple[str]: + """Returns the filenames of the cache files that will be searched for""" + channel_urls_and_names = get_channel_name_and_urls(get_channel_objs(ctx)) + + return tuple( + ChannelNoticeResponse.get_cache_key(url, Path("")).name + for url, name in channel_urls_and_names + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda/testing/solver_helpers.py b/miniconda3/lib/python3.13/site-packages/conda/testing/solver_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..6e900a2a90526d1216f630ea50d3f81eb8a880de --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/testing/solver_helpers.py @@ -0,0 +1,1324 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Helpers for testing the solver.""" + +from __future__ import annotations + +import collections +import functools +import pathlib +import time +from tempfile import TemporaryDirectory + +import pytest + +from ..base.context import context +from ..common.serialize import json +from ..core.solve import Solver +from ..exceptions import ( + PackagesNotFoundError, + ResolvePackageNotFound, + UnsatisfiableError, +) +from ..models.channel import Channel +from ..models.match_spec import MatchSpec +from ..models.records import PackageRecord +from . import helpers + + +@functools.cache +def index_packages(num): + """Get the index data of the ``helpers.get_index_r_*`` helpers.""" + # XXX: get_index_r_X should probably be refactored to avoid loading the environment like this. + get_index = getattr(helpers, f"get_index_r_{num}") + index, _ = get_index(context.subdir) + return list(index.values()) + + +def package_string(record): + return f"{record.channel.name}::{record.name}-{record.version}-{record.build}" + + +def package_string_set(packages): + """Transforms package container in package string set.""" + return {package_string(record) for record in packages} + + +def package_dict(packages): + """Transforms package container into a dictionary.""" + return {record.name: record for record in packages} + + +class SimpleEnvironment: + """Helper environment object.""" + + REPO_DATA_KEYS = ( + "build", + "build_number", + "depends", + "license", + "md5", + "name", + "sha256", + "size", + "subdir", + "timestamp", + "version", + "track_features", + "features", + ) + + def __init__(self, path, solver_class, subdirs=context.subdirs): + self._path = pathlib.Path(path) + self._prefix_path = self._path / "prefix" + self._channels_path = self._path / "channels" + self._solver_class = solver_class + self.subdirs = subdirs + self.installed_packages = [] + # if repo_packages is a list, the packages will be put in a `test` channel + # if it is a dictionary, it the keys are the channel name and the value + # the channel packages + self.repo_packages: list[str] | dict[str, list[str]] = [] + + def solver(self, add, remove): + """Writes ``repo_packages`` to the disk and creates a solver instance.""" + channels = [] + self._write_installed_packages() + for channel_name, packages in self._channel_packages.items(): + self._write_repo_packages(channel_name, packages) + channel = Channel(str(self._channels_path / channel_name)) + channels.append(channel) + return self._solver_class( + prefix=self._prefix_path, + subdirs=self.subdirs, + channels=channels, + specs_to_add=add, + specs_to_remove=remove, + ) + + def solver_transaction(self, add=(), remove=(), as_specs=False): + packages = self.solver(add=add, remove=remove).solve_final_state() + if as_specs: + return packages + return package_string_set(packages) + + def install(self, *specs, as_specs=False): + return self.solver_transaction(add=specs, as_specs=as_specs) + + def remove(self, *specs, as_specs=False): + return self.solver_transaction(remove=specs, as_specs=as_specs) + + @property + def _channel_packages(self): + """Helper that unfolds the ``repo_packages`` into a dictionary.""" + if isinstance(self.repo_packages, dict): + return self.repo_packages + return {"test": self.repo_packages} + + def _package_data(self, record): + """Turn record into data, to be written in the JSON environment/repo files.""" + data = { + key: value + for key, value in vars(record).items() + if key in self.REPO_DATA_KEYS + } + if "subdir" not in data: + data["subdir"] = context.subdir + return data + + def _write_installed_packages(self): + if not self.installed_packages: + return + conda_meta = self._prefix_path / "conda-meta" + conda_meta.mkdir(exist_ok=True, parents=True) + # write record files + for record in self.installed_packages: + record_path = ( + conda_meta / f"{record.name}-{record.version}-{record.build}.json" + ) + record_data = self._package_data(record) + record_data["channel"] = record.channel.name + record_path.write_text(json.dumps(record_data)) + # write history file + history_path = conda_meta / "history" + history_path.write_text( + "\n".join( + ( + "==> 2000-01-01 00:00:00 <==", + *map(package_string, self.installed_packages), + ) + ) + ) + + def _write_repo_packages(self, channel_name, packages): + """Write packages to the channel path.""" + # build package data + package_data = collections.defaultdict(dict) + for record in packages: + package_data[record.subdir][record.fn] = self._package_data(record) + # write repodata + assert set(self.subdirs).issuperset(set(package_data.keys())) + for subdir in self.subdirs: + subdir_path = self._channels_path / channel_name / subdir + subdir_path.mkdir(parents=True, exist_ok=True) + subdir_path.joinpath("repodata.json").write_text( + json.dumps( + { + "info": { + "subdir": subdir, + }, + "packages": package_data.get(subdir, {}), + } + ) + ) + + +def empty_prefix(): + return TemporaryDirectory(prefix="conda-test-repo-") + + +@pytest.fixture() +def temp_simple_env(solver_class=Solver) -> SimpleEnvironment: + with empty_prefix() as prefix: + yield SimpleEnvironment(prefix, solver_class) + + +class SolverTests: + """Tests for :py:class:`conda.core.solve.Solver` implementations.""" + + @property + def solver_class(self) -> type[Solver]: + """Class under test.""" + raise NotImplementedError + + @property + def tests_to_skip(self): + return {} # skip reason -> list of tests to skip + + @pytest.fixture(autouse=True) + def skip_tests(self, request): + for reason, skip_list in self.tests_to_skip.items(): + if request.node.name in skip_list: + pytest.skip(reason) + + @pytest.fixture() + def env(self): + with TemporaryDirectory(prefix="conda-test-repo-") as tmpdir: + self.env = SimpleEnvironment(tmpdir, self.solver_class) + yield self.env + self.env = None + + def find_package_in_list(self, packages, **kwargs): + for record in packages: + if all(getattr(record, key) == value for key, value in kwargs.items()): + return record + + def find_package(self, **kwargs): + if isinstance(self.env.repo_packages, dict): + if "channel" not in kwargs: + raise ValueError( + "Repo has multiple channels, the `channel` argument must be specified" + ) + packages = self.env.repo_packages[kwargs["channel"]] + else: + packages = self.env.repo_packages + return self.find_package_in_list(packages, **kwargs) + + def assert_unsatisfiable(self, exc_info, entries): + """Helper to assert that a :py:class:`conda.exceptions.UnsatisfiableError` + instance as a the specified set of unsatisfiable specifications. + """ + assert issubclass(exc_info.type, UnsatisfiableError) + if exc_info.type is UnsatisfiableError: + assert ( + sorted( + tuple(map(str, entries)) for entries in exc_info.value.unsatisfiable + ) + == entries + ) + + def test_empty(self, env): + env.repo_packages = index_packages(1) + assert env.install() == set() + + def test_iopro_mkl(self, env): + env.repo_packages = index_packages(1) + assert env.install("iopro 1.4*", "python 2.7*", "numpy 1.7*") == { + "test::iopro-1.4.3-np17py27_p0", + "test::numpy-1.7.1-py27_0", + "test::openssl-1.0.1c-0", + "test::python-2.7.5-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::unixodbc-2.3.1-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py27_1", + "test::pip-1.3.1-py27_1", + } + + def test_iopro_nomkl(self, env): + env.repo_packages = index_packages(1) + assert env.install( + "iopro 1.4*", "python 2.7*", "numpy 1.7*", MatchSpec(track_features="mkl") + ) == { + "test::iopro-1.4.3-np17py27_p0", + "test::mkl-rt-11.0-p0", + "test::numpy-1.7.1-py27_p0", + "test::openssl-1.0.1c-0", + "test::python-2.7.5-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::unixodbc-2.3.1-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py27_1", + "test::pip-1.3.1-py27_1", + } + + def test_mkl(self, env): + env.repo_packages = index_packages(1) + assert env.install("mkl") == env.install( + "mkl 11*", MatchSpec(track_features="mkl") + ) + + def test_accelerate(self, env): + env.repo_packages = index_packages(1) + assert env.install("accelerate") == env.install( + "accelerate", MatchSpec(track_features="mkl") + ) + + def test_scipy_mkl(self, env): + env.repo_packages = index_packages(1) + records = env.install( + "scipy", + "python 2.7*", + "numpy 1.7*", + MatchSpec(track_features="mkl"), + as_specs=True, + ) + + for record in records: + if record.name in ("numpy", "scipy"): + assert "mkl" in record.features + + assert "test::numpy-1.7.1-py27_p0" in package_string_set(records) + assert "test::scipy-0.12.0-np17py27_p0" in package_string_set(records) + + def test_anaconda_nomkl(self, env): + env.repo_packages = index_packages(1) + records = env.install("anaconda 1.5.0", "python 2.7*", "numpy 1.7*") + assert len(records) == 107 + assert "test::scipy-0.12.0-np17py27_0" in records + + def test_pseudo_boolean(self, env): + env.repo_packages = index_packages(1) + # The latest version of iopro, 1.5.0, was not built against numpy 1.5 + assert env.install("iopro", "python 2.7*", "numpy 1.5*") == { + "test::iopro-1.4.3-np15py27_p0", + "test::numpy-1.5.1-py27_4", + "test::openssl-1.0.1c-0", + "test::python-2.7.5-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::unixodbc-2.3.1-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py27_1", + "test::pip-1.3.1-py27_1", + } + assert env.install( + "iopro", "python 2.7*", "numpy 1.5*", MatchSpec(track_features="mkl") + ) == { + "test::iopro-1.4.3-np15py27_p0", + "test::mkl-rt-11.0-p0", + "test::numpy-1.5.1-py27_p4", + "test::openssl-1.0.1c-0", + "test::python-2.7.5-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::unixodbc-2.3.1-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py27_1", + "test::pip-1.3.1-py27_1", + } + + def test_unsat_from_r1(self, env): + env.repo_packages = index_packages(1) + + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("numpy 1.5*", "scipy 0.12.0b1") + self.assert_unsatisfiable( + exc_info, + [ + ("numpy=1.5",), + ("scipy==0.12.0b1", "numpy[version='1.6.*|1.7.*']"), + ], + ) + + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("numpy 1.5*", "python 3*") + self.assert_unsatisfiable( + exc_info, + [ + ("numpy=1.5", "nose", "python=3.3"), + ("numpy=1.5", "python[version='2.6.*|2.7.*']"), + ("python=3",), + ], + ) + + with pytest.raises((ResolvePackageNotFound, PackagesNotFoundError)) as exc_info: + env.install("numpy 1.5*", "numpy 1.6*") + if exc_info.type is ResolvePackageNotFound: + assert sorted(map(str, exc_info.value.bad_deps)) == [ + "numpy[version='1.5.*,1.6.*']", + ] + + def test_unsat_simple(self, env): + env.repo_packages = [ + helpers.record(name="a", depends=["c >=1,<2"]), + helpers.record(name="b", depends=["c >=2,<3"]), + helpers.record(name="c", version="1.0"), + helpers.record(name="c", version="2.0"), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("a", "b") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "c[version='>=1,<2']"), + ("b", "c[version='>=2,<3']"), + ], + ) + + def test_get_dists(self, env): + env.repo_packages = index_packages(1) + records = env.install("anaconda 1.4.0") + assert "test::anaconda-1.4.0-np17py33_0" in records + assert "test::freetype-2.4.10-0" in records + + def test_unsat_shortest_chain_1(self, env): + env.repo_packages = [ + helpers.record(name="a", depends=["d", "c <1.3.0"]), + helpers.record(name="b", depends=["c"]), + helpers.record( + name="c", + version="1.3.6", + ), + helpers.record( + name="c", + version="1.2.8", + ), + helpers.record(name="d", depends=["c >=0.8.0"]), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("c=1.3.6", "a", "b") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "c[version='<1.3.0']"), + ("a", "d", "c[version='>=0.8.0']"), + ("b", "c"), + ("c=1.3.6",), + ], + ) + + def test_unsat_shortest_chain_2(self, env): + env.repo_packages = [ + helpers.record(name="a", depends=["d", "c >=0.8.0"]), + helpers.record(name="b", depends=["c"]), + helpers.record( + name="c", + version="1.3.6", + ), + helpers.record( + name="c", + version="1.2.8", + ), + helpers.record(name="d", depends=["c <1.3.0"]), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("c=1.3.6", "a", "b") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "c[version='>=0.8.0']"), + ("a", "d", "c[version='<1.3.0']"), + ("b", "c"), + ("c=1.3.6",), + ], + ) + + def test_unsat_shortest_chain_3(self, env): + env.repo_packages = [ + helpers.record(name="a", depends=["f", "e"]), + helpers.record(name="b", depends=["c"]), + helpers.record( + name="c", + version="1.3.6", + ), + helpers.record( + name="c", + version="1.2.8", + ), + helpers.record(name="d", depends=["c >=0.8.0"]), + helpers.record(name="e", depends=["c <1.3.0"]), + helpers.record(name="f", depends=["d"]), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("c=1.3.6", "a", "b") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "e", "c[version='<1.3.0']"), + ("b", "c"), + ("c=1.3.6",), + ], + ) + + def test_unsat_shortest_chain_4(self, env): + env.repo_packages = [ + helpers.record(name="a", depends=["py =3.7.1"]), + helpers.record(name="py_req_1"), + helpers.record(name="py_req_2"), + helpers.record( + name="py", version="3.7.1", depends=["py_req_1", "py_req_2"] + ), + helpers.record( + name="py", version="3.6.1", depends=["py_req_1", "py_req_2"] + ), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("a", "py=3.6.1") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "py=3.7.1"), + ("py=3.6.1",), + ], + ) + + def test_unsat_chain(self, env): + # a -> b -> c=1.x -> d=1.x + # e -> c=2.x -> d=2.x + env.repo_packages = [ + helpers.record(name="a", depends=["b"]), + helpers.record(name="b", depends=["c >=1,<2"]), + helpers.record(name="c", version="1.0", depends=["d >=1,<2"]), + helpers.record(name="d", version="1.0"), + helpers.record(name="e", depends=["c >=2,<3"]), + helpers.record(name="c", version="2.0", depends=["d >=2,<3"]), + helpers.record(name="d", version="2.0"), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("a", "e") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "b", "c[version='>=1,<2']"), + ("e", "c[version='>=2,<3']"), + ], + ) + + def test_unsat_any_two_not_three(self, env): + # can install any two of a, b and c but not all three + env.repo_packages = [ + helpers.record(name="a", version="1.0", depends=["d >=1,<2"]), + helpers.record(name="a", version="2.0", depends=["d >=2,<3"]), + helpers.record(name="b", version="1.0", depends=["d >=1,<2"]), + helpers.record(name="b", version="2.0", depends=["d >=3,<4"]), + helpers.record(name="c", version="1.0", depends=["d >=2,<3"]), + helpers.record(name="c", version="2.0", depends=["d >=3,<4"]), + helpers.record(name="d", version="1.0"), + helpers.record(name="d", version="2.0"), + helpers.record(name="d", version="3.0"), + ] + # a and b can be installed + installed = env.install("a", "b", as_specs=True) + assert any(k.name == "a" and k.version == "1.0" for k in installed) + assert any(k.name == "b" and k.version == "1.0" for k in installed) + # a and c can be installed + installed = env.install("a", "c", as_specs=True) + assert any(k.name == "a" and k.version == "2.0" for k in installed) + assert any(k.name == "c" and k.version == "1.0" for k in installed) + # b and c can be installed + installed = env.install("b", "c", as_specs=True) + assert any(k.name == "b" and k.version == "2.0" for k in installed) + assert any(k.name == "c" and k.version == "2.0" for k in installed) + # a, b and c cannot be installed + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("a", "b", "c") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "d[version='>=1,<2|>=2,<3']"), + ("b", "d[version='>=1,<2|>=3,<4']"), + ("c", "d[version='>=2,<3|>=3,<4']"), + ], + ) + + def test_unsat_expand_single(self, env): + env.repo_packages = [ + helpers.record(name="a", depends=["b", "c"]), + helpers.record(name="b", depends=["d >=1,<2"]), + helpers.record(name="c", depends=["d >=2,<3"]), + helpers.record(name="d", version="1.0"), + helpers.record(name="d", version="2.0"), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("a") + self.assert_unsatisfiable( + exc_info, + [ + ("b", "d[version='>=1,<2']"), + ("c", "d[version='>=2,<3']"), + ], + ) + + def test_unsat_missing_dep(self, env): + env.repo_packages = [ + helpers.record(name="a", depends=["b", "c"]), + helpers.record(name="b", depends=["c >=2,<3"]), + helpers.record(name="c", version="1.0"), + ] + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("a", "b") + self.assert_unsatisfiable( + exc_info, + [ + ("a", "b"), + ("b",), + ], + ) + + def test_nonexistent(self, env): + with pytest.raises((ResolvePackageNotFound, PackagesNotFoundError)): + env.install("notarealpackage 2.0*") + with pytest.raises((ResolvePackageNotFound, PackagesNotFoundError)): + env.install("numpy 1.5") + + def test_timestamps_and_deps(self, env): + env.repo_packages = index_packages(1) + [ + helpers.record( + name="mypackage", + version="1.0", + build="hash12_0", + timestamp=1, + depends=["libpng 1.2.*"], + ), + helpers.record( + name="mypackage", + version="1.0", + build="hash15_0", + timestamp=0, + depends=["libpng 1.5.*"], + ), + ] + # libpng 1.2 + records_12 = env.install("libpng 1.2.*", "mypackage") + assert "test::libpng-1.2.50-0" in records_12 + assert "test::mypackage-1.0-hash12_0" in records_12 + # libpng 1.5 + records_15 = env.install("libpng 1.5.*", "mypackage") + assert "test::libpng-1.5.13-1" in records_15 + assert "test::mypackage-1.0-hash15_0" in records_15 + # this is testing that previously installed reqs are not disrupted + # by newer timestamps. regression test of sorts for + # https://github.com/conda/conda/issues/6271 + assert ( + env.install("mypackage", *env.install("libpng 1.2.*", as_specs=True)) + == records_12 + ) + assert ( + env.install("mypackage", *env.install("libpng 1.5.*", as_specs=True)) + == records_15 + ) + # unspecified python version should maximize libpng (v1.5), + # even though it has a lower timestamp + assert env.install("mypackage") == records_15 + + def test_nonexistent_deps(self, env): + env.repo_packages = index_packages(1) + [ + helpers.record( + name="mypackage", + version="1.0", + depends=["nose", "python 3.3*", "notarealpackage 2.0*"], + ), + helpers.record( + name="mypackage", + version="1.1", + depends=["nose", "python 3.3*"], + ), + helpers.record( + name="anotherpackage", + version="1.0", + depends=["nose", "mypackage 1.1"], + ), + helpers.record( + name="anotherpackage", + version="2.0", + depends=["nose", "mypackage"], + ), + ] + # XXX: missing find_matches and reduced_index + assert env.install("mypackage") == { + "test::mypackage-1.1-0", + "test::nose-1.3.0-py33_0", + "test::openssl-1.0.1c-0", + "test::python-3.3.2-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py33_1", + "test::pip-1.3.1-py33_1", + } + assert env.install("anotherpackage 1.0") == { + "test::anotherpackage-1.0-0", + "test::mypackage-1.1-0", + "test::nose-1.3.0-py33_0", + "test::openssl-1.0.1c-0", + "test::python-3.3.2-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py33_1", + "test::pip-1.3.1-py33_1", + } + assert env.install("anotherpackage") == { + "test::anotherpackage-2.0-0", + "test::mypackage-1.1-0", + "test::nose-1.3.0-py33_0", + "test::openssl-1.0.1c-0", + "test::python-3.3.2-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py33_1", + "test::pip-1.3.1-py33_1", + } + + # Add 1s to make sure the new repodata.jsons have different mod times + time.sleep(1) + + # This time, the latest version is messed up + env.repo_packages = index_packages(1) + [ + helpers.record( + name="mypackage", + version="1.0", + depends=["nose", "python 3.3*"], + ), + helpers.record( + name="mypackage", + version="1.1", + depends=["nose", "python 3.3*", "notarealpackage 2.0*"], + ), + helpers.record( + name="anotherpackage", + version="1.0", + depends=["nose", "mypackage 1.0"], + ), + helpers.record( + name="anotherpackage", + version="2.0", + depends=["nose", "mypackage"], + ), + ] + # XXX: missing find_matches and reduced_index + assert env.install("mypackage") == { + "test::mypackage-1.0-0", + "test::nose-1.3.0-py33_0", + "test::openssl-1.0.1c-0", + "test::python-3.3.2-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py33_1", + "test::pip-1.3.1-py33_1", + } + # TODO: We need UnsatisfiableError here because mamba does not + # have more granular exceptions yet. + with pytest.raises((ResolvePackageNotFound, UnsatisfiableError)): + env.install("mypackage 1.1") + assert env.install("anotherpackage 1.0") == { + "test::anotherpackage-1.0-0", + "test::mypackage-1.0-0", + "test::nose-1.3.0-py33_0", + "test::openssl-1.0.1c-0", + "test::python-3.3.2-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py33_1", + "test::pip-1.3.1-py33_1", + } + + # If recursive checking is working correctly, this will give + # anotherpackage 2.0, not anotherpackage 1.0 + assert env.install("anotherpackage") == { + "test::anotherpackage-2.0-0", + "test::mypackage-1.0-0", + "test::nose-1.3.0-py33_0", + "test::openssl-1.0.1c-0", + "test::python-3.3.2-0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + "test::distribute-0.6.36-py33_1", + "test::pip-1.3.1-py33_1", + } + + def test_install_package_with_feature(self, env): + env.repo_packages = index_packages(1) + [ + helpers.record( + name="mypackage", + version="1.0", + depends=["python 3.3*"], + features="feature", + ), + helpers.record( + name="feature", + version="1.0", + depends=["python 3.3*"], + track_features="feature", + ), + ] + # should not raise + env.install("mypackage", "feature 1.0") + + def test_unintentional_feature_downgrade(self, env): + # See https://github.com/conda/conda/issues/6765 + # With the bug in place, this bad build of scipy + # will be selected for install instead of a later + # build of scipy 0.11.0. + good_rec_match = MatchSpec("channel-1::scipy==0.11.0=np17py33_3") + good_rec = next( + prec for prec in index_packages(1) if good_rec_match.match(prec) + ) + bad_deps = tuple(d for d in good_rec.depends if not d.startswith("numpy")) + bad_rec = PackageRecord.from_objects( + good_rec, + channel="test", + build=good_rec.build.replace("_3", "_x0"), + build_number=0, + depends=bad_deps, + fn=good_rec.fn.replace("_3", "_x0"), + url=good_rec.url.replace("_3", "_x0"), + ) + + env.repo_packages = index_packages(1) + [bad_rec] + records = env.install("scipy 0.11.0") + assert "test::scipy-0.11.0-np17py33_x0" not in records + assert "test::scipy-0.11.0-np17py33_3" in records + + def test_circular_dependencies(self, env): + env.repo_packages = index_packages(1) + [ + helpers.record( + name="package1", + depends=["package2"], + ), + helpers.record( + name="package2", + depends=["package1"], + ), + ] + assert ( + env.install("package1", "package2") + == env.install("package1") + == env.install("package2") + ) + + def test_irrational_version(self, env): + env.repo_packages = index_packages(1) + assert env.install("pytz 2012d", "python 3*") == { + "test::distribute-0.6.36-py33_1", + "test::openssl-1.0.1c-0", + "test::pip-1.3.1-py33_1", + "test::python-3.3.2-0", + "test::pytz-2012d-py33_0", + "test::readline-6.2-0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + + def test_no_features(self, env): + env.repo_packages = index_packages(1) + + assert env.install("python 2.6*", "numpy 1.6*", "scipy 0.11*") == { + "test::distribute-0.6.36-py26_1", + "test::numpy-1.6.2-py26_4", + "test::openssl-1.0.1c-0", + "test::pip-1.3.1-py26_1", + "test::python-2.6.8-6", + "test::readline-6.2-0", + "test::scipy-0.11.0-np16py26_3", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + assert env.install( + "python 2.6*", "numpy 1.6*", "scipy 0.11*", MatchSpec(track_features="mkl") + ) == { + "test::distribute-0.6.36-py26_1", + "test::mkl-rt-11.0-p0", + "test::numpy-1.6.2-py26_p4", + "test::openssl-1.0.1c-0", + "test::pip-1.3.1-py26_1", + "test::python-2.6.8-6", + "test::readline-6.2-0", + "test::scipy-0.11.0-np16py26_p3", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + + env.repo_packages += [ + helpers.record( + name="pandas", + version="0.12.0", + build="np16py27_0", + depends=[ + "dateutil", + "numpy 1.6*", + "python 2.7*", + "pytz", + ], + ), + helpers.record( + name="numpy", + version="1.6.2", + build="py27_p5", + build_number=0, + depends=[ + "mkl-rt 11.0", + "python 2.7", + ], + features="mkl", + ), + ] + assert env.install("pandas 0.12.0 np16py27_0", "python 2.7*") == { + "test::dateutil-2.1-py27_1", + "test::distribute-0.6.36-py27_1", + "test::numpy-1.6.2-py27_4", + "test::openssl-1.0.1c-0", + "test::pandas-0.12.0-np16py27_0", + "test::pip-1.3.1-py27_1", + "test::python-2.7.5-0", + "test::pytz-2013b-py27_0", + "test::readline-6.2-0", + "test::six-1.3.0-py27_0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + assert env.install( + "pandas 0.12.0 np16py27_0", "python 2.7*", MatchSpec(track_features="mkl") + ) == { + "test::dateutil-2.1-py27_1", + "test::distribute-0.6.36-py27_1", + "test::mkl-rt-11.0-p0", + "test::numpy-1.6.2-py27_p4", + "test::openssl-1.0.1c-0", + "test::pandas-0.12.0-np16py27_0", + "test::pip-1.3.1-py27_1", + "test::python-2.7.5-0", + "test::pytz-2013b-py27_0", + "test::readline-6.2-0", + "test::six-1.3.0-py27_0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + + @pytest.mark.xfail(reason="CONDA_CHANNEL_PRIORITY does not seem to have any effect") + def test_channel_priority_1(self, monkeypatch, env): + # XXX: Test is skipped because CONDA_CHANNEL_PRIORITY does not seems to + # have any effect. I have also tried conda.common.io.env_var like + # the other tests but no luck. + env.repo_packages = {} + env.repo_packages["channel-A"] = [] + env.repo_packages["channel-1"] = index_packages(1) + + pandas_0 = self.find_package( + channel="channel-1", + name="pandas", + version="0.10.1", + build="np17py27_0", + ) + env.repo_packages["channel-A"].append(pandas_0) + + # channel-1 has pandas np17py27_1, channel-A only has np17py27_0 + # when priority is set, it channel-A should take precedence and + # np17py27_0 be installed, otherwise np17py27_1 should be installed as + # it has a higher build version + monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") + assert "channel-A::pandas-0.11.0-np16py27_0" in env.install( + "pandas", "python 2.7*", "numpy 1.6*" + ) + monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "False") + assert "channel-1::pandas-0.11.0-np16py27_1" in env.install( + "pandas", "python 2.7*", "numpy 1.6*" + ) + # now lets revert the channels + env.repo_packages = dict(reversed(env.repo_packages.items())) + monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") + assert "channel-1::pandas-0.11.0-np16py27_1" in env.install( + "pandas", "python 2.7*", "numpy 1.6*" + ) + + @pytest.mark.xfail(reason="CONDA_CHANNEL_PRIORITY does not seem to have any effect") + def test_unsat_channel_priority(self, monkeypatch, env): + # XXX: Test is skipped because CONDA_CHANNEL_PRIORITY does not seems to + # have any effect. I have also tried conda.common.io.env_var like + # the other tests but no luck. + env.repo_packages = {} + # higher priority + env.repo_packages["channel-1"] = [ + helpers.record( + name="a", + version="1.0", + depends=["c"], + ), + helpers.record( + name="b", + version="1.0", + depends=["c >=2,<3"], + ), + helpers.record( + name="c", + version="1.0", + ), + ] + # lower priority, missing c 2.0 + env.repo_packages["channel-2"] = [ + helpers.record( + name="a", + version="2.0", + depends=["c"], + ), + helpers.record( + name="b", + version="2.0", + depends=["c >=2,<3"], + ), + helpers.record( + name="c", + version="1.0", + ), + helpers.record( + name="c", + version="2.0", + ), + ] + + monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") + records = env.install("a", "b", as_specs=True) + # channel-1 a and b packages (1.0) installed + assert any(k.name == "a" and k.version == "1.0" for k in records) + assert any(k.name == "b" and k.version == "1.0" for k in records) + + monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "False") + records = env.install("a", "b", as_specs=True) + # no channel priority, largest version of a and b (2.0) installed + assert any(k.name == "a" and k.version == "2.0" for k in records) + assert any(k.name == "b" and k.version == "2.0" for k in records) + + monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") + with pytest.raises(UnsatisfiableError) as exc_info: + env.install("a", "b") + self.assert_unsatisfiable(exc_info, [("b", "c[version='>=2,<3']")]) + + @pytest.mark.xfail( + reason="There is some weird global state making " + "this test fail when the whole test suite is run" + ) + def test_remove(self, env): + env.repo_packages = index_packages(1) + records = env.install("pandas", "python 2.7*", as_specs=True) + assert package_string_set(records) == { + "test::dateutil-2.1-py27_1", + "test::distribute-0.6.36-py27_1", + "test::numpy-1.7.1-py27_0", + "test::openssl-1.0.1c-0", + "test::pandas-0.11.0-np17py27_1", + "test::pip-1.3.1-py27_1", + "test::python-2.7.5-0", + "test::pytz-2013b-py27_0", + "test::readline-6.2-0", + "test::scipy-0.12.0-np17py27_0", + "test::six-1.3.0-py27_0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + + env.installed_packages = records + assert env.remove("pandas") == { + "test::dateutil-2.1-py27_1", + "test::distribute-0.6.36-py27_1", + "test::numpy-1.7.1-py27_0", + "test::openssl-1.0.1c-0", + "test::pip-1.3.1-py27_1", + "test::python-2.7.5-0", + "test::pytz-2013b-py27_0", + "test::readline-6.2-0", + "test::scipy-0.12.0-np17py27_0", + "test::six-1.3.0-py27_0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + assert env.remove("numpy") == { + "test::dateutil-2.1-py27_1", + "test::distribute-0.6.36-py27_1", + "test::openssl-1.0.1c-0", + "test::pip-1.3.1-py27_1", + "test::python-2.7.5-0", + "test::pytz-2013b-py27_0", + "test::readline-6.2-0", + "test::six-1.3.0-py27_0", + "test::sqlite-3.7.13-0", + "test::system-5.8-1", + "test::tk-8.5.13-0", + "test::zlib-1.2.7-0", + } + + def test_surplus_features_1(self, env): + env.repo_packages += [ + helpers.record( + name="feature", + track_features="feature", + ), + helpers.record( + name="package1", + features="feature", + ), + helpers.record( + name="package2", + version="1.0", + features="feature", + depends=["package1"], + ), + helpers.record( + name="package2", + version="2.0", + features="feature", + ), + ] + assert env.install("package2", "feature") == { + "test::package2-2.0-0", + "test::feature-1.0-0", + } + + def test_surplus_features_2(self, env): + env.repo_packages += [ + helpers.record( + name="feature", + track_features="feature", + ), + helpers.record( + name="package1", + features="feature", + ), + helpers.record( + name="package2", + version="1.0", + build_number=0, + features="feature", + depends=["package1"], + ), + helpers.record( + name="package2", + version="1.0", + build_number=1, + features="feature", + ), + ] + assert env.install("package2", "feature") == { + "test::package2-1.0-0", + "test::feature-1.0-0", + } + + def test_get_reduced_index_broadening_with_unsatisfiable_early_dep(self, env): + # Test that spec broadening reduction doesn't kill valid solutions + # In other words, the order of packages in the index should not affect the + # overall result of the reduced index. + # see discussion at https://github.com/conda/conda/pull/8117#discussion_r249249815 + env.repo_packages += [ + helpers.record( + name="a", + version="1.0", + # not satisfiable. This record should come first, so that its c==2 + # constraint tries to mess up the inclusion of the c record below, + # which should be included as part of b's deps, but which is + # broader than this dep. + depends=["b", "c==2"], + ), + helpers.record( + name="a", + version="2.0", + depends=["b"], + ), + helpers.record( + name="b", + depends=["c"], + ), + helpers.record( + name="c", + ), + ] + assert env.install("a") == { + "test::a-2.0-0", + "test::b-1.0-0", + "test::c-1.0-0", + } + + def test_get_reduced_index_broadening_preferred_solution(self, env): + # test that order of index reduction does not eliminate what should be a preferred solution + # https://github.com/conda/conda/pull/8117#discussion_r249216068 + env.repo_packages += [ + helpers.record( + name="top", + version="1.0", + # this is the first processed record, and imposes a broadening constraint on bottom + # if things are overly restricted, we'll end up with bottom 1.5 in our solution + # instead of the preferred (latest) 2.5 + depends=["middle", "bottom==1.5"], + ), + helpers.record( + name="top", + version="2.0", + depends=["middle"], + ), + helpers.record( + name="middle", + depends=["bottom"], + ), + helpers.record( + name="bottom", + version="1.5", + ), + helpers.record( + name="bottom", + version="2.5", + ), + ] + for record in env.install("top", as_specs=True): + if record.name == "top": + assert record.version == "2.0", ( + f"top version should be 2.0, but is {record.version}" + ) + elif record.name == "bottom": + assert record.version == "2.5", ( + f"bottom version should be 2.5, but is {record.version}" + ) + + def test_arch_preferred_over_noarch_when_otherwise_equal(self, env): + env.repo_packages += [ + helpers.record( + name="package1", + subdir="noarch", + ), + helpers.record( + name="package1", + ), + ] + records = env.install("package1", as_specs=True) + assert len(records) == 1 + assert records[0].subdir == context.subdir + + def test_noarch_preferred_over_arch_when_version_greater(self, env): + env.repo_packages += [ + helpers.record( + name="package1", + version="2.0", + subdir="noarch", + ), + helpers.record( + name="package1", + version="1.0", + ), + ] + records = env.install("package1", as_specs=True) + assert len(records) == 1 + assert records[0].subdir == "noarch" + + def test_noarch_preferred_over_arch_when_version_greater_dep(self, env): + env.repo_packages += [ + helpers.record( + name="package1", + version="1.0", + ), + helpers.record( + name="package1", + version="2.0", + subdir="noarch", + ), + helpers.record( + name="package2", + depends=["package1"], + ), + ] + records = env.install("package2", as_specs=True) + package1 = self.find_package_in_list(records, name="package1") + assert package1.subdir == "noarch" + + def test_noarch_preferred_over_arch_when_build_greater(self, env): + env.repo_packages += [ + helpers.record( + name="package1", + build_number=0, + ), + helpers.record( + name="package1", + build_number=1, + subdir="noarch", + ), + ] + records = env.install("package1", as_specs=True) + assert len(records) == 1 + assert records[0].subdir == "noarch" + + def test_noarch_preferred_over_arch_when_build_greater_dep(self, env): + env.repo_packages += [ + helpers.record( + name="package1", + build_number=0, + ), + helpers.record( + name="package1", + build_number=1, + subdir="noarch", + ), + helpers.record( + name="package2", + depends=["package1"], + ), + ] + records = env.install("package2", as_specs=True) + package1 = self.find_package_in_list(records, name="package1") + assert package1.subdir == "noarch" diff --git a/miniconda3/lib/python3.13/site-packages/conda/trust/__init__.py b/miniconda3/lib/python3.13/site-packages/conda/trust/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b601a4b66b017829b4b3733eaa823a94c07f9a13 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/trust/__init__.py @@ -0,0 +1,8 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause + +from ..deprecations import deprecated + +# Mark the entire module for deprecation. For more information see +# https://github.com/conda/conda-content-trust and #14797 +deprecated.module("25.9", "26.3") diff --git a/miniconda3/lib/python3.13/site-packages/conda/trust/constants.py b/miniconda3/lib/python3.13/site-packages/conda/trust/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a65f0ff428a564d9c6d4d40c9fe420c99b37e4f2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/trust/constants.py @@ -0,0 +1,64 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Context trust constants. + +You could argue that the signatures being here is not necessary; indeed, we +are not necessarily going to be able to check them *properly* (based on some +prior expectations) as the user, since this is the beginning of trust +bootstrapping, the first/backup version of the root of trust metadata. +Still, the signatures here are useful for diagnostic purposes, and, more +important, to allow self-consistency checks: that helps us avoid breaking the +chain of trust if someone accidentally lists the wrong keys down the line. (: +The discrepancy can be detected when loading the root data, and we can +decline to cache incorrect trust metadata that would make further root +updates impossible. +""" + +from ..deprecations import deprecated + +# Mark the entire module for deprecation. For more information see +# https://github.com/conda/conda-content-trust and #14797 +deprecated.module( + "25.9", # deprecate_in version + "26.3", # remove_in version + addendum="This module will be moved to conda-anaconda-trust-root.", +) + +INITIAL_TRUST_ROOT = { + "signatures": { + "6d4d5888398ad77465e9fd53996309187723e16509144aa6733015c960378e7a": { + "other_headers": "04001608001d162104d2ca1d4bf5d77e7c312534284dd9c45328b685ec0502605dbb03", + "signature": "b71c9b3aa60e77258c402e574397127bcb4bc15ef3055ada8539b0d1e355bf1415a135fb7cecc9244f839a929f6b1f82844a5b3df8d6225ec9a50b181692490f", + }, + "508debb915ede0b16dc0cff63f250bde73c5923317b44719fcfc25cc95560c44": { + "other_headers": "04001608001d162104e6dffee4638f24cfa60a08ba03afe1314a3a38fc050260621281", + "signature": "29d53d4e7dbea0a3efb07266d22e57cf4df7abe004453981c631245716e1b737c7a6b4ab95f42592af70be67abf56e97020e1aa1f52b49ef39b37481f05d5701", + }, + }, + "signed": { + "delegations": { + "key_mgr": { + "pubkeys": [ + "f24c813d23a9b26be665eee5c54680c35321061b337f862385ed6d783b0bedb0" + ], + "threshold": 1, + }, + "root": { + "pubkeys": [ + "668a3217d72d4064edb16648435dc4a3e09a172ecee45dcab1464dcd2f402ec6", + "508debb915ede0b16dc0cff63f250bde73c5923317b44719fcfc25cc95560c44", + "6d4d5888398ad77465e9fd53996309187723e16509144aa6733015c960378e7a", + "e0c88b4c0721bd451b7e720dfb0d0bb6b3853f0cbcf5570edd73367d0841be51", + ], + "threshold": 2, + }, + }, + "expiration": "2022-10-31T18:00:00Z", + "metadata_spec_version": "0.6.0", + "timestamp": "2021-03-26T00:00:00Z", + "type": "root", + "version": 1, + }, +} + +KEY_MGR_FILE = "key_mgr.json" diff --git a/miniconda3/lib/python3.13/site-packages/conda/trust/signature_verification.py b/miniconda3/lib/python3.13/site-packages/conda/trust/signature_verification.py new file mode 100644 index 0000000000000000000000000000000000000000..80d4f9426373a6f34270fa6461bcf3f8dc3ac548 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/trust/signature_verification.py @@ -0,0 +1,325 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Interface between conda-content-trust and conda.""" + +from __future__ import annotations + +import os +import re +import warnings +from functools import cache +from logging import getLogger +from pathlib import Path + +from ..common.serialize import json + +try: + from conda_content_trust.authentication import verify_delegation, verify_root + from conda_content_trust.common import ( + SignatureError, + load_metadata_from_file, + write_metadata_to_file, + ) + from conda_content_trust.signing import wrap_as_signable +except ImportError: + # _SignatureVerification.enabled handles the rest of this state + class SignatureError(Exception): + pass + + +from typing import TYPE_CHECKING + +from ..base.constants import CONDA_PACKAGE_EXTENSION_V1, CONDA_PACKAGE_EXTENSION_V2 +from ..base.context import context +from ..common.url import join_url +from ..core.subdir_data import SubdirData +from ..deprecations import deprecated +from ..gateways.connection import HTTPError, InsecureRequestWarning +from ..gateways.connection.session import get_session +from .constants import INITIAL_TRUST_ROOT, KEY_MGR_FILE + +if TYPE_CHECKING: + from ..models.records import PackageRecord + +# Mark the entire module for deprecation. For more information see +# https://github.com/conda/conda-content-trust and #14797 +deprecated.module( + "25.9", # deprecate_in version + "26.3", # remove_in version + addendum="This module will be moved to conda-content-trust.", +) + + +log = getLogger(__name__) + + +RE_ROOT_METADATA = re.compile(r"(?P\d+)\.root\.json") + + +class _SignatureVerification: + @property + @cache + def enabled(self) -> bool: + # safety checks must be enabled + if not context.extra_safety_checks: + return False + + # signing url must be defined + if not context.signing_metadata_url_base: + log.warning( + "metadata signature verification requested, " + "but no metadata URL base has not been specified." + ) + return False + + # conda_content_trust must be installed + try: + import conda_content_trust # noqa: F401 + except ImportError: + log.warning( + "metadata signature verification requested, " + "but `conda-content-trust` is not installed." + ) + return False + + # ensure artifact verification directory exists + Path(context.av_data_dir).mkdir(parents=True, exist_ok=True) + + # ensure the trusted_root exists + if self.trusted_root is None: + log.warning( + "could not find trusted_root data for metadata signature verification" + ) + return False + + # ensure the key_mgr exists + if self.key_mgr is None: + log.warning( + "could not find key_mgr data for metadata signature verification" + ) + return False + + # signature verification is enabled + return True + + @property + @cache + def trusted_root(self) -> dict: + # TODO: formalize paths for `*.root.json` and `key_mgr.json` on server-side + trusted: dict | None = None + + # Load latest trust root metadata from filesystem + try: + paths = { + int(m.group("number")): entry + for entry in os.scandir(context.av_data_dir) + if (m := RE_ROOT_METADATA.match(entry.name)) + } + except (FileNotFoundError, NotADirectoryError, PermissionError): + # FileNotFoundError: context.av_data_dir does not exist + # NotADirectoryError: context.av_data_dir is not a directory + # PermsissionError: context.av_data_dir is not readable + pass + else: + for _, entry in sorted(paths.items(), reverse=True): + log.info(f"Loading root metadata from {entry}.") + try: + trusted = load_metadata_from_file(entry) + except (IsADirectoryError, FileNotFoundError, PermissionError): + # IsADirectoryError: entry is not a file + # FileNotFoundError: entry does not exist + # PermsissionError: entry is not readable + continue + else: + break + + # Fallback to default root metadata if unable to fetch any + if not trusted: + log.debug( + f"No root metadata in {context.av_data_dir}. " + "Using built-in root metadata." + ) + trusted = INITIAL_TRUST_ROOT + + # Refresh trust root metadata + while True: + # TODO: caching mechanism to reduce number of refresh requests + fname = f"{trusted['signed']['version'] + 1}.root.json" + path = Path(context.av_data_dir, fname) + + try: + # TODO: support fetching root data with credentials + untrusted = self._fetch_channel_signing_data( + context.signing_metadata_url_base, + fname, + ) + + verify_root(trusted, untrusted) + except HTTPError as err: + # HTTP 404 implies no updated root.json is available, which is + # not really an "error" and does not need to be logged. + if err.response.status_code != 404: + log.error(err) + break + except Exception as err: + # TODO: more error handling + log.error(err) + break + else: + # New trust root metadata checks out + write_metadata_to_file(trusted := untrusted, path) + + return trusted + + @property + @cache + def key_mgr(self) -> dict | None: + trusted: dict | None = None + + # Refresh key manager metadata + fname = KEY_MGR_FILE + path = Path(context.av_data_dir, fname) + + try: + untrusted = self._fetch_channel_signing_data( + context.signing_metadata_url_base, + fname, + ) + + verify_delegation("key_mgr", untrusted, self.trusted_root) + except ConnectionError as err: + log.warning(err) + except HTTPError as err: + # sometimes the HTTPError message is blank, when that occurs include the + # HTTP status code + log.warning( + str(err) or f"{err.__class__.__name__} ({err.response.status_code})" + ) + else: + # New key manager metadata checks out + write_metadata_to_file(trusted := untrusted, path) + + # If key_mgr is unavailable from server, fall back to copy on disk + if not trusted and path.exists(): + trusted = load_metadata_from_file(path) + + return trusted + + def _fetch_channel_signing_data( + self, signing_data_url: str, filename: str, etag=None, mod_stamp=None + ) -> dict: + session = get_session(signing_data_url) + + if not context.ssl_verify: + warnings.simplefilter("ignore", InsecureRequestWarning) + + headers = { + "Accept-Encoding": "gzip, deflate, compress, identity", + "Content-Type": "application/json", + } + if etag: + headers["If-None-Match"] = etag + if mod_stamp: + headers["If-Modified-Since"] = mod_stamp + + saved_token_setting = context.add_anaconda_token + try: + # Assume trust metadata is intended to be "generally available", + # and specifically, _not_ protected by a conda/binstar token. + # Seems reasonable, since we (probably) don't want the headaches of + # dealing with protected, per-channel trust metadata. + # + # Note: Setting `auth=None` here does allow trust metadata to be + # protected using standard HTTP basic auth mechanisms, with the + # login information being provided in the user's netrc file. + context.add_anaconda_token = False + resp = session.get( + join_url(signing_data_url, filename), + headers=headers, + proxies=session.proxies, + auth=None, + timeout=( + context.remote_connect_timeout_secs, + context.remote_read_timeout_secs, + ), + ) + # TODO: maybe add more sensible error handling + resp.raise_for_status() + finally: + context.add_anaconda_token = saved_token_setting + + # In certain cases (e.g., using `-c` access anaconda.org channels), the + # `CondaSession.get()` retry logic combined with the remote server's + # behavior can result in non-JSON content being returned. Parse returned + # content here (rather than directly in the return statement) so callers of + # this function only have to worry about a ValueError being raised. + try: + return resp.json() + except json.JSONDecodeError as err: # noqa + # TODO: additional loading and error handling improvements? + raise ValueError( + f"Invalid JSON returned from {signing_data_url}/{filename}" + ) + + def verify(self, repodata_fn: str, record: PackageRecord): + repodata, _ = SubdirData( + record.channel, + repodata_fn=repodata_fn, + ).repo_fetch.fetch_latest_parsed() + + # short-circuit if no signatures are defined + if "signatures" not in repodata: + record.metadata.add( + f"(no signatures found for {record.channel.canonical_name})" + ) + return + signatures = repodata["signatures"] + + # short-circuit if no signature is defined for this package + if record.fn not in signatures: + record.metadata.add(f"(no signatures found for {record.fn})") + return + signature = signatures[record.fn] + + # extract metadata to be verified + if record.fn.endswith(CONDA_PACKAGE_EXTENSION_V1): + info = repodata["packages"][record.fn] + elif record.fn.endswith(CONDA_PACKAGE_EXTENSION_V2): + info = repodata["packages.conda"][record.fn] + else: + raise ValueError("unknown package extension") + + # create a signable envelope (a dict with the info and signatures) + envelope = wrap_as_signable(info) + envelope["signatures"] = signature + + try: + verify_delegation("pkg_mgr", envelope, self.key_mgr) + except SignatureError: + log.warning(f"invalid signature for {record.fn}") + record.metadata.add("(package metadata is UNTRUSTED)") + else: + log.info(f"valid signature for {record.fn}") + record.metadata.add("(package metadata is TRUSTED)") + + def __call__( + self, + repodata_fn: str, + unlink_precs: tuple[PackageRecord, ...], + link_precs: tuple[PackageRecord, ...], + ) -> None: + if not self.enabled: + return + + for prec in link_precs: + self.verify(repodata_fn, prec) + + @classmethod + def cache_clear(cls) -> None: + cls.enabled.fget.cache_clear() + cls.trusted_root.fget.cache_clear() + cls.key_mgr.fget.cache_clear() + + +# singleton for caching +signature_verification = _SignatureVerification() diff --git a/miniconda3/lib/python3.13/site-packages/conda/utils.py b/miniconda3/lib/python3.13/site-packages/conda/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8667a07aa3152264d6fd97e08f9af4abf4c1435a --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda/utils.py @@ -0,0 +1,442 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Utility functions.""" + +from __future__ import annotations + +import logging +import re +import sys +from functools import cache, wraps +from os import environ +from os.path import abspath, basename, dirname, isfile, join +from pathlib import Path +from shutil import which +from typing import TYPE_CHECKING + +from . import CondaError +from .activate import _build_activator_cls +from .auxlib.compat import Utf8NamedTemporaryFile, shlex_split_unicode +from .common.compat import isiterable, on_win +from .common.url import path_to_url +from .deprecations import deprecated + +if TYPE_CHECKING: + from collections.abc import Sequence + +log = logging.getLogger(__name__) + + +@deprecated( + "25.3", + "26.3", + addendum="Use `conda.common.path.unix_path_to_win` instead.", +) +def unix_path_to_win(path, root_prefix=""): + """Convert a path or :-separated string of paths into a Windows representation + Does not add cygdrive. If you need that, set root_prefix to "/cygdrive" + """ + if len(path) > 1 and (";" in path or (path[1] == ":" and path.count(":") == 1)): + # already a windows path + return path.replace("/", "\\") + path_re = root_prefix + r'(/[a-zA-Z]/(?:(?![:\s]/)[^:*?"<>])*)' + + def _translation(found_path): + group = found_path.group(0) + return "{}:{}".format( + group[len(root_prefix) + 1], + group[len(root_prefix) + 2 :].replace("/", "\\"), + ) + + translation = re.sub(path_re, _translation, path) + translation = re.sub( + ":([a-zA-Z]):\\\\", lambda match: ";" + match.group(0)[1] + ":\\", translation + ) + return translation + + +deprecated.constant("25.3", "26.3", "unix_path_to_win", unix_path_to_win) +del unix_path_to_win + + +def human_bytes(n): + """ + Return the number of bytes n in more human readable form. + + Note: Uses SI prefixes (KB, MB, GB) instead of binary prefixes (KiB, MiB, GiB). + + Examples: + >>> human_bytes(42) + '42 B' + >>> human_bytes(1042) + '1 KB' + >>> human_bytes(10004242) + '9.5 MB' + >>> human_bytes(100000004242) + '93.13 GB' + """ + if n < 1024: + return "%d B" % n + k = n / 1024 + if k < 1024: + return "%d KB" % round(k) + m = k / 1024 + if m < 1024: + return f"{m:.1f} MB" + g = m / 1024 + return f"{g:.2f} GB" + + +# ########################################## +# put back because of conda build +# ########################################## + +urlpath = url_path = path_to_url + + +@cache +def sys_prefix_unfollowed(): + """Since conda is installed into non-root environments as a symlink only + and because sys.prefix follows symlinks, this function can be used to + get the 'unfollowed' sys.prefix. + + This value is usually the same as the prefix of the environment into + which conda has been symlinked. An example of when this is necessary + is when conda looks for external sub-commands in find_commands.py + """ + try: + frame = next(iter(sys._current_frames().values())) + while frame.f_back: + frame = frame.f_back + code = frame.f_code + filename = code.co_filename + unfollowed = dirname(dirname(filename)) + except Exception: + return sys.prefix + return unfollowed + + +def quote_for_shell(*arguments): + """Properly quote arguments for command line passing. + + For POSIX uses `shlex.join`, for Windows uses a custom implementation to properly escape + metacharacters. + + :param arguments: Arguments to quote. + :type arguments: list of str + :return: Quoted arguments. + :rtype: str + """ + # [backport] Support passing in a list of strings or args of string. + if len(arguments) == 1 and isiterable(arguments[0]): + arguments = arguments[0] + + return _args_join(arguments) + + +if on_win: + # https://ss64.com/nt/syntax-esc.html + # https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way + + _RE_UNSAFE = re.compile(r'["%\s^<>&|]') + _RE_DBL = re.compile(r'(["%])') + + def _args_join(args): + """Return a shell-escaped string from *args*.""" + + def quote(s): + # derived from shlex.quote + if not s: + return '""' + # if any unsafe chars are present we must quote + if not _RE_UNSAFE.search(s): + return s + # double escape (" -> "") + s = _RE_DBL.sub(r"\1\1", s) + # quote entire string + return f'"{s}"' + + return " ".join(quote(arg) for arg in args) + +else: + from shlex import join as _args_join + + +# Ensures arguments are a tuple or a list. Strings are converted +# by shlex_split_unicode() which is bad; we warn about it or else +# we assert (and fix the code). +@deprecated("26.9", "27.3") +def massage_arguments(arguments, errors="assert"): + # For reference and in-case anything breaks .. + # .. one of the places (run_command in conda_env/utils.py) this + # gets called from used to do this too: + # + # def escape_for_winpath(p): + # return p.replace('\\', '\\\\') + # + # if not isinstance(arguments, list): + # arguments = list(map(escape_for_winpath, arguments)) + + if isinstance(arguments, str): + if errors == "assert": + # This should be something like 'conda programming bug' + raise RuntimeError("Please ensure arguments are not strings") + else: + arguments = shlex_split_unicode(arguments) + log.warning( + "Please ensure arguments is not a string; " + "used `shlex_split_unicode()` on it" + ) + + if not isiterable(arguments): + arguments = (arguments,) + + if any(isiterable(arg) for arg in arguments): + raise ValueError("Individual arguments must not be iterable") + arguments = list(arguments) + + return arguments + + +@deprecated.argument( + "26.9", + "27.3", + "use_system_tmp_path", + addendum="Use the TMPDIR, TEMP, or TMP environment variables to set the system temporary directory location.", +) +def wrap_subprocess_call( + root_prefix, + prefix, + dev_mode, + debug_wrapper_scripts, + arguments: Sequence[str], +): + # Ensure arguments is a tuple of strings + if not isiterable(arguments): + raise TypeError("`arguments` must be iterable") + arguments = tuple(map(str, arguments)) + + script_caller = None + multiline = False + if len(arguments) == 1 and "\n" in arguments[0]: + multiline = True + if on_win: + comspec = get_comspec() # fail early with KeyError if undefined + + with Utf8NamedTemporaryFile(mode="w", suffix=".bat", delete=False) as fh: + silencer = "" if debug_wrapper_scripts else "@" + fh.write(f"{silencer}ECHO OFF\n") + fh.write(f"{silencer}SET PYTHONIOENCODING=utf-8\n") + fh.write(f"{silencer}SET PYTHONUTF8=1\n") + fh.write( + f'{silencer}FOR /F "tokens=2 delims=:." %%A in (\'chcp\') do for %%B in (%%A) do set "_CONDA_OLD_CHCP=%%B"\n' + ) + fh.write(f"{silencer}chcp 65001 > NUL\n") + if dev_mode: + from . import CONDA_SOURCE_ROOT + + fh.write(f"{silencer}SET CONDA_DEV=1\n") + # In dev mode, conda is really: + # 'python -m conda' + # *with* PYTHONPATH set. + fh.write(f"{silencer}SET PYTHONPATH={CONDA_SOURCE_ROOT}\n") + fh.write(f"{silencer}SET CONDA_EXE={sys.executable}\n") + fh.write(f"{silencer}SET _CE_M=-m\n") + fh.write(f"{silencer}SET _CE_CONDA=conda\n") + if debug_wrapper_scripts: + fh.write("echo *** environment before *** 1>&2\n") + fh.write("SET 1>&2\n") + # Not sure there is any point in backing this up, nothing will get called with it reset + # after all! + # fh.write("@FOR /F \"tokens=100\" %%F IN ('chcp') DO @SET CONDA_OLD_CHCP=%%F\n") + # fh.write('@chcp 65001>NUL\n') + + # We pursue activation inline here, which allows us to avoid + # spawning a `conda activate` process at wrapper runtime. + activator_cls = _build_activator_cls("cmd.exe.run") + activator_args = ["activate"] + if dev_mode: + activator_args.append("--dev") + activator_args.append(prefix) + + activator = activator_cls(activator_args) + activator._parse_and_set_args() + activate_script = activator.activate() + + for line in activate_script.splitlines(): + fh.write(f"{silencer}{line}\n") + + fh.write(f"{silencer}IF %ERRORLEVEL% NEQ 0 EXIT /b %ERRORLEVEL%\n") + if debug_wrapper_scripts: + fh.write("echo *** environment after *** 1>&2\n") + fh.write("SET 1>&2\n") + if multiline: + # No point silencing the first line. If that's what's wanted then + # it needs doing for each line and the caller may as well do that. + fh.write(f"{arguments[0]}\n") + else: + if any("\n" in arg for arg in arguments): + raise NotImplementedError( + "Support for scripts where arguments contain newlines not implemented.\n" + ".. requires writing the script to an external file and knowing how to " + "transform the command-line (e.g. `python -c args` => `python file`) " + "in a tool dependent way, or attempting something like:\n" + ".. https://stackoverflow.com/a/15032476 (adds unacceptable escaping" + "requirements)" + ) + fh.write(f"{silencer}{quote_for_shell(*arguments)}\n") + # Capture the user's command exit code before deactivation, and + # run the deactivate.d hooks for the active environment, if any, + # sorted in reverse alphabetical order. + fh.write(f'{silencer}SET "_CONDA_EXE_RC=%ERRORLEVEL%"\n') + deactivate_d = Path(prefix) / "etc" / "conda" / "deactivate.d" + if deactivate_d.is_dir(): + deactivate_scripts = sorted( + deactivate_d.glob("*.bat"), + key=lambda p: p.name, + reverse=True, + ) + for script in deactivate_scripts: + if script.is_file(): + fh.write(f'{silencer}CALL "{script}"\n') + + fh.write(f"{silencer}chcp %_CONDA_OLD_CHCP%>NUL\n") + # Always exit with the user's original exit code, not + # whatever the last deactivate script or chcp returned. + fh.write(f"{silencer}EXIT /B %_CONDA_EXE_RC%\n") + script_caller = fh.name + command_args = [comspec, "/d", "/c", script_caller] + else: + shell_path = which("bash") or which("sh") + if shell_path is None: + raise Exception("No compatible shell found!") + + # During tests, we sometimes like to have a temp env with e.g. an old python in it + # and have it run tests against the very latest development sources. For that to + # work we need extra smarts here, we want it to be instead: + if dev_mode: + conda_exe = [abspath(join(root_prefix, "bin", "python")), "-m", "conda"] + dev_arg = "--dev" + dev_args = [dev_arg] + else: + conda_exe = [ + environ.get("CONDA_EXE", abspath(join(root_prefix, "bin", "conda"))) + ] + dev_arg = "" + dev_args = [] + with Utf8NamedTemporaryFile(mode="w", delete=False) as fh: + # If any of these calls to the activation hook scripts fail, we want + # to exit the wrapper immediately and abort `conda run` right away. + fh.write("set -e\n") + if dev_mode: + from . import CONDA_SOURCE_ROOT + + fh.write(">&2 export PYTHONPATH=" + CONDA_SOURCE_ROOT + "\n") + hook_quoted = quote_for_shell(*conda_exe, "shell.posix", "hook", *dev_args) + if debug_wrapper_scripts: + fh.write(">&2 echo '*** environment before ***'\n>&2 env\n") + fh.write(f'>&2 echo "$({hook_quoted})"\n') + fh.write(f'eval "$({hook_quoted})"\n') + + # We pursue activation inline here, which allows us to avoid + # spawning a `conda activate` process at wrapper runtime. + activator_cls = _build_activator_cls("posix") + activator_args = ["activate"] + if dev_mode: + activator_args.append("--dev") + activator_args.append(prefix) + + activator = activator_cls(activator_args) + activator._parse_and_set_args() + activate_code = activator.activate() + + fh.write(activate_code) + + if debug_wrapper_scripts: + fh.write(">&2 echo '*** environment after ***'\n>&2 env\n") + # Disable exit-on-error for the user's command so we can capture its exit code. + fh.write("set +e\n") + if multiline: + # The ' '.join() is pointless since mutliline is only True when there's 1 arg + # still, if that were to change this would prevent breakage. + fh.write("{}\n".format(" ".join(arguments))) + else: + fh.write(f"{quote_for_shell(*arguments)}\n") + # Capture the return code of the user's command in a variable + # before deactivating. We don't need to unset this per se, because + # the shell process will terminate and clean it up afterwards. + fh.write("_CONDA_EXE_RC=$?\n") + deactivate_d = Path(prefix) / "etc" / "conda" / "deactivate.d" + if deactivate_d.is_dir(): + deactivate_scripts = sorted( + deactivate_d.glob("*.sh"), + key=lambda p: p.name, + reverse=True, + ) + for script in deactivate_scripts: + if script.is_file(): + fh.write(f'. "{script}"\n') + + # Exit with this captured return code from the user's command. + fh.write("exit $_CONDA_EXE_RC\n") + script_caller = fh.name + if debug_wrapper_scripts: + command_args = [shell_path, "-x", script_caller] + else: + command_args = [shell_path, script_caller] + + return script_caller, command_args + + +def get_comspec(): + """Returns COMSPEC from envvars. + + Ensures COMSPEC envvar is set to cmd.exe, if not attempt to find it. + + :raises KeyError: COMSPEC is undefined and cannot be found. + :returns: COMSPEC value. + :rtype: str + """ + if basename(environ.get("COMSPEC", "")).lower() != "cmd.exe": + for comspec in ( + # %SystemRoot%\System32\cmd.exe + environ.get("SystemRoot") + and join(environ["SystemRoot"], "System32", "cmd.exe"), + # %windir%\System32\cmd.exe + environ.get("windir") and join(environ["windir"], "System32", "cmd.exe"), + ): + if comspec and isfile(comspec): + environ["COMSPEC"] = comspec + break + else: + log.warning( + "cmd.exe could not be found. Looked in SystemRoot and windir env vars.\n" + ) + + # fails with KeyError if still undefined + return environ["COMSPEC"] + + +def ensure_dir_exists(func): + """ + Ensures that the directory exists for functions returning + a Path object containing a directory + """ + + @wraps(func) + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + + if isinstance(result, Path): + try: + result.mkdir(parents=True, exist_ok=True) + except OSError as exc: + raise CondaError( + "Error encountered while attempting to create cache directory." + f"\n Directory: {result}" + f"\n Exception: {exc}" + ) + + return result + + return wrapper diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4a2f5420fb7a76ab9fa63476f56e8f30522433f3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/METADATA @@ -0,0 +1,86 @@ +Metadata-Version: 2.4 +Name: conda-anaconda-telemetry +Version: 0.3.0 +Summary: A conda plugin for Anaconda Telemetry +License: BSD 3-Clause License + + Copyright (c) 2024, Anaconda, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * 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 NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +License-File: LICENSE +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.9 +Requires-Dist: conda>=24.11 +Description-Content-Type: text/markdown + +# Conda Anaconda Telemetry + +Welcome to the Conda Anaconda Telemetry project! This project is a plugin that +submits data about conda's usage to Anaconda. This helps Anaconda learn more about +those using conda. This plugin is also an example of how others can leverage conda's +plugin system to begin collecting more information about their conda users too. + +## Installation + +To begin using this plugin, install it in your base environment with the following command: + +```commandline +conda install --name base conda-anaconda-telemetry +``` + +## Disabling + +To disable this plugin, you can either add the following to your `.condarc` file: + +```yaml +plugins: + anaconda_telemetry: false +``` + +Or remove it from your base environment: + +```commandline +conda remove --name base conda-anaconda-telemetry +``` + +## Contributing to this repository + +Contributions are very welcome 😄 + +Feel free to: +1. File bug reports +2. Create feature requests +3. Open pull requests to resolve issues available in the [Github issues queue](https://github.com/anaconda/conda-anaconda-telemetry/issues). +4. Review open pull requests +5. Report any typos, wrong/outdated information on the [documentation website](https://anaconda.github.io/conda-anaconda-telemetry/). +6. Engage in ongoing discussions in this project and add new ideas. diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9e8b87e9076cda5dc65f3e4729a3c117f349c221 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/RECORD @@ -0,0 +1,15 @@ +conda_anaconda_telemetry-0.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda_anaconda_telemetry-0.3.0.dist-info/METADATA,sha256=DwjJKz-thlchCB8sizOmFKKvnNmgPyqeUfXSvTWxM7w,3787 +conda_anaconda_telemetry-0.3.0.dist-info/RECORD,, +conda_anaconda_telemetry-0.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_anaconda_telemetry-0.3.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +conda_anaconda_telemetry-0.3.0.dist-info/direct_url.json,sha256=nbBIsct66FTzz3diHE-sMBS7RWudRjoa0YxwccLTCVE,84 +conda_anaconda_telemetry-0.3.0.dist-info/entry_points.txt,sha256=MRYujujlYJWCF1DPL88db0Cgd9wLuQATRCnpprGQwfw,66 +conda_anaconda_telemetry-0.3.0.dist-info/licenses/LICENSE,sha256=nlBEMQcN2KTMjAIQQtG-oGWnHK5xunhB4dJs59JZa1o,1544 +conda_anaconda_telemetry/__init__.py,sha256=0JcCy4tIH6mz-RN74KcGL-OnEROc0Q7KzgWrN5g0-yg,983 +conda_anaconda_telemetry/__pycache__/__init__.cpython-39.pyc,, +conda_anaconda_telemetry/__pycache__/_version.cpython-39.pyc,, +conda_anaconda_telemetry/__pycache__/hooks.cpython-39.pyc,, +conda_anaconda_telemetry/_version.py,sha256=AGmG_Lx0-9ztFw_7d9mYbaYuC-2abxE1oXOUNAY29YY,511 +conda_anaconda_telemetry/hooks.py,sha256=RlSnH5JHe5dC-cvO1Mt-ZRo4oScJuC48wHNFcKFuDkQ,9058 +conda_anaconda_telemetry/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..594b28bdbc410976e272632ea21e51ef490bdac0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/conda-anaconda-telemetry_1755883788794/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..c8405e19e9b65266e3f1f0e0f267e5bd5d1e39f2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[conda] +conda-anaconda-telemetry = conda_anaconda_telemetry.hooks diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eeebfbfeda28357c61cc3618c43c334579cba80e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry-0.3.0.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +BSD 3-Clause License + +Copyright (c) 2024, Anaconda, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * 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 NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c97011ee44a7deee086bc1a5e7f243e1c70bf12 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__init__.py @@ -0,0 +1,32 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""A conda plugin for Anaconda Telemetry.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Final + +#: Application name. +APP_NAME: Final = "conda-anaconda-telemetry" + +try: + from ._version import __version__ +except ImportError: + # _version.py is only created after running `pip install` + try: + from setuptools_scm import get_version + + __version__ = get_version(root="..", relative_to=__file__) + except (ImportError, OSError, LookupError): + # ImportError: setuptools_scm isn't installed + # OSError: git isn't installed + # LookupError: setuptools_scm unable to detect version + # conda-anaconda-telemetry follows SemVer, so the dev version is: + # MJ.MN.MICRO.devN+gHASH[.dirty] + __version__ = "0.0.0.dev0+placeholder" + +#: Application version. +APP_VERSION: Final = __version__ diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/_version.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..ac8d8d494d79bd19c708ea69e224679485cf1b37 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/_version.py @@ -0,0 +1,21 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] +else: + VERSION_TUPLE = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE + +__version__ = version = '0.3.0' +__version_tuple__ = version_tuple = (0, 3, 0) diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/hooks.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f44f089e9f17224fee7987f88096fee0ef1aae --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/hooks.py @@ -0,0 +1,289 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda plugin that adds telemetry headers to requests made by conda.""" + +from __future__ import annotations + +import functools +import logging +import re +import time +import typing + +from conda.base.context import context +from conda.cli.main_list import list_packages +from conda.common.configuration import PrimitiveParameter +from conda.common.url import mask_anaconda_token +from conda.models.channel import all_channel_urls +from conda.plugins import CondaRequestHeader, CondaSetting, hookimpl + +try: + from conda_build import __version__ as conda_build_version +except ImportError: + conda_build_version = "n/a" + +if typing.TYPE_CHECKING: + from collections.abc import Iterator, Sequence + from typing import Callable + +logger = logging.getLogger(__name__) + +#: Field separator for request header +FIELD_SEPARATOR = ";" + +#: Size limit in bytes for the payload in the request header +SIZE_LIMIT = 7_000 + +#: Prefix for all custom headers submitted via this plugin +# Note: header names are normalized to lowercase by the HTTP layer, so keep +# the prefix lowercased to match the actual header names emitted at runtime. +HEADER_PREFIX = "anaconda-telemetry" + +#: Name of the virtual package header +HEADER_VIRTUAL_PACKAGES = f"{HEADER_PREFIX}-virtual-packages" + +#: Name of the channels header +HEADER_CHANNELS = f"{HEADER_PREFIX}-channels" + +#: Name of the packages header +HEADER_PACKAGES = f"{HEADER_PREFIX}-packages" + +#: Name of the search header +HEADER_SEARCH = f"{HEADER_PREFIX}-search" + +#: Name of the install header +HEADER_INSTALL = f"{HEADER_PREFIX}-install" + +#: Name of the sys info header +HEADER_SYS_INFO = f"{HEADER_PREFIX}-sys-info" + +#: Regex pattern for hosts and paths we want to submit request headers to +REQUEST_HEADER_PATTERN = re.compile( + r""" + ^ # Start of string + (?: # Non-capturing group for host patterns + repo\.anaconda\. # repo.anaconda. (literal dots) + (?:com|cloud) # Either "com" or "cloud" + (?:/.*)? # Optional path starting with forward slash + | # OR + conda\.anaconda\.org/ # conda.anaconda.org/ (literal dots and slash) + (?: # Non-capturing group for channel paths + anaconda| # anaconda channel + conda-forge| # conda-forge channel + main| # main channel + msys2| # msys2 channel + r # r channel + ) + /.* # Forward slash followed by any characters + ) + $ # End of string + """, + re.VERBOSE, +) + + +def timer(func: Callable) -> Callable: + """Log the duration of a function call.""" + + @functools.wraps(func) + def wrapper_timer(*args: tuple, **kwargs: dict) -> Callable: + """Wrap the given function.""" + if logger.getEffectiveLevel() <= logging.INFO: + tic = time.perf_counter() + value = func(*args, **kwargs) + toc = time.perf_counter() + elapsed_time = toc - tic + logger.info( + "function: %s; duration (seconds): %0.4f", + func.__name__, + elapsed_time, + ) + return value + + return func(*args, **kwargs) + + return wrapper_timer + + +def get_virtual_packages() -> tuple[str, ...]: + """Retrieve the registered virtual packages from conda's context.""" + return tuple( + f"{package.name}={package.version}={package.build}" + for package in context.plugin_manager.get_virtual_package_records() + ) + + +def get_channel_urls() -> tuple[str, ...]: + """Return a list of currently configured channel URLs with tokens masked.""" + channels = list(all_channel_urls(context.channels)) + return tuple(mask_anaconda_token(c) for c in channels) + + +def get_conda_command() -> str: + """Use ``sys.argv`` to determine the conda command that is current being run.""" + return context._argparse_args.cmd + + +def get_package_list() -> tuple[str, ...]: + """Retrieve the list of packages in the current environment.""" + prefix = context.active_prefix or context.root_prefix + _, packages = list_packages(prefix, format="canonical") + + return packages + + +def get_search_term() -> str: + """Retrieve the search term being used when search command is run.""" + return context._argparse_args.match_spec + + +def get_install_arguments() -> tuple[str, ...]: + """Get the parsed position argument.""" + return context._argparse_args.packages + + +@timer +@functools.lru_cache(None) +def get_sys_info_header_value() -> str: + """Return ``;`` delimited string of extra system information.""" + telemetry_data = { + "conda_build_version": conda_build_version, + "conda_command": get_conda_command(), + } + + return FIELD_SEPARATOR.join( + f"{key}:{value}" for key, value in telemetry_data.items() + ) + + +@timer +@functools.lru_cache(None) +def get_channel_urls_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of channel URLs.""" + return FIELD_SEPARATOR.join(get_channel_urls()) + + +@timer +@functools.lru_cache(None) +def get_virtual_packages_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of virtual packages.""" + return FIELD_SEPARATOR.join(get_virtual_packages()) + + +@timer +@functools.lru_cache(None) +def get_install_arguments_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of channel URLs.""" + return FIELD_SEPARATOR.join(get_install_arguments()) + + +@timer +@functools.lru_cache(None) +def get_installed_packages_header_value() -> str: + """Return ``FIELD_SEPARATOR`` delimited string of install arguments.""" + return FIELD_SEPARATOR.join(get_package_list()) + + +class HeaderWrapper(typing.NamedTuple): + """Object that wraps ``CondaRequestHeader`` and adds a ``size_limit`` field.""" + + header: CondaRequestHeader + size_limit: int + + +def validate_headers( + header_wrappers: Sequence[HeaderWrapper], +) -> Iterator[CondaRequestHeader]: + """Make sure that all headers combined are not larger than ``SIZE_LIMIT``. + + Any headers over their individual limits will be truncated. + """ + for wrapper in header_wrappers: + wrapper.header.value = wrapper.header.value[: wrapper.size_limit] + yield wrapper.header + + +def _conda_request_headers() -> Sequence[HeaderWrapper]: + custom_headers = [ + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_SYS_INFO, + value=get_sys_info_header_value(), + ), + size_limit=500, + ), + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_CHANNELS, + value=get_channel_urls_header_value(), + ), + size_limit=500, + ), + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_VIRTUAL_PACKAGES, + value=get_virtual_packages_header_value(), + ), + size_limit=500, + ), + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_PACKAGES, + value=get_installed_packages_header_value(), + ), + size_limit=5_000, + ), + ] + + command = get_conda_command() + + if command == "search": + custom_headers.append( + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_SEARCH, + value=get_search_term(), + ), + size_limit=500, + ) + ) + + elif command in {"install", "create"}: + custom_headers.append( + HeaderWrapper( + header=CondaRequestHeader( + name=HEADER_INSTALL, + value=get_install_arguments_header_value(), + ), + size_limit=500, + ) + ) + + return custom_headers + + +def should_submit_request_headers(host: str, path: str) -> bool: + """Return whether we should submit request headers to the given host and path.""" + return REQUEST_HEADER_PATTERN.match(f"{host}{path}") is not None + + +@hookimpl +def conda_request_headers(host: str, path: str) -> Iterator[CondaRequestHeader]: + """Return a list of custom headers to be included in the request.""" + try: + if context.plugins.anaconda_telemetry and should_submit_request_headers( + host, path + ): + yield from validate_headers(_conda_request_headers()) + except Exception as exc: + logger.debug("Failed to collect telemetry data", exc_info=exc) + + +@hookimpl +def conda_settings() -> Iterator[CondaSetting]: + """Return a list of settings that can be configured by the user.""" + yield CondaSetting( + name="anaconda_telemetry", + description="Whether Anaconda Telemetry is enabled", + parameter=PrimitiveParameter(True, element_type=bool), + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/py.typed b/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9a4ae15b12d5f32354f767a7f06914a52e2d8337 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/METADATA @@ -0,0 +1,45 @@ +Metadata-Version: 2.4 +Name: conda-anaconda-tos +Version: 0.2.2 +Summary: Conda subcommand to view, accept, and interact with a channel's Terms of Service (ToS). +License: BSD 3-Clause License + + Copyright (c) 2024, Anaconda, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * 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 NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +License-File: LICENSE +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.9 +Requires-Dist: conda>=24.11 +Requires-Dist: pydantic +Requires-Dist: rich diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..23c068b2aa4b74ceff5a431e62d4635737bfbcd9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/RECORD @@ -0,0 +1,35 @@ +conda_anaconda_tos-0.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda_anaconda_tos-0.2.2.dist-info/METADATA,sha256=ax5bvnq2HzEE-KLnbw9-5oPDiiSn2_1yvX12WBbQM3Y,2532 +conda_anaconda_tos-0.2.2.dist-info/RECORD,, +conda_anaconda_tos-0.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_anaconda_tos-0.2.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +conda_anaconda_tos-0.2.2.dist-info/direct_url.json,sha256=C5BqwOgXZ6TZiARfn3eTFVydq0p9b6r76ixWIRqPTjg,78 +conda_anaconda_tos-0.2.2.dist-info/entry_points.txt,sha256=0cUjXUStHHPx7CSiIc7aOCpn5xRREIKjTGfjPfA5Udw,55 +conda_anaconda_tos-0.2.2.dist-info/licenses/LICENSE,sha256=nlBEMQcN2KTMjAIQQtG-oGWnHK5xunhB4dJs59JZa1o,1544 +conda_anaconda_tos/__init__.py,sha256=3o1gxQhqx-5uOP0gvcl8SAszHeKeUW8ODYA3p_qvvCA,984 +conda_anaconda_tos/__pycache__/__init__.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/_version.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/api.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/exceptions.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/local.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/models.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/path.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/plugin.cpython-313.pyc,, +conda_anaconda_tos/__pycache__/remote.cpython-313.pyc,, +conda_anaconda_tos/_version.py,sha256=OjGGK5TcHVG44Y62aAqeJH4CskkZoY9ydbHOtCDew50,511 +conda_anaconda_tos/api.py,sha256=3DHgEFjlEc07-RrfAoi-6vrx_PzvopI3punuQejPq0I,13142 +conda_anaconda_tos/console/__init__.py,sha256=m0_R55EAN8g1IkFPfevtTKLOpXCWT-D_mejX2eg-gsc,306 +conda_anaconda_tos/console/__pycache__/__init__.cpython-313.pyc,, +conda_anaconda_tos/console/__pycache__/mappers.cpython-313.pyc,, +conda_anaconda_tos/console/__pycache__/prompt.cpython-313.pyc,, +conda_anaconda_tos/console/__pycache__/render.cpython-313.pyc,, +conda_anaconda_tos/console/mappers.py,sha256=eVQG_IGf_bl9hEQnV0ohuF30BdcJRPq0agXLXgSAI-Q,1707 +conda_anaconda_tos/console/prompt.py,sha256=9RUAyARbIM6Q4Wt12r60Oy8KRVXQukzJQatkwdEyHn8,1473 +conda_anaconda_tos/console/render.py,sha256=ZPWZBGlE1Wi_GT-G7sQzurvwzNVduBRKo6GFJnv8Ua4,16007 +conda_anaconda_tos/exceptions.py,sha256=VsLbEW-XaTgvfbroirUVxki0dps7IwHKiJVZlEPEWAg,4039 +conda_anaconda_tos/local.py,sha256=mvUtasTmh584LZ8mJmg5dOBTSVEuAs9wg7lsDuRyMzg,4366 +conda_anaconda_tos/models.py,sha256=IslelwXsuA3fB_OqXaNsPsoEv6zEONwphLRPlJ6oCXo,2186 +conda_anaconda_tos/path.py,sha256=-VZ_cfOX6gFwTwylEhTrc2wS9w8DfrZRf11AQVrIWqU,4446 +conda_anaconda_tos/plugin.py,sha256=SuVVed5CDFY1G3dErKKHdO51nA4ViGmZ2ToKcnbTSXQ,12532 +conda_anaconda_tos/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_anaconda_tos/remote.py,sha256=0BXiZimYyCHe3YAjkFgRxkxKR1-JNel2x4QA08OhNVk,5942 diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..7208d8842084af793587e3b5518c202975c17eff --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///croot/conda-anaconda-tos_1755123313635/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..800cc8ca4badc8fe75d5b6dec393d3936c90734c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[conda] +conda-anaconda-tos = conda_anaconda_tos.plugin diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eeebfbfeda28357c61cc3618c43c334579cba80e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos-0.2.2.dist-info/licenses/LICENSE @@ -0,0 +1,27 @@ +BSD 3-Clause License + +Copyright (c) 2024, Anaconda, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * 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 NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d86b0941639c68a9d4b027d92f667cc598433585 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/__init__.py @@ -0,0 +1,32 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Conda channel's Terms of Service management plugin.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Final + +#: Application name. +APP_NAME: Final = "conda-anaconda-tos" + +try: + from ._version import __version__ +except ImportError: + # _version.py is only created after running `pip install` + try: + from setuptools_scm import get_version + + __version__ = get_version(root="..", relative_to=__file__) + except (ImportError, OSError, LookupError): + # ImportError: setuptools_scm isn't installed + # OSError: git isn't installed + # LookupError: setuptools_scm unable to detect version + # conda-anaconda-tos follows SemVer, so the dev version is: + # MJ.MN.MICRO.devN+gHASH[.dirty] + __version__ = "0.0.0.dev0+placeholder" + +#: Application version. +APP_VERSION: Final = __version__ diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/_version.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..e38f676dc504b9efb2253f6b65ae06b9ef3e6ec6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/_version.py @@ -0,0 +1,21 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = ["__version__", "__version_tuple__", "version", "version_tuple"] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] +else: + VERSION_TUPLE = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE + +__version__ = version = '0.2.2' +__version_tuple__ = version_tuple = (0, 2, 2) diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/api.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/api.py new file mode 100644 index 0000000000000000000000000000000000000000..6033f471e0082f75c1ff42e2ed9fd33946f5e8ff --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/api.py @@ -0,0 +1,327 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""High-level API functions for interacting with a channel's Terms of Service.""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import TYPE_CHECKING + +from conda.auxlib.type_coercion import boolify +from conda.models.channel import Channel + +from .exceptions import CondaToSMissingError +from .local import get_local_metadata, get_local_metadatas, write_metadata +from .models import LocalPair, RemotePair +from .path import get_all_channel_paths, get_cache_paths +from .remote import get_remote_metadata + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from typing import Final + + +#: Boolean CI environment variables (checked with boolify) +#: Sources: Official CI platform documentation and community knowledge base +CI_BOOLEAN_VARS: Final = ( + "APPVEYOR", # AppVeyor CI (https://www.appveyor.com/docs/environment-variables/) + "BITRISE_IO", # Bitrise (https://devcenter.bitrise.io/en/references/available-environment-variables.html) + "BUDDY", # Buddy CI/CD (https://buddy.works/docs/pipelines/environment-variables) + "BUILDKITE", # Buildkite (https://buildkite.com/docs/pipelines/environment-variables) + "CI", # Generic CI indicator (many platforms) + "CIRCLECI", # CircleCI (https://circleci.com/docs/variables/#built-in-environment-variables) + "CIRRUS_CI", # Cirrus CI (https://cirrus-ci.org/guide/environment-variables/) + "CONCOURSE_CI", # Concourse CI (https://concourse-ci.org/implementing-resource-types.html#environment) + "DRONE", # Drone CI (https://docs.drone.io/pipeline/environment/reference/) + "GITHUB_ACTIONS", # GitHub Actions (https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables) + "GITLAB_CI", # GitLab CI/CD (https://docs.gitlab.com/ee/ci/variables/predefined_variables.html) + "SAIL_CI", # Sail CI + "SEMAPHORE", # Semaphore CI (https://docs.semaphoreci.com/ci-cd-environment/environment-variables/) + "TF_BUILD", # Azure DevOps (Team Foundation) (https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables) + "TRAVIS", # Travis CI (https://docs.travis-ci.com/user/environment-variables/#default-environment-variables) + "WERCKER", # Wercker (deprecated) + "WOODPECKER_CI", # Woodpecker CI (https://woodpecker-ci.org/docs/usage/environment) +) + +#: Presence-based CI environment variables (checked for existence) +#: Sources: Official CI platform documentation +CI_PRESENCE_VARS: Final = ( + "BAMBOO_BUILDKEY", # Atlassian Bamboo (https://confluence.atlassian.com/bamboo/bamboo-variables-289277087.html) + "CODEBUILD_BUILD_ID", # AWS CodeBuild (https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html) + "HEROKU_TEST_RUN_ID", # Heroku CI (https://devcenter.heroku.com/articles/heroku-ci#environment-variables) + "JENKINS_URL", # Jenkins (https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables) + "TEAMCITY_VERSION", # JetBrains TeamCity (https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html) +) + + +#: Container indicators for cgroup detection +#: Reference: https://github.com/containers/podman/issues/3586, +#: Docker/containerd documentation +CONTAINER_INDICATORS: Final = ( + "containerd", # containerd runtime + "docker", # Docker containers + "kubepods", # Kubernetes pods (https://kubernetes.io/docs/tasks/administer-cluster/migrating-from-dockershim/find-out-runtime-you-use/) + "lxc", # Linux Containers + "podman", # Podman containers +) + +#: Partial CI environment variables (used with container detection) +#: These variables may be present in containerized CI environments that don't +#: set full CI variables +PARTIAL_CI_VARS: Final = ( + "AZURE_HTTP_USER_AGENT", # Azure DevOps user agent + "BUILD_ID", # Generic build identifier (Jenkins, etc.) + "BUILD_NUMBER", # Generic build number (Jenkins, etc.) + "BUILD_URL", # Generic build URL (Jenkins, etc.) + "BUILDKITE_BUILD_ID", # Buildkite build identifier + "CIRCLE_BUILD_NUM", # CircleCI build number + "CIRCLE_PROJECT_REPONAME", # CircleCI repository name + "GITHUB_JOB", # GitHub Actions job name + "GITHUB_REPOSITORY", # GitHub repository name + "GITHUB_WORKFLOW", # GitHub Actions workflow name + "GITLAB_PROJECT_ID", # GitLab project identifier + "GITLAB_USER_ID", # GitLab user identifier + "JOB_NAME", # Generic job name (Jenkins, etc.) + "RUNNER_ARCH", # GitHub Actions runner architecture + "RUNNER_OS", # GitHub Actions runner OS + "WORKSPACE", # Generic workspace path (Jenkins, etc.) +) + + +def _in_ci_container() -> bool: + """Detect if running in a containerized CI environment. + + This function combines container detection with partial CI environment variables + to address cases where CI systems run jobs in containers but don't set complete + CI environment variables (see GitHub issue #232). This is a workaround for + https://github.com/anaconda/conda-anaconda-tos/issues/232. + + Returns: + bool: True if both container indicators and partial CI variables are present + + """ + # Check documented container indicators + container_checks = [ + os.getpid() == 1, # Process ID 1 (init process in containers) + bool(os.environ.get("CONTAINER")), # Generic container environment variable + ] + + # Check cgroup for container runtime identifiers (Docker official method) + # Reference: https://docs.docker.com/engine/containers/runmetrics/#find-the-cgroup-for-a-given-container + try: + with Path("/proc/self/cgroup").open() as f: + cgroup_content = f.read() + # Container runtime signatures in cgroups (documented by Docker): + # - "docker": Docker containers + # - "containerd": containerd runtime + # - "kubepods": Kubernetes pods + # - "lxc": Linux Containers + # - "podman": Podman containers + if any(indicator in cgroup_content for indicator in CONTAINER_INDICATORS): + container_checks.append(True) + except OSError: + # Ignore errors (e.g., on non-Linux systems or restricted access) + pass + + # Return True only if we detect container AND partial CI indicators + # This prevents false positives from containers without CI context + return any(container_checks) and any(os.getenv(var) for var in PARTIAL_CI_VARS) + + +def _is_ci() -> bool: + """Determine if running in a CI environment. + + This function uses a multi-layered approach to detect CI environments: + 1. First checks if any CI variables are explicitly set to false + (respects user override) + 2. Then checks boolean CI variables for true values + 3. Finally checks presence-based variables and container environments + + Returns: + bool: True if running in a detected CI environment + + """ + # Check all boolean CI variables for explicit false values first + # If any CI variable is explicitly set to false, respect that + for var_value in map(os.getenv, CI_BOOLEAN_VARS): + if var_value and not boolify(var_value): + return False + + # Check boolean CI environment variables for true values + for var_value in map(os.getenv, CI_BOOLEAN_VARS): + if boolify(var_value): + return True + + # Check presence-based CI environment variables + return any(os.getenv(var) for var in CI_PRESENCE_VARS) or _in_ci_container() + + +#: Whether the current environment is a CI environment +CI: Final = _is_ci() + +#: Whether the current environment is a Jupyter environment +JUPYTER: Final = os.getenv("JPY_SESSION_NAME") and os.getenv("JPY_PARENT_PID") + + +def get_channels(*channels: str | Channel) -> Iterable[Channel]: + """Yield all unique channels from the given channels.""" + # expand every multichannel into its individual channels + # and remove any duplicates + seen: set[Channel] = set() + for multichannel in map(Channel, channels): + for channel in map(Channel, multichannel.urls()): + channel = Channel(channel.base_url) + if channel not in seen: + yield channel + seen.add(channel) + + +def get_one_tos( + channel: str | Channel, + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> LocalPair | RemotePair: + """Get the Terms of Service metadata for the given channel.""" + # fetch remote metadata + remote_metadata = remote_exc = None + try: + remote_metadata = get_remote_metadata(channel, cache_timeout=cache_timeout) + except CondaToSMissingError as exc: + # CondaToSMissingError: no remote metadata + remote_exc = exc + + # fetch local metadata + try: + local_pair = get_local_metadata(channel, extend_search_path=[tos_root]) + except CondaToSMissingError as exc: + # CondaToSMissingError: no local metadata + if remote_exc: + raise remote_exc from exc + # no local ToS metadata + return RemotePair(metadata=remote_metadata) + else: + # return local metadata, include remote metadata if newer + if not remote_metadata or local_pair.metadata >= remote_metadata: + return local_pair + return LocalPair( + metadata=local_pair.metadata, + path=local_pair.path, + remote=remote_metadata, + ) + + +def get_stored_tos( + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> Iterator[tuple[Channel, LocalPair]]: + """Yield metadata of all stored Terms of Service.""" + for channel, local_pair in get_local_metadatas(extend_search_path=[tos_root]): + try: + remote_metadata = get_remote_metadata(channel, cache_timeout=cache_timeout) + except CondaToSMissingError: + # CondaToSMissingError: no remote metadata + continue + + # yield local metadata, include remote metadata if newer + if local_pair.metadata >= remote_metadata: + yield channel, local_pair + else: + yield ( + channel, + LocalPair( + metadata=local_pair.metadata, + path=local_pair.path, + remote=remote_metadata, + ), + ) + + +def accept_tos( + channel: str | Channel, + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> LocalPair: + """Accept the Terms of Service for the given channel.""" + pair = get_one_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ) + metadata = pair.remote or pair.metadata + return write_metadata(tos_root, channel, metadata, tos_accepted=True) + + +def reject_tos( + channel: str | Channel, + *, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> LocalPair: + """Reject the Terms of Service for the given channel.""" + pair = get_one_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ) + metadata = pair.remote or pair.metadata + return write_metadata(tos_root, channel, metadata, tos_accepted=False) + + +def get_all_tos( + *channels: str | Channel, + tos_root: str | os.PathLike | Path, + cache_timeout: int | float | None, +) -> Iterator[tuple[Channel, LocalPair | RemotePair | None]]: + """List all channels and whether their Terms of Service have been accepted.""" + # list all active channels + seen: set[Channel] = set() + for channel in get_channels(*channels): + try: + yield ( + channel, + get_one_tos(channel, tos_root=tos_root, cache_timeout=cache_timeout), + ) + except CondaToSMissingError: + yield channel, None + seen.add(channel) + + # list all other channels whose Terms of Service have been accepted/rejected + for channel, metadata_pair in get_stored_tos( + tos_root=tos_root, + cache_timeout=cache_timeout, + ): + if channel not in seen: + yield channel, metadata_pair + seen.add(channel) + + +def clean_cache() -> Iterator[Path]: + """Clean all metadata cache files.""" + for path in get_cache_paths(): + try: + path.unlink() + except (PermissionError, FileNotFoundError, IsADirectoryError): + # PermissionError: no permission to delete the file + # FileNotFoundError: the file doesn't exist + # IsADirectoryError: the path is a directory + pass + else: + yield path + + +def clean_tos(tos_root: str | os.PathLike[str] | Path) -> Iterator[Path]: + """Clean all metadata directories.""" + for path in get_all_channel_paths(extend_search_path=[tos_root]): + try: + path.unlink() + except (PermissionError, FileNotFoundError, IsADirectoryError): + # PermissionError: no permission to delete the file + # FileNotFoundError: the file doesn't exist + # IsADirectoryError: the path is a directory + pass + else: + yield path diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6de20c79d10e7f6c03959ea19d51783fa1dda67 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/__init__.py @@ -0,0 +1,14 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Render functions for console output.""" + +from .render import ( # noqa: F401 + noop_printer, + render_accept, + render_clean, + render_info, + render_interactive, + render_list, + render_reject, + render_view, +) diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/mappers.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/mappers.py new file mode 100644 index 0000000000000000000000000000000000000000..879044a938042d0233d3b1716112b243f212dc75 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/mappers.py @@ -0,0 +1,55 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Mappers to aid in rendering of console output.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..models import RemoteToSMetadata + +if TYPE_CHECKING: + from datetime import datetime + from pathlib import Path + from typing import Final + + from ..models import LocalToSMetadata + + +NULL_CHAR: Final = "[dim]-" + + +def timestamp_mapping(timestamp: datetime) -> str: + """Map the UTC metadata timestamp to a localized human-readable string.""" + return timestamp.astimezone().strftime("%Y-%m-%d %H:%M:%S %Z") + + +def accepted_mapping(metadata: RemoteToSMetadata | LocalToSMetadata) -> str: + """Map the metadata acceptance status to a human-readable string.""" + if isinstance(metadata, RemoteToSMetadata): + return NULL_CHAR + + tos_accepted = metadata.tos_accepted + acceptance_timestamp = metadata.acceptance_timestamp + if tos_accepted: + if acceptance_timestamp: + # convert timestamp to localized time + return f"[bold green]{timestamp_mapping(acceptance_timestamp)}" + else: + # accepted but no timestamp + return "[dim]unknown" + else: + return "[bold red]rejected" + + +def location_mapping(path: Path | None) -> str: + """Map the metadata path to a human-readable string.""" + if not path: + return NULL_CHAR + return str(path.parent.parent) + + +def version_mapping(version: datetime, remote: RemoteToSMetadata | None) -> str: + """Map the metadata version to a human-readable string.""" + version_str = timestamp_mapping(version) + return f"[bold yellow]{version_str} *" if remote else version_str diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/prompt.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a96ce60eec41f0969d3a5412b2db8ee355b0f4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/prompt.py @@ -0,0 +1,47 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Custom rich.prompt.Prompt implementations for console prompting.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from rich.prompt import InvalidResponse, Prompt + +if TYPE_CHECKING: + from typing import Self + + +class FuzzyPrompt(Prompt): + """A prompt that fuzzy matches the choices.""" + + @staticmethod + def strip_braces(value: str) -> str: + """Strip braces from value.""" + return value.replace("(", "").replace(")", "").strip() + + def check_choice(self: Self, value: str) -> str | None: + """Check value is in the list of valid choices.""" + if not self.choices: + return value + value = self.strip_braces(value) + value = value.lower() + return next( + ( + choice + for choice in map(self.strip_braces, self.choices) + if choice.lower().startswith(value) + ), + None, + ) + + def process_response(self: Self, value: str) -> str: + """Process response from user, convert to prompt type.""" + try: + return_value = self.response_type(value) + except ValueError as exc: + raise InvalidResponse(self.validate_error_message) from exc + + if not (return_value := self.check_choice(return_value)): + raise InvalidResponse(self.illegal_choice_message) + return return_value diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/render.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/render.py new file mode 100644 index 0000000000000000000000000000000000000000..56511b34fd5e6766a00391f64c2b5bc731aca2ff --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/console/render.py @@ -0,0 +1,516 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Render functions for console output.""" + +from __future__ import annotations + +import functools +from pathlib import Path +from typing import TYPE_CHECKING + +from conda.common.io import IS_INTERACTIVE +from conda.exceptions import ArgumentError +from rich.console import Console +from rich.table import Table + +from ..api import ( + CI, + JUPYTER, + accept_tos, + clean_cache, + clean_tos, + get_all_tos, + get_channels, + get_one_tos, + reject_tos, +) +from ..exceptions import ( + CondaToSMissingError, + CondaToSNonInteractiveError, + CondaToSRejectedError, +) +from ..path import CACHE_DIR, SEARCH_PATH +from .mappers import NULL_CHAR, accepted_mapping, location_mapping, version_mapping +from .prompt import FuzzyPrompt + +if TYPE_CHECKING: + import os + from collections.abc import Iterable + from typing import Any, Callable, Final + + from conda.models.channel import Channel + + from ..models import LocalPair, RemotePair + + AcceptedType = dict[str, dict] + RejectedType = list[Channel] + NonInteractiveType = list[Channel] + ChannelPairsType = list[tuple[Channel, RemotePair | LocalPair]] + + +TOS_OUTDATED: Final = "* Terms of Service version(s) are outdated." + +TOS_AUTO_ACCEPTED_TEMPLATE: Final = ( + "By accessing {channel} with auto acceptance enabled (auto_accept_tos=True) " + "for this repository you acknowledge and agree to the Terms of Service:\n" + "{tos_text}" +) +TOS_CI_ACCEPTED_TEMPLATE: Final = ( + "By accessing {channel} via CI " + "for this repository you acknowledge and agree to the Terms of Service:\n" + "{tos_text}" +) + + +def noop_printer(*args: Any, **kwargs: Any) -> None: # noqa: ANN401 + """Use this no-op printer when nothing should be printed to the screen.""" + + +def printable(func: Callable[..., int]) -> Callable[..., int]: + """Pass console and printer functions to the decorated function. + + This instantiates a console for the render functions if not provided and + the console and json printers to pass them to the decorated function. + """ + + @functools.wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> int: # noqa: ANN401 + console = kwargs.pop("console", Console()) + json = kwargs.pop("json", False) + printer = kwargs.pop("printer", noop_printer if json else console.print) + json_printer = kwargs.pop("json_printer", console.print_json) + return func( + *args, + **kwargs, + json=json, + console=console, + printer=printer, + json_printer=json_printer, + ) + + return wrapper + + +@printable +def render_list( + *channels: str | Channel, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, + json: bool = False, + verbose: bool = False, + console: Console | None = None, # noqa: ARG001 + printer: Callable[..., None], + json_printer: Callable[..., None], +) -> int: + """Display listing of unaccepted, accepted, and rejected Terms of Service.""" + table = Table() + table.add_column("Channel") + table.add_column("Version") + table.add_column("Accepted") + table.add_column("Support") + if verbose: + table.add_column("Location") + add_row = table.add_row + else: + add_row = lambda *args: table.add_row(*args[:-1]) # noqa: E731 + + json_output: dict[str, Any] = {} + outdated = False + for channel, metadata_pair in get_all_tos( + *channels, + tos_root=tos_root, + cache_timeout=cache_timeout, + ): + if not metadata_pair: + json_output[channel.base_url] = None + add_row(channel.base_url, NULL_CHAR, NULL_CHAR, NULL_CHAR, NULL_CHAR) + else: + json_output[channel.base_url] = { + **metadata_pair.metadata.model_dump(mode="json"), + "outdated": bool(metadata_pair.remote), + "path": str(metadata_pair.path), + } + outdated = outdated or bool(metadata_pair.remote) + add_row( + channel.base_url, + version_mapping(metadata_pair.metadata.version, metadata_pair.remote), + accepted_mapping(metadata_pair.metadata), + metadata_pair.metadata.support, + location_mapping(metadata_pair.path), + ) + + if json: + json_printer(data=json_output) + else: + printer(table) + if outdated: + printer(f"[bold yellow]{TOS_OUTDATED}") + return 0 + + +@printable +def render_view( + *channels: str | Channel, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, + json: bool = False, + console: Console | None = None, # noqa: ARG001 + printer: Callable[..., None], + json_printer: Callable[..., None], +) -> int: + """Display the Terms of Service text for the given channels.""" + json_output: dict[str, Any] = {} + for channel in get_channels(*channels): + try: + metadata = get_one_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ).metadata + except CondaToSMissingError: + json_output[channel.base_url] = None + printer(f"no Terms of Service for {channel}") + else: + json_output[channel.base_url] = metadata.model_dump(mode="json") + printer(f"viewing Terms of Service for {channel}:") + printer(metadata.text) + + if json: + json_printer(data=json_output) + return 0 + + +@printable +def render_accept( + *channels: str | Channel, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, + json: bool = False, + console: Console | None = None, # noqa: ARG001 + printer: Callable[..., None], + json_printer: Callable[..., None], +) -> int: + """Display acceptance of the Terms of Service for the given channels.""" + json_output: dict[str, Any] = {} + for channel in get_channels(*channels): + try: + metadata = accept_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ).metadata + except CondaToSMissingError: + json_output[channel.base_url] = None + printer(f"Terms of Service not found for {channel}") + else: + json_output[channel.base_url] = metadata.model_dump(mode="json") + printer(f"accepted Terms of Service for {channel}") + + if json: + json_printer(data=json_output) + return 0 + + +@printable +def render_reject( + *channels: str | Channel, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, + json: bool = False, + console: Console | None = None, # noqa: ARG001 + printer: Callable[..., None], + json_printer: Callable[..., None], +) -> int: + """Display rejection of the Terms of Service for the given channels.""" + json_output: dict[str, Any] = {} + for channel in get_channels(*channels): + try: + metadata = reject_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ).metadata + except CondaToSMissingError: + json_output[channel.base_url] = None + printer(f"Terms of Service not found for {channel}") + else: + json_output[channel.base_url] = metadata.model_dump(mode="json") + printer(f"rejected Terms of Service for {channel}") + + if json: + json_printer(data=json_output) + return 0 + + +def _prompt_acceptance( + channel: Channel, + pair: RemotePair | LocalPair, + console: Console, + choices: Iterable[str] = ("(a)ccept", "(r)eject", "(v)iew"), +) -> bool: + prologue = "" + if pair.remote: + state = "[bold red]rejected[/]" + if pair.metadata.tos_accepted: + state = "[bold green]accepted[/]" + prologue = ( + f"The Terms of Service for {channel} was previously {state}. " + f"An updated Terms of Service is now available.\n" + ) + + response = FuzzyPrompt.ask( + f"{prologue}Do you accept the Terms of Service (ToS) for {channel}?", + choices=choices, + console=console, + ) + if response == "accept": + return True + elif response == "reject": + return False + else: + console.print(pair.latest_text) + return _prompt_acceptance(channel, pair, console, ("(a)ccept", "(r)eject")) + + +def _gather_tos( + *channels: str | Channel, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, +) -> tuple[ + AcceptedType, + RejectedType, + ChannelPairsType, +]: + accepted = {} + rejected = [] + channel_pairs = [] + for channel in get_channels(*channels): + try: + pair = get_one_tos(channel, tos_root=tos_root, cache_timeout=cache_timeout) + except CondaToSMissingError: + # CondaToSMissingError: no metadata found + continue + + if pair.remote or getattr(pair.metadata, "tos_accepted", None) is None: + # Terms of Service has been updated or + # Terms of Service haven't been accepted or rejected yet + channel_pairs.append((channel, pair)) + elif pair.metadata.tos_accepted: + accepted[channel.base_url] = pair.metadata.model_dump(mode="json") + else: + rejected.append(channel) + return accepted, rejected, channel_pairs + + +def _is_tos_accepted( + *, + channel: Channel, + pair: RemotePair | LocalPair, + auto_accept_tos: bool, + always_yes: bool, + json_mode: bool, + console: Console, + printer: Callable[..., None], +) -> bool: + """Determine if the Terms of Service is accepted for a channel.""" + # Auto-accept has highest priority + if auto_accept_tos: + printer( + TOS_AUTO_ACCEPTED_TEMPLATE.format( + channel=channel, + tos_text=pair.latest_text, + ), + style="bold yellow", + ) + return True + + # CI environment auto-accepts with warning + if CI: + printer( + TOS_CI_ACCEPTED_TEMPLATE.format( + channel=channel, + tos_text=pair.latest_text, + ), + style="bold yellow", + ) + return True + + # Non-interactive environments exits before prompt + if json_mode or always_yes or JUPYTER or not IS_INTERACTIVE: + raise CondaToSNonInteractiveError + + # Interactive prompt + return _prompt_acceptance(channel, pair, console) + + +def _process_channel_pairs( + *, + channel_pairs: ChannelPairsType, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, + auto_accept_tos: bool, + always_yes: bool, + json_mode: bool, + console: Console, + printer: Callable[..., None], + # optional arguments, if provided they are updated in place + accepted: AcceptedType | None = None, + rejected: RejectedType | None = None, + non_interactive: NonInteractiveType | None = None, +) -> tuple[AcceptedType, RejectedType, NonInteractiveType]: + """Iterate over channel pairs and process the Terms of Service.""" + accepted = {} if accepted is None else accepted + rejected = [] if rejected is None else rejected + non_interactive = [] if non_interactive is None else non_interactive + + for channel, pair in channel_pairs: + try: + if _is_tos_accepted( + channel=channel, + pair=pair, + auto_accept_tos=auto_accept_tos, + always_yes=always_yes, + json_mode=json_mode, + console=console, + printer=printer, + ): + accepted[channel.base_url] = accept_tos( + channel, + tos_root=tos_root, + cache_timeout=cache_timeout, + ).metadata + else: + reject_tos(channel, tos_root=tos_root, cache_timeout=cache_timeout) + rejected.append(channel) + except CondaToSNonInteractiveError: + non_interactive.append(channel) + + return accepted, rejected, non_interactive + + +@printable +def render_interactive( + *channels: str | Channel, + tos_root: str | os.PathLike[str] | Path, + cache_timeout: int | float | None, + json: bool = False, + verbose: bool = False, + auto_accept_tos: bool, + always_yes: bool, + console: Console | None = None, + printer: Callable[..., None], + json_printer: Callable[..., None], +) -> int: + """Prompt user to accept or reject Terms of Service for channels.""" + if verbose: + printer("[bold blue]Gathering channels...") + + accepted, rejected, channel_pairs = _gather_tos( + *channels, + tos_root=tos_root, + cache_timeout=cache_timeout, + ) + + if verbose: + printer("[bold yellow]Reviewing channels...") + + # exit early if some channels are already rejected + if rejected: + printer(f"[bold red]{len(rejected)} channel Terms of Service rejected") + raise CondaToSRejectedError(*rejected) + + if CI: + printer("[bold yellow]CI detected...") + elif JUPYTER: + printer("[bold yellow]Jupyter detected...") + + accepted, rejected, non_interactive = _process_channel_pairs( + accepted=accepted, + rejected=rejected, + channel_pairs=channel_pairs, + tos_root=tos_root, + cache_timeout=cache_timeout, + auto_accept_tos=auto_accept_tos, + always_yes=always_yes, + json_mode=json, + console=console, + printer=printer, + ) + + if non_interactive: + raise CondaToSNonInteractiveError(*non_interactive) + elif rejected: + printer(f"[bold red]{len(rejected)} channel Terms of Service rejected") + raise CondaToSRejectedError(*rejected) + + if verbose or accepted: + printer(f"[bold green]{len(accepted)} channel Terms of Service accepted") + + if json: + json_printer(data=accepted) + return 0 + + +@printable +def render_info( + *, + json: bool = False, + console: Console | None = None, # noqa: ARG001 + printer: Callable[..., None], + json_printer: Callable[..., None], +) -> int: + """Display information about the Terms of Service cache.""" + data: dict[str, str | tuple[str, ...]] = {} + data["SEARCH_PATH"] = SEARCH_PATH + try: + relative_dir = Path("~", CACHE_DIR.relative_to(Path.home())) + except ValueError: + # ValueError: CACHE_DIR is not relative to the user's home directory + relative_dir = CACHE_DIR + data["CACHE_DIR"] = str(relative_dir) + + if json: + json_printer(data=data) + else: + table = Table(show_header=False) + table.add_column("Key") + table.add_column("Value") + for key, value in data.items(): + if isinstance(value, (tuple, list)): + value = "\n".join(map(str, value)) + else: + value = str(value) + table.add_row(key, value) + printer(table) + return 0 + + +@printable +def render_clean( + cache: bool, + tos: bool, + all: bool, # noqa: A002 + *, + tos_root: str | os.PathLike[str] | Path, + json: bool = False, + console: Console | None = None, # noqa: ARG001 + printer: Callable[..., None], + json_printer: Callable[..., None], +) -> int: + """Clean the metadata cache directories.""" + if not (all or cache or tos): + raise ArgumentError( + "At least one removal target must be given. See 'conda tos clean --help'." + ) + + json_output: dict[str, Any] = {} + if all or cache: + json_output["cache"] = cache_files = list(map(str, clean_cache())) + printer(f"Removed {len(cache_files)} cache files.") + if all or tos: + json_output["tos"] = tos_files = list(map(str, clean_tos(tos_root))) + printer(f"Removed {len(tos_files)} Terms of Service files.") + + if json: + json_printer(data=json_output) + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/exceptions.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..46b2394c3c73e3f3fd06fdbc1b8480ba0533a55b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/exceptions.py @@ -0,0 +1,115 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Custom exceptions.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from conda.exceptions import CondaError +from conda.models.channel import Channel + +if TYPE_CHECKING: + import os + from collections.abc import Iterable + from pathlib import Path + from typing import Self + + +class CondaToSError(CondaError): + """Base exception.""" + + +class CondaToSMissingError(CondaToSError): + """Error class for when the metadata is missing for a channel.""" + + def __init__(self: Self, channel: str | Channel) -> None: + """Format error message with channel base URL.""" + super().__init__(f"No Terms of Service for {_url(channel)}.") + + +class CondaToSInvalidError(CondaToSMissingError): + """Error class for when the metadata is invalid for a channel.""" + + def __init__(self: Self, channel: str | Channel) -> None: + """Format error message with channel base URL.""" + super().__init__(f"Invalid Terms of Service for {_url(channel)}.") + + +class CondaToSPermissionError(PermissionError, CondaToSError): + """Error class for when the metadata file cannot be written.""" + + def __init__( + self: Self, + path: str | os.PathLike[str] | Path, + channel: str | Channel | None = None, + ) -> None: + """Format error message with channel base URL and path.""" + addendum = f" for {_url(channel)}" if channel else "" + super().__init__( + f"Unable to read/write path ({path}){addendum}. Please check permissions." + ) + + +class CondaToSRejectedError(CondaToSError): + """Error class for when the Terms of Service are rejected for a channel.""" + + def __init__(self: Self, *channels: str | Channel) -> None: + """Format error message with channel base URL.""" + channel_urls = [_url(channel) for channel in channels] + accept_commands = [ + f"conda tos accept --override-channels --channel {url}" + for url in channel_urls + ] + + super().__init__( + f"Terms of Service has been rejected for the following channels. " + f"Please remove or accept them before proceeding:\n" + f"{_bullet(channel_urls)}\n" + f"\n" + f"To accept these channels' Terms of Service, run the following commands:\n" + f"{_bullet(accept_commands, prefix=' ')}\n" + f"\n" + f"{_get_removal_guidance()}" + ) + + +class CondaToSNonInteractiveError(CondaToSError): + """Error class when Terms of Service are not actionable in non-interactive mode.""" + + def __init__(self: Self, *channels: str | Channel) -> None: + """Format error message with channel base URL.""" + channel_urls = [_url(channel) for channel in channels] + accept_commands = [ + f"conda tos accept --override-channels --channel {url}" + for url in channel_urls + ] + + super().__init__( + f"Terms of Service have not been accepted for the following channels. " + f"Please accept or remove them before proceeding:\n" + f"{_bullet(channel_urls)}\n" + f"\n" + f"To accept these channels' Terms of Service, run the following commands:\n" + f"{_bullet(accept_commands, prefix=' ')}\n" + f"\n" + f"{_get_removal_guidance()}" + ) + + +def _url(channel: str | Channel) -> str: + _channel = channel if isinstance(channel, Channel) else Channel(str(channel)) + return str(_channel.base_url or channel) + + +def _bullet(args: Iterable[str], *, prefix: str = " - ") -> str: + return prefix + f"\n{prefix}".join(args) + + +def _get_removal_guidance() -> str: + """Generate removal guidance based on channel types.""" + return ( + "For information on safely removing channels from your conda configuration,\n" + "please see the official documentation:\n\n" + " https://www.anaconda.com/docs/tools/working-with-conda/channels" + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/local.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/local.py new file mode 100644 index 0000000000000000000000000000000000000000..3e715e21d18c0658082a3a1096575934a718213e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/local.py @@ -0,0 +1,120 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level local (acceptance & rejection) Terms of Service metadata management.""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import TYPE_CHECKING + +from conda.models.channel import Channel +from pydantic import ValidationError + +from .exceptions import CondaToSMissingError, CondaToSPermissionError +from .models import LocalPair, LocalToSMetadata, RemoteToSMetadata +from .path import get_all_channel_paths, get_channel_paths, get_metadata_path, get_path + +if TYPE_CHECKING: + import os + from collections.abc import Iterable, Iterator + from pathlib import Path + from typing import Any + + +def write_metadata( + tos_root: str | os.PathLike[str] | Path, + channel: str | Channel, + metadata: LocalToSMetadata | RemoteToSMetadata, + # kwargs extends/overrides metadata fields + **kwargs: Any, # noqa: ANN401 +) -> LocalPair: + """Write the metadata to file.""" + # argument validation/coercion + channel = Channel(channel) + if not channel.base_url: + raise ValueError("`channel` must have a base URL.") + if not isinstance(metadata, (LocalToSMetadata, RemoteToSMetadata)): + raise TypeError("`metadata` must be a LocalToSMetadata or RemoteToSMetadata.") + + # create/update ToSMetadata object + metadata = LocalToSMetadata( + **{ + **metadata.model_dump(), + **kwargs, + # override the following fields with the current time and channel base URL + "acceptance_timestamp": datetime.now(tz=timezone.utc), + "base_url": channel.base_url, + } + ) + + # write metadata to file + path = get_metadata_path(tos_root, channel, metadata.version) + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(metadata.model_dump_json()) + except PermissionError as exc: + # PermissionError: can't write metadata path + raise CondaToSPermissionError(path, channel) from exc + + return LocalPair(metadata=metadata, path=path) + + +def read_metadata(path: str | os.PathLike[str] | Path) -> LocalPair | None: + """Load the metadata from file.""" + try: + return LocalPair( + metadata=LocalToSMetadata.model_validate_json(get_path(path).read_text()), + path=path, + ) + except (FileNotFoundError, ValidationError): + # FileNotFoundError: metadata path doesn't exist + # ValidationError: invalid JSON schema, treat it as missing + return None + except PermissionError as exc: + # PermissionError: can't read metadata path + raise CondaToSPermissionError(path) from exc + + +def get_local_metadata( + channel: str | Channel, + *, + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> LocalPair: + """Get the latest metadata for the given channel.""" + # find all metadata files for the given channel + metadata_pairs = [ + metadata_pair + for path in get_channel_paths(channel, extend_search_path=extend_search_path) + if (metadata_pair := read_metadata(path)) + ] + + # return if no metadata found + if not metadata_pairs: + raise CondaToSMissingError(f"No Terms of Service metadata found for {channel}") + + # reverse to order from lowest to highest priority + metadata_pairs.reverse() + + # return newest (and highest priority) metadata for channel + return sorted(metadata_pairs)[-1] + + +def get_local_metadatas( + *, + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[tuple[Channel, LocalPair]]: + """Yield all metadata.""" + # group metadata by channel + grouped_metadatas: dict[Channel, list[LocalPair]] = {} + for path in get_all_channel_paths(extend_search_path=extend_search_path): + if metadata_pair := read_metadata(path): + channel = Channel(metadata_pair.metadata.base_url) + grouped_metadatas.setdefault(channel, []).append(metadata_pair) + + # return the newest (and highest priority) metadata for each channel + for channel, metadata_pairs in grouped_metadatas.items(): + # reverse to order from lowest to highest priority + metadata_pairs.reverse() + + # yield newest (and highest priority) metadata for channel + yield channel, sorted(metadata_pairs)[-1] diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/models.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/models.py new file mode 100644 index 0000000000000000000000000000000000000000..cae06ce4df993bfc1b6f866bd9e4a46e133fe2df --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/models.py @@ -0,0 +1,77 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Models to encapsulate Terms of Service metadata.""" + +from __future__ import annotations + +from datetime import datetime # noqa: TC003 # needed for Pydantic model +from pathlib import Path # noqa: TC003 # needed for Pydantic model +from typing import TYPE_CHECKING, Optional + +from pydantic import BaseModel, ConfigDict + +if TYPE_CHECKING: + from typing import Self + + +class _ToSMetadata(BaseModel): + model_config = ConfigDict(extra="allow", frozen=True) + version: datetime + text: str + support: str + + def __ge__(self: Self, other: _ToSMetadata) -> bool: + """Compare the ToS metadata version.""" + if not isinstance(other, _ToSMetadata): + return NotImplemented + return self.version >= other.version + + +class RemoteToSMetadata(_ToSMetadata): + """Metadata schema for the remote endpoint.""" + + +class LocalToSMetadata(_ToSMetadata): + """Metadata schema with acceptance fields.""" + + base_url: str + tos_accepted: bool + acceptance_timestamp: datetime + + +class _MetadataPathPair(BaseModel): + model_config = ConfigDict(frozen=True) + metadata: _ToSMetadata + # FUTURE: Python 3.10+, switch to `Path | None` + path: Optional[Path] # noqa: UP045 + # FUTURE: Python 3.10+, switch to `_ToSMetadata | None` + remote: Optional[RemoteToSMetadata] = None # noqa: UP045 + + def __lt__(self: Self, other: _MetadataPathPair) -> bool: + """Compare the metadata version. + + Critical for sorting a list of metadata path pairs. + """ + if not isinstance(other, _MetadataPathPair): + return NotImplemented + return self.metadata.version < other.metadata.version + + @property + def latest_text(self: Self) -> str: + """Get the latest text of the Terms of Service.""" + return (self.remote or self.metadata).text + + +class RemotePair(_MetadataPathPair): + """Tuple of remote metadata and no path.""" + + metadata: RemoteToSMetadata + path: None = None + remote: None = None + + +class LocalPair(_MetadataPathPair): + """Tuple of local metadata and path.""" + + metadata: LocalToSMetadata + path: Path diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/path.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/path.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7c346ea850a6162de1d84d7c07ee25497cd01d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/path.py @@ -0,0 +1,140 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level path helpers.""" + +from __future__ import annotations + +import hashlib +import os +from functools import cache +from pathlib import Path +from typing import TYPE_CHECKING + +from conda.common.compat import on_win +from conda.common.configuration import custom_expandvars +from conda.models.channel import Channel +from platformdirs import user_cache_dir + +from . import APP_NAME + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + from datetime import datetime + from typing import Final + +#: Site metadata directory. This is the highest priority location. +SITE_TOS_ROOT: Final = "C:/ProgramData/conda/tos" if on_win else "/etc/conda/tos" + +#: System metadata directory. Located in the conda installation. +SYSTEM_TOS_ROOT: Final = "$CONDA_ROOT/conda-meta/tos" + +#: User metadata directory. Located in the user home directory. +USER_TOS_ROOT: Final = "~/.conda/tos" + +#: Environment metadata directory. Located in the current conda environment. +ENV_TOS_ROOT: Final = "$CONDA_PREFIX/conda-meta/tos" + +#: Search path for metadata directories. +SEARCH_PATH: Final = tuple( + filter( + None, + ( + SITE_TOS_ROOT, + "/var/lib/conda/tos" if not on_win else None, + SYSTEM_TOS_ROOT, + "$XDG_CONFIG_HOME/conda/tos", + "~/.config/conda/tos", + USER_TOS_ROOT, + ENV_TOS_ROOT, + # mirrors $CONDARC + "$CONDATOS", + ), + ), +) + +#: Metadata file glob pattern. +TOS_GLOB: Final = "*.json" + +#: OS and user specific metadata cache directory. +CACHE_DIR: Final = Path(user_cache_dir(APP_NAME, appauthor=APP_NAME)) + + +@cache +def hash_channel(channel: str | Channel) -> str: + """Hash the channel to remove problematic characters (e.g. /).""" + channel = Channel(channel) + if not channel.base_url: + raise ValueError( + "`channel` must have a base URL. " + "(hint: `conda.models.channel.MultiChannel` cannot be hashed)" + ) + + hasher = hashlib.new("sha256") + hasher.update(channel.channel_location.encode("utf-8")) + hasher.update(channel.channel_name.encode("utf-8")) + return hasher.hexdigest() + + +def get_path(path: str | os.PathLike[str] | Path) -> Path: + """Expand environment variables and user home in the path.""" + if isinstance(path, str): + path = custom_expandvars(path, os.environ) + elif not isinstance(path, Path): + raise TypeError("`path` must be a string or `pathlib.Path`.") + return Path(path).expanduser() + + +def get_search_path( + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[Path]: + """Get all root metadata paths ordered from highest to lowest priority.""" + seen: set[Path] = set() + for tos_root in (*SEARCH_PATH, *(extend_search_path or ())): + if (path := get_path(tos_root)).is_dir() and path not in seen: + yield path + seen.add(path) + + +def get_tos_dir( + tos_root: str | os.PathLike[str] | Path, + channel: str | Channel, +) -> Path: + """Get the metadata directory for the given channel.""" + return get_path(tos_root) / hash_channel(channel) + + +def get_metadata_path( + tos_root: str | os.PathLike[str] | Path, + channel: str | Channel, + version: datetime, +) -> Path: + """Get the metadata file path for the given channel and version.""" + return get_tos_dir(tos_root, channel) / f"{version.timestamp()}.json" + + +def get_all_channel_paths( + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[Path]: + """Get all local metadata file paths.""" + for path in get_search_path(extend_search_path): + yield from sorted(get_path(path).glob(f"*/{TOS_GLOB}")) + + +def get_channel_paths( + channel: str | Channel, + *, + extend_search_path: Iterable[str | os.PathLike[str] | Path] | None = None, +) -> Iterator[Path]: + """Get all local metadata file paths for the given channel.""" + for path in get_search_path(extend_search_path): + yield from sorted(get_tos_dir(path, channel).glob(TOS_GLOB)) + + +def get_cache_path(channel: str | Channel) -> Path: + """Get the metadata cache file path for the given channel.""" + return CACHE_DIR / f"{hash_channel(channel)}.cache" + + +def get_cache_paths() -> Iterator[Path]: + """Get all local metadata cache file paths.""" + yield from sorted(CACHE_DIR.glob("*.cache")) diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/plugin.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..6c81d1cb42a4bdca3152f190f379eb28540ce6f8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/plugin.py @@ -0,0 +1,411 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""High-level conda plugin registration.""" + +from __future__ import annotations + +from datetime import timedelta +from functools import cache +from typing import TYPE_CHECKING + +from conda.base.context import context +from conda.cli.helpers import add_parser_prefix, add_parser_verbose +from conda.common.configuration import PrimitiveParameter +from conda.common.constants import NULL +from conda.plugins import ( + CondaPreCommand, + CondaRequestHeader, + CondaSetting, + CondaSubcommand, + hookimpl, +) +from rich.console import Console + +from . import APP_NAME, APP_VERSION +from .api import CI, get_channels +from .console import ( + noop_printer, + render_accept, + render_clean, + render_info, + render_interactive, + render_list, + render_reject, + render_view, +) +from .exceptions import CondaToSMissingError +from .local import get_local_metadata +from .path import ENV_TOS_ROOT, SITE_TOS_ROOT, SYSTEM_TOS_ROOT, USER_TOS_ROOT +from .remote import ENDPOINT + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace + from collections.abc import Iterator + from typing import Callable + + +#: Default metadata storage location. +DEFAULT_TOS_ROOT = USER_TOS_ROOT + +#: Default cache timeout in seconds. +DEFAULT_CACHE_TIMEOUT = timedelta(hours=1).total_seconds() + +#: Field separator for request header +FIELD_SEPARATOR = ";" + +#: Key-value separator for request header +KEY_SEPARATOR = "=" + +#: Terms of Service acceptance request header +TOS_ACCEPT_HEADER = "Anaconda-ToS-Accept" + +#: Hosts to which the Terms of Service header is added +HOSTS = {"repo.anaconda.com"} + + +def _add_channel(parser: ArgumentParser) -> None: + channel_group = parser.add_argument_group("Channel Customization") + channel_group.add_argument( + "-c", + "--channel", + action="append", + help="Additional channels to search for Terms of Service.", + ) + channel_group.add_argument( + "--override-channels", + action="store_true", + help="Do not search default or .condarc channels. Requires --channel.", + ) + + +def _add_location(parser: ArgumentParser) -> None: + location_group = parser.add_argument_group("Local Metadata Storage Location") + location_mutex = location_group.add_mutually_exclusive_group() + for flag, value, text in ( + ("--site", SITE_TOS_ROOT, "System-wide storage location."), + ("--system", SYSTEM_TOS_ROOT, "Conda installation storage location."), + ("--user", USER_TOS_ROOT, "User storage location."), + ("--env", ENV_TOS_ROOT, "Conda environment storage location."), + ): + location_mutex.add_argument( + flag, + dest="tos_root", + action="store_const", + const=value, + help=text, + ) + location_mutex.add_argument( + "--tos-root", + action="store", + help="Custom storage location.", + ) + parser.set_defaults(tos_root=DEFAULT_TOS_ROOT) + + +def _add_cache(parser: ArgumentParser) -> None: + cache_group = parser.add_argument_group("Cache Control") + cache_mutex = cache_group.add_mutually_exclusive_group() + cache_mutex.add_argument( + "--cache-timeout", + action="store", + type=int, + help="Cache timeout (in seconds) to check for Terms of Service updates.", + ) + cache_mutex.add_argument( + "--ignore-cache", + dest="cache_timeout", + action="store_const", + const=0, + help="Ignore the cache and always check for Terms of Service updates.", + ) + parser.set_defaults(cache_timeout=DEFAULT_CACHE_TIMEOUT) + + +def _add_json(parser: ArgumentParser) -> None: + # TODO: replace with conda.cli.helpers.add_parser_json + parser.add_argument( + "--json", + action="store_true", + default=NULL, + help="Report all output as json. Suitable for using conda programmatically.", + ) + + +def configure_parser(parser: ArgumentParser) -> None: + """Configure the parser for the `tos` subcommand.""" + # conda tos --version + parser.add_argument( + "-V", + "--version", + action="version", + version=f"{APP_NAME} {APP_VERSION}", + help=f"Show the {APP_NAME} version number and exit.", + ) + + # conda tos (default behavior) + _add_channel(parser) + add_parser_prefix(parser) + _add_cache(parser) + _add_json(parser) + add_parser_verbose(parser) + parser.set_defaults(tos_root=DEFAULT_TOS_ROOT) + + # conda tos + subparsers = parser.add_subparsers( + title="subcommand", + description="The following subcommands are available.", + dest="cmd", + required=False, + ) + + # conda tos accept + accept_parser = subparsers.add_parser( + "accept", + help=( + "Accept the Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(accept_parser) + add_parser_prefix(accept_parser) + _add_location(accept_parser) + _add_cache(accept_parser) + _add_json(accept_parser) + + # conda tos reject + reject_parser = subparsers.add_parser( + "reject", + help=( + "Reject the Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(reject_parser) + add_parser_prefix(reject_parser) + _add_location(reject_parser) + _add_cache(reject_parser) + _add_json(reject_parser) + + # conda tos view + view_parser = subparsers.add_parser( + "view", + help=( + "View the Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(view_parser) + add_parser_prefix(view_parser) + _add_location(view_parser) + _add_cache(view_parser) + _add_json(view_parser) + + # conda tos interactive + interactive_parser = subparsers.add_parser( + "interactive", + help=( + "Interactively accept/reject/view Terms of Service for all active channels " + "(default, .condarc, and/or those specified via --channel)." + ), + ) + _add_channel(interactive_parser) + add_parser_prefix(interactive_parser) + _add_location(interactive_parser) + _add_cache(interactive_parser) + _add_json(interactive_parser) + add_parser_verbose(interactive_parser) + + # conda tos info + info_parser = subparsers.add_parser( + "info", + help=( + "Display information about the plugin " + "(e.g., search path and cache directory)." + ), + ) + _add_json(info_parser) + + # conda tos clean + clean_parser = subparsers.add_parser( + "clean", + help="Clean the cache directories.", + ) + clean_parser.add_argument( + "--cache", + action="store_true", + help="Remove all cache files.", + ) + clean_parser.add_argument( + "--tos", + action="store_true", + help="Remove all acceptances/rejections.", + ) + clean_parser.add_argument( + "--all", + action="store_true", + help="Invoke both `--cache` and `--tos`.", + ) + _add_json(clean_parser) + + +def execute(args: Namespace) -> int: + """Execute the `tos` subcommand.""" + try: + # FUTURE: update once we only support conda 25.5+ + from conda.core.prefix_data import PrefixData + + PrefixData(context.target_prefix).assert_exists() + except AttributeError: + # AttributeError: PrefixData.assert_exists isn't defined + from pathlib import Path + + from conda.exceptions import EnvironmentLocationNotFound + + if not (prefix := Path(context.target_prefix).exists()): + raise EnvironmentLocationNotFound(prefix) from None + + console = Console() + action: Callable + kwargs = {} + if args.cmd == "accept": + action = render_accept + elif args.cmd == "reject": + action = render_reject + elif args.cmd == "view": + action = render_view + elif args.cmd == "interactive": + action = render_interactive + kwargs["auto_accept_tos"] = context.plugins.auto_accept_tos + kwargs["always_yes"] = context.always_yes + kwargs["verbose"] = context.verbose + elif args.cmd == "info": + # refactor into `conda info` plugin (when possible) + return render_info(json=context.json, console=console) + elif args.cmd == "clean": + # refactor into `conda clean` plugin (when possible) + return render_clean( + cache=args.cache, + tos=args.tos, + all=args.all, + tos_root=args.tos_root, + json=context.json, + console=console, + ) + else: + # default + action = render_list + kwargs["verbose"] = context.verbose + + return action( + *context.channels, + tos_root=args.tos_root, + cache_timeout=args.cache_timeout, + json=context.json, + console=console, + **kwargs, + ) + + +@hookimpl +def conda_subcommands() -> Iterator[CondaSubcommand]: + """Return a list of subcommands for the plugin.""" + yield CondaSubcommand( + name="tos", + action=execute, + summary=( + "A subcommand for viewing, accepting, rejecting, and otherwise interacting " + "with a channel's Terms of Service (ToS). This plugin periodically checks " + "for updated Terms of Service for the active/selected channels. " + "Channels with a Terms of Service will need to be accepted or rejected " + "prior to use. Conda will only allow package installation from channels " + "without a Terms of Service or with an accepted Terms of Service. " + "Attempting to use a channel with a rejected Terms of Service will result " + "in an error." + ), + configure_parser=configure_parser, + ) + + +@hookimpl +def conda_settings() -> Iterator[CondaSetting]: + """Return a list of settings for the plugin.""" + yield CondaSetting( + name="auto_accept_tos", + description="Automatically accept Terms of Service (ToS) for all channels.", + parameter=PrimitiveParameter(False, element_type=bool), + ) + + +def _pre_command_check_tos(_command: str) -> None: + render_interactive( + *context.channels, + tos_root=DEFAULT_TOS_ROOT, + cache_timeout=DEFAULT_CACHE_TIMEOUT, + json=context.json, + verbose=context.verbose, + auto_accept_tos=context.plugins.auto_accept_tos, + always_yes=context.always_yes, + json_printer=noop_printer, # no JSON output even if --json + ) + + +@hookimpl(tryfirst=True) +def conda_pre_commands() -> Iterator[CondaPreCommand]: + """Return a list of pre-commands for the plugin.""" + yield CondaPreCommand( + name="check_tos", + action=_pre_command_check_tos, + run_for={ + "create", + "env_create", + "env_remove", + "env_update", + "install", + "remove", + "rename", + "search", + "update", + }, + ) + + +@cache +def _get_tos_acceptance_header() -> str: + values = [] + for channel in get_channels(*context.channels): + try: + local_pair = get_local_metadata( + channel, + extend_search_path=[DEFAULT_TOS_ROOT], + ) + except CondaToSMissingError: + pass + else: + values.append( + KEY_SEPARATOR.join( + ( + channel.base_url, + str(int(local_pair.metadata.version.timestamp())), + "accepted" if local_pair.metadata.tos_accepted else "rejected", + str(int(local_pair.metadata.acceptance_timestamp.timestamp())), + ) + ) + ) + if CI: + values.append("CI=true") + return FIELD_SEPARATOR.join(values) + + +@hookimpl +def conda_request_headers(host: str, path: str) -> Iterator[CondaRequestHeader]: + """Return a list of request headers for the plugin.""" + if ( + # only add the header to anaconda.com endpoints + host in HOSTS + # only add the Terms of Service header for non-Terms of Service endpoints + and not path.endswith(f"/{ENDPOINT}") + ): + yield CondaRequestHeader( + name=TOS_ACCEPT_HEADER, + value=_get_tos_acceptance_header(), + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/py.typed b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/remote.py b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/remote.py new file mode 100644 index 0000000000000000000000000000000000000000..a0b183813b31f8e0fa35840947ac6d83db323839 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_anaconda_tos/remote.py @@ -0,0 +1,179 @@ +# Copyright (C) 2024 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Low-level remote (the "raw" endpoint JSON) Terms of Service metadata management.""" + +from __future__ import annotations + +from datetime import datetime +from json import JSONDecodeError +from typing import TYPE_CHECKING + +from conda.base.context import context +from conda.common.url import join_url +from conda.gateways.connection.session import get_session +from conda.models.channel import Channel +from pydantic import ValidationError +from requests.exceptions import RequestException + +from .exceptions import ( + CondaToSInvalidError, + CondaToSMissingError, + CondaToSPermissionError, +) +from .models import RemoteToSMetadata +from .path import get_cache_path + +if TYPE_CHECKING: + from pathlib import Path + from typing import Final + + from requests import Response + +ENDPOINT: Final = "terms.json" + + +def get_endpoint(channel: str | Channel) -> Response: + """Get the metadata endpoint for the given channel.""" + channel = Channel(channel) + if not channel.base_url: + raise ValueError( + "`channel` must have a base URL. " + "(hint: `conda.models.channel.MultiChannel` doesn't have an endpoint)" + ) + + session = get_session(channel.base_url) + url = join_url(channel.base_url, ENDPOINT) + + saved_token_setting = context.add_anaconda_token + try: + # do not inject conda/binstar token into URL for two reasons: + # 1. Metadata endpoint shouldn't be a protected endpoint + # 2. CondaHttpAuth.add_binstar_token adds subdir to the URL + # which the metadata endpoint doesn't have + context.add_anaconda_token = False + response = session.get( + url, + headers={"Content-Type": "application/json"}, + timeout=( + context.remote_connect_timeout_secs, + context.remote_read_timeout_secs, + ), + ) + response.raise_for_status() + except RequestException as exc: + # RequestException: failed to get metadata endpoint + raise CondaToSMissingError(channel) from exc + finally: + context.add_anaconda_token = saved_token_setting + return response + + +def get_cached_endpoint( + channel: str | Channel, + *, + cache_timeout: int | float | None = float("inf"), +) -> Path | None: + """Get the path to cached payload for the given channel.""" + # early exit if cache is disabled + if not cache_timeout: + return None + + # argument validation/coercion + path = get_cache_path(channel) + if not isinstance(cache_timeout, (int, float)): + raise TypeError("`cache_timeout` must be an integer, float, or falsy.") + + # get mtime of cache + try: + mtime = path.stat().st_mtime + except FileNotFoundError: + # FileNotFoundError: cache path doesn't exist + return None + + # check if cache is stale + now = datetime.now().timestamp() # noqa: DTZ005 + if (now - mtime) >= cache_timeout: + return None + return path + + +def write_cached_endpoint( + channel: str | Channel, + metadata: RemoteToSMetadata | None, +) -> Path: + """Write the metadata cache for the given channel.""" + # argument validation/coercion + path = get_cache_path(channel) + if metadata and not isinstance(metadata, RemoteToSMetadata): + raise TypeError("`metadata` must be a RemoteToSMetadata.") + + # write to cache + try: + path.parent.mkdir(parents=True, exist_ok=True) + if metadata: + path.write_text(metadata.model_dump_json()) + else: + path.touch() + except PermissionError as exc: + # PermissionError: can't write to cache path + raise CondaToSPermissionError(path, channel) from exc + + return path + + +def get_remote_metadata( # noqa: C901 + channel: str | Channel, + *, + cache_timeout: int | float | None = None, +) -> RemoteToSMetadata: + """Get the metadata metadata for the given channel.""" + # argument validation/coercion + cache = get_cached_endpoint( + channel, + # when in offline mode cache_timeout is ignored + cache_timeout=float("inf") if context.offline else cache_timeout, + ) + + # return cached metadata + if cache: + try: + text = cache.read_text().strip() + if not text: + raise CondaToSMissingError(channel) + except FileNotFoundError as exc: + # FileNotFoundError: cache path doesn't exist + raise CondaToSMissingError(channel) from exc + except PermissionError as exc: + # PermissionError: can't read cache path + raise CondaToSPermissionError(cache, channel) from exc + + try: + return RemoteToSMetadata.model_validate_json(text) + except ValidationError as exc: + # ValidationError: invalid JSON schema + raise CondaToSInvalidError(channel) from exc + + # return remote metadata + try: + metadata = RemoteToSMetadata(**get_endpoint(channel).json()) + except CondaToSMissingError: + # CondaToSMissingError: no Terms of Service for this channel + # create an empty cache to prevent repeated requests + write_cached_endpoint(channel, None) + raise + except RuntimeError as exc: + # RuntimeError: potentially raised by CondaSession due to --offline + if "offline mode" in exc.args[0]: + write_cached_endpoint(channel, None) + raise CondaToSMissingError(channel) from exc + raise + except (AttributeError, TypeError, JSONDecodeError, ValidationError) as exc: + # AttributeError: response has no JSON + # TypeError: invalid JSON + # JSONDecodeError: invalid JSON + # ValidationError: invalid JSON schema + write_cached_endpoint(channel, None) + raise CondaToSInvalidError(channel) from exc + else: + write_cached_endpoint(channel, metadata) + return metadata diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..94a84fe1b86a82ccb244d48f95f8e8ecd5d84ba3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/METADATA @@ -0,0 +1,120 @@ +Metadata-Version: 2.3 +Name: conda-content-trust +Version: 0.2.0 +Summary: Signing and verification tools, geared toward the conda ecosystem. +Project-URL: repository, https://github.com/conda/conda-content-trust +Project-URL: changelog, https://github.com/conda/conda-content-trust/blob/main/CHANGELOG.md +Author-email: "Anaconda, Inc." +License: BSD License + + Copyright (c) 2019, Anaconda, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * 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. + + * 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 NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. +License-File: AUTHORS.md +License-File: LICENSE +Keywords: authentication,compromise,conda,conda-authentication-resources,conda-content-trust,key,secure,signing,verify +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.8 +Requires-Dist: cryptography>=41 +Provides-Extra: gpgsigning +Requires-Dist: securesystemslib==0.13.1; extra == 'gpgsigning' +Description-Content-Type: text/markdown + +[ci-tests-badge]: https://github.com/conda/conda-content-trust/actions/workflows/tests.yml/badge.svg +[codecov-badge]: https://img.shields.io/codecov/c/github/conda/conda-content-trust/main.svg?label=coverage +[release-badge]: https://img.shields.io/github/release/conda/conda-content-trust.svg + +# Conda Content Trust: Signing and verification tools for Conda + +[![Tests (GitHub Actions)][ci-tests-badge]](https://github.com/conda/conda-content-trust/actions/workflows/tests.yml) +[![Codecov Status][codecov-badge]](https://codecov.io/gh/conda/conda-content-trust/branch/main) +[![latest release version][release-badge]](https://github.com/conda/conda-content-trust/releases) + +*What:* Based on [The Update Framework (TUF)](https://theupdateframework.io/), conda-content-trust is intended to ensure that when users in the conda ecosystem obtain a package or data about that package, they can know whether or not it is trustworthy (e.g. originally comes from a reliable source and has not been tampered with). A basic library and basic CLI are included to provide signing, verification, and trust delegation functionality. + +*Why:* This exists as an alteration of TUF because of the very particular needs of the conda ecosystem. (Developers are encouraged to *just use TUF* whenever possible!) + +*Where:* This tool is general purpose. It is currently used in conda 4.10.1+ to verify package metadata signatures when they are available ([announcement](https://www.anaconda.com/blog/conda-signature-verification), [instructions](https://docs.anaconda.com/anaconda-commercial/security)). + +## Installation + +Installation can be accomplished via conda: + +``` +conda install conda-content-trust +``` + +Or via pip: + +``` +pip install conda-content-trust +``` + +(If you intend to tinker with the code, feel free to use an editable install: `pip install -e .`) + +### Optional Dependencies for Producing Signatures with GPG Keys / YubiKeys + +If you intend to *create* *GPG* key signatures (as opposed to the typical non-GPG signatures), and/or you intend to use the YubiKey interface, you will need to install two optional dependencies: + +- `GPG` (any gpg client that provides command-line gpg functionality should do) +- `securesystemslib` (`pip install securesystemslib`) + +## Demonstration and Use + +Use of the command-line utility provides help functionality:: + +``` +conda-content-trust --help +``` + +You should be able to run the demo after installing: + +``` +python3 demo.py +``` + +(Portions of the demo may require the optional dependencies above.) + + +## Testing + +Each set of tests is a module in the `tests/` directory. These can all be run with: + +``` +pytest +``` diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f50d62ca90856561e9d9ca6cd7dd1f59504a58ab --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/RECORD @@ -0,0 +1,30 @@ +../../../bin/conda-content-trust,sha256=OfC4-yB1uYgSaGN2jMKM2Ple0ZiyrRxG4THIjwPfgIU,503 +conda_content_trust-0.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda_content_trust-0.2.0.dist-info/METADATA,sha256=eo811VHSYxFaTR77I-T4HdmhWItjO4DDBF_EVr4Yq18,5708 +conda_content_trust-0.2.0.dist-info/RECORD,, +conda_content_trust-0.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_content_trust-0.2.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +conda_content_trust-0.2.0.dist-info/direct_url.json,sha256=C1jzrre-6wpDEHARV_LvNb0k-oLn2D1CpxsogJF0Y7M,113 +conda_content_trust-0.2.0.dist-info/entry_points.txt,sha256=8kIfTSV2muIUqQV0jZzZU-XWcLOhJebM1VmiODqvSYA,126 +conda_content_trust-0.2.0.dist-info/licenses/AUTHORS.md,sha256=M67rb4QLM9565Na6CHZnKeljEOtcozVchaRP011OG_0,281 +conda_content_trust-0.2.0.dist-info/licenses/LICENSE,sha256=Cd-oJyYTQWtOISHqn9-XCaJeGr8UTkwXyBqXWm_Xcck,1505 +conda_content_trust/__init__.py,sha256=EVu6odFu6gXZj7TD4O2hc9Lc8zkOH_VgOlp2BxvI1eU,126 +conda_content_trust/__main__.py,sha256=2913q-WtZP4QWmmL4HVY6oMURX1oOXvNzXwbpKzC4HA,122 +conda_content_trust/__pycache__/__init__.cpython-313.pyc,, +conda_content_trust/__pycache__/__main__.cpython-313.pyc,, +conda_content_trust/__pycache__/__version__.cpython-313.pyc,, +conda_content_trust/__pycache__/authentication.cpython-313.pyc,, +conda_content_trust/__pycache__/cli.cpython-313.pyc,, +conda_content_trust/__pycache__/common.cpython-313.pyc,, +conda_content_trust/__pycache__/metadata_construction.cpython-313.pyc,, +conda_content_trust/__pycache__/plugin.cpython-313.pyc,, +conda_content_trust/__pycache__/root_signing.cpython-313.pyc,, +conda_content_trust/__pycache__/signing.cpython-313.pyc,, +conda_content_trust/__version__.py,sha256=H-qsvrxCpdhaQzyddR-yajEqI71hPxLa4KxzpP3uS1g,411 +conda_content_trust/authentication.py,sha256=uZD63uParw7Yl41gkxh6IBBgqbH3WOaheQt8xFgfwQE,22695 +conda_content_trust/cli.py,sha256=XG_yINHDWkEeMihUa3Ewxpgoqxse-clkeOmlFEtlzgk,18553 +conda_content_trust/common.py,sha256=w23tDH1DmGcNbO6HVe1daV1tAsEfu92MShlv8SYwd4M,33377 +conda_content_trust/metadata_construction.py,sha256=nlo9NmnyU3MVoGeDXidG0Q6sIw6R4T0JhVbWhjxztH4,10325 +conda_content_trust/plugin.py,sha256=VrFwespayVyRwMPVWxVM4w7DjZ8XUOgR5Ygehnq9k9M,326 +conda_content_trust/root_signing.py,sha256=fwLOo8I8H_nnLtJVLZ3wBrrau_yWT2KAnBPVTOXDKFs,15395 +conda_content_trust/signing.py,sha256=Z23g2W_1WrRLCpKpKbF_YeC3HzclARp5HdvIclrNLKY,8741 diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..cdd68a497cdfa8d3f2b837225beacef711b85047 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.25.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..22024d4be5282cde1594db2afe7e8b0f824e221f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///work/perseverance-python-buildout/croot/conda-content-trust_1728487058234/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..b26481e6a0ae7224837e33038a4ddb0dfac3af7d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +conda-content-trust = conda_content_trust.cli:cli + +[conda] +conda-content-trust = conda_content_trust.plugin diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/licenses/AUTHORS.md b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/licenses/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..6f8b98dbad5b6b00b7d5090fa250adf02c0230ab --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/licenses/AUTHORS.md @@ -0,0 +1,13 @@ +All of the people who have made at least one contribution to conda-content-trust. +Authors are sorted alphabetically. + +* Bianca Henderson +* Cheng H. Lee +* Conda Bot +* Daniel Holth +* Jannis Leidel +* Ken Odegard +* Mike Sarahan +* Sebastien Awwad +* dependabot[bot] +* pre-commit-ci[bot] diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bb7dfabecb7c07ab2f0fa0d46c6c87a5f64cb4f4 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust-0.2.0.dist-info/licenses/LICENSE @@ -0,0 +1,29 @@ +BSD License + +Copyright (c) 2019, Anaconda, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* 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. + +* 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 NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6bd53805d2e37a4b9d956f0b872b82959c24c1 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/__init__.py @@ -0,0 +1,3 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from .__version__ import __version__ # noqa: F401 diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/__main__.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf77a67ba3d03e02dd5b857f230cd066e2b609d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/__main__.py @@ -0,0 +1,5 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from conda_content_trust import cli + +cli.cli() diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/__version__.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..92bd625ef64bdc4d4c561f73fd9f401f9317ce92 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/__version__.py @@ -0,0 +1,16 @@ +# file generated by setuptools_scm +# don't change, don't track in version control +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple, Union + VERSION_TUPLE = Tuple[Union[int, str], ...] +else: + VERSION_TUPLE = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE + +__version__ = version = '0.2.0' +__version_tuple__ = version_tuple = (0, 2, 0) diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/authentication.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/authentication.py new file mode 100644 index 0000000000000000000000000000000000000000..d11a9d88ce85e28b12a8171395e7365ee6abc159 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/authentication.py @@ -0,0 +1,539 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This module contains functions that verify signatures and thereby authenticate +data. + +Function Manifest for this Module + verify_signature + verify_gpg_signature + verify_signable + verify_root + verify_delegation +""" +from binascii import unhexlify +from struct import pack + +import cryptography.exceptions +from cryptography.hazmat.primitives.asymmetric import ed25519 + +from .common import ( + MetadataVerificationError, + PublicKey, + SignatureError, + UnknownRoleError, + canonserialize, + checkformat_byteslike, + checkformat_delegating_metadata, + checkformat_gpg_signature, + checkformat_hex_key, + checkformat_signable, + is_gpg_signature, + is_hex_key, + is_hex_signature, + is_signable, + is_signature, +) + + +# TODO✅: Consider reversing this argument order? What's more intuitive? +def verify_root(trusted_current_root_metadata, untrusted_new_root_metadata): + """ + Given currently trusted root metadata, verify that new root metadata is + trustworthy per the currently trusted root metadata. + + This requires a root chaining process as specified in The Update Framework + specification. (Version N must be used in order to verify version N+1. + Versions cannot be skipped.) + + # TODO✅: Proper docstring. + """ + # TODO✅💣❌⚠️: Vet against root chaining algorithm we updated in TUF, + # and add the attack tests to tests/test_authentication.py. + + # TODO✅: More argument validation + checkformat_delegating_metadata(trusted_current_root_metadata) + checkformat_delegating_metadata(untrusted_new_root_metadata) + + if ( + trusted_current_root_metadata["signed"]["type"] != "root" + or untrusted_new_root_metadata["signed"]["type"] != "root" + ): + raise ValueError( + "Expected two instances of root metadata. Listed metadata " + "type in one or both pieces of metadata provided is not " + '"root".' + ) + + # Extract rules for root from old, trusted version of root. + root_expectations = trusted_current_root_metadata["signed"]["delegations"]["root"] + expected_threshold = root_expectations["threshold"] + authorized_pub_keys = root_expectations["pubkeys"] + + # Also extract new rules for root per new untrusted version of root. + # NOTE THAT it is important that a new root version be verified BOTH + # based on the prior, trusted version of root, and also based on ITSELF + # (the latter in order to reduce the odds of accidentally breaking the root + # trust chain). + new_root_expectations = untrusted_new_root_metadata["signed"]["delegations"]["root"] + new_expected_threshold = new_root_expectations["threshold"] + new_authorized_pub_keys = new_root_expectations["pubkeys"] + + trusted_root_version = trusted_current_root_metadata["signed"]["version"] + untrusted_root_version = untrusted_new_root_metadata["signed"]["version"] + + if trusted_root_version + 1 != untrusted_root_version: + # TODO ✅: Create a suitable error class for this. + raise MetadataVerificationError( + "Root chaining failure: we currently trust a version of root " + "that marks itself as version " + + str(trusted_root_version) + + ", and the provided new root metadata to verify marks itself " + "as version " + str(untrusted_root_version) + "; the new " + "version must be 1 more than the old version: root updates " + "MUST be processed one at a time for security reasons: no " + "root version may be skipped." + ) + + # Verify the new root metadata based on the prior, trusted root version. + verify_signable( + untrusted_new_root_metadata, authorized_pub_keys, expected_threshold, gpg=True + ) + + # Make sure that the signatures on the new root metadata would be + # sufficient to verify it using the new root metadata's own rules as well. + # Doing this helps avoid breaking the chain of trust. + verify_signable( + untrusted_new_root_metadata, + new_authorized_pub_keys, + new_expected_threshold, + gpg=True, + ) + + +# TODO ✅: Consider verify_untrusted_based_on_trusted(), a function that just +# takes the two roles and does the digging to fetch authorized keys +# and threshold for you, along with an argument specifying what role +# we're trying to verify (redundant, perhaps, but important to make +# explicit, to avoid bad patterns of trusting attackers in the calling +# code). +# The function should: +# - return if verification succeeds +# - raise UnknownRoleError if there's no matching delegation +# - raise a verification failure error if a signature is bad or +# signatures don't match expectations (threshold, wrong keys, +# etc.) +# - of course, raise ValueError if the arguments are invalid +# +# TODO ✅: Autodetect signature type rather than expecting an argument, +# and allow both OpenPGP-facilitated ed25519 and raw ed25519 +# signatures for any authority metadata (root, key_mgr, etc.) +# TODO ✅: Find way to specifically discourage anti-pattern of calling +# verify_delegation() directly to verify root metadata (instead of +# calling verify_root). We could add a _helper function and have +# both verify_delegation and verify_root call that, and each check +# to make sure the metadata type provided is/isn't root as +# appropriate, but I'd like to avoid adding another level of +# functions if possible. +# TODO ✅: Remove delegation_name and just take it from +# untrusted_delegating_metadata['signed']['type']. Consider utility +# of keeping argument, though... (allow enforcement, if you have +# reason to constrain the verifications? unlikely to be a useful arg) +def verify_delegation( + delegation_name, + untrusted_delegated_metadata, + trusted_delegating_metadata, + gpg=False, +): + """ + Verify that the given untrusted, delegated-to metadata is trustworthy, + based on the given trusted metadata's expectations (expected keys and + threshold). This function returns if verification succeeds. + + + In other words, check trusted_delegating_metadata's delegation + to delegation_name to find the expected signing keys and threshold for + delegation_name, and then check untrusted_delegated_metadata to see if it + is signed by enough of the right keys to be trustworthy. + + For example, using root metadata to verify key_mgr metadata looks like + this: + verify_delegation( + 'key_mgr', , ) + + Arguments: + (string) delegation_name is the name of the role delegated. + (dict) trusted_delegating_metadata is a signable JSON-serializable + object representing the full metadata that delegates to role + delegation_name. + (dict) untrusted_delegated_metadata is a signable JSON-serializable + object + (bool) gpg should be true if the signatures to be verified in the + delegated metadata are expected to be OpenPGP signatures + rather than the usual raw ed25519 signatures. + + Exceptions: + - raises UnknownRoleError if there's no matching delegation + - raises SignatureError if a signature is bad or signatures + don't match expectations (threshold, wrong keys, etc.) + # TODO: Consider exception handling to raise MetadataVerificationError instead? + - raises MetadataVerificationError if the metadata type is unexpected + - raises TypeError or ValueError if the arguments are invalid + """ + + # Argument validation + + if not isinstance(delegation_name, str): + raise TypeError( + "delegation_name must be a string, not a " + str(type(delegation_name)) + ) + + if gpg not in [True, False]: + raise TypeError( + 'Argument "gpg" must be a boolean.' + ) # should probably be ValueError + + checkformat_delegating_metadata(trusted_delegating_metadata) + + # Note that we don't really know the structure of the metadata we're + # verifying beyond that we expect it to be a signed envelope. + # We can't assume, for example, that it is itself delegating metadata also, + # (so no checkformat_delegating_metadata on it): while it could be + # that we're verifying key_mgr using root, it could also be that we're + # verifying some package metadata (which is not delegating metadata) using + # key_mgr. + # If, however, the untrusted_delegated_metadata *is* delegating metadata, + # we want to make sure that its type matches what the caller passed in as + # delegation_name. + checkformat_signable(untrusted_delegated_metadata) + try: + checkformat_delegating_metadata(untrusted_delegated_metadata) + except: + # If we can't verify that we're verifying more delegating metadata + # (e.g. we're using root to verify key_mgr), then we don't need to + # perform the type check, as it can just be any signed content we're + # verifying. + pass + else: + # If this is indeed more delegating metadata, make sure the type + # the caller expects matches what the metadata claims. + if delegation_name != untrusted_delegated_metadata["signed"]["type"]: + raise MetadataVerificationError( + "Instructed to verify provided metadata as if it is of " + 'type "' + delegation_name + '", but it claims to be of ' + 'type "' + untrusted_delegated_metadata["signed"]["type"] + '"!' + ) + + # Process the delegation. + delegations = trusted_delegating_metadata["signed"]["delegations"] + + if delegation_name not in delegations: + raise UnknownRoleError( + "Role " + delegation_name + " not found in the given " + "delegating metadata." + ) + + expected_keys = delegations[delegation_name]["pubkeys"] + threshold = delegations[delegation_name]["threshold"] + + verify_signable( + untrusted_delegated_metadata, + expected_keys, # drawn from trusted_delegating_metadata + threshold, # drawn from trusted_delegating_metadata + gpg=gpg, + ) # from argument to this func + + +# TODO ✅: Consider taking a hex public key instead of a key object, so that: +# 1: the API is simpler (verify_signature is part of the API) +# 2: we can remove PublicKey from the higher-level code, making it +# simpler. +# The tradeoff is that we can't later accept key objects that might +# be used as interfaces to hardware keys, for example. +def verify_signature(signature, public_key, data): + """ + Raises ❌cryptography.exceptions.InvalidSignature if signature is not a + correct signature by the given key over the given data. + + Raises ❌TypeError if public_key, signature, or data are not correctly + formatted. + + Otherwise, returns (nothing), indicating the signature was verified. + + Note that this does not use the generalized signature format (which would + be compatible with OpenPGP/GPG signatures as well as pyca/cryptography's + simple ed25519 sigs). + + Args: + - public_key must be an ed25519.Ed25519PublicKeyObject + - signature must be a hex string, length 128, representing a 64-byte + raw ed25519 signature + - data must be bytes + """ + if not isinstance(public_key, ed25519.Ed25519PublicKey): + raise TypeError( + "verify_signature expects a " + "cryptography.hazmat.primitives.asymmetric.ed25519ed25519.Ed25519PublicKey" + 'object as the "public_key" argument. Instead, received ' + + str(type(public_key)) + ) + + if not is_hex_signature(signature): + raise TypeError( + "verify_signature expects a hex string representing an " + 'ed25519 signature as the "signature" argument. Instead, ' + "received object of type " + str(type(signature)) + ) + + if not isinstance(data, bytes): + raise TypeError( + 'verify_signature expects a bytes object as the "signature" ' + "argument. Instead, received " + str(type(data)) + ) + + public_key.verify(unhexlify(signature), data) + + # If no error is raised, return, indicating success (Explicit for editors) + return + + +def verify_signable(signable, authorized_pub_keys, threshold, gpg=False): + """ + Raises a ❌SignatureError if signable does not include at least threshold + good signatures from (unique) keys with public keys listed in + authorized_pub_keys, over the data contained in signable['signed']. + + Raises ❌TypeError if the arguments are invalid. + + Else returns (nothing). + + Args: + - signable + common.is_a_signable(signable) must return true. + wrap_as_signable() produces output of this type. See those + functions. + + - authorized_pub_keys + a list of ed25519 public keys (32 bytes) expressed as 64-character + hex strings. This is the form in which they appear in authority + metadata (root.json, etc.) Only good signatures from keys listed + in authorized_pub_keys count against the threshold of signatures + required to verify the signable. + + - threshold + the number of good signatures from unique authorized keys required + in order to verify the signable. + + - gpg (boolean, default False) + If True, expects OpenPGP ed25519 signatures (see RFC 4880 bis-08) + instead of raw ed25519 signatures. + If False, expects raw ed25519 signatures. + """ + + # TODO: ✅ Be sure to check with the analogous code in the tuf reference + # implementation in case one of us had some clever gotcha there. + # Would be in tuf.sig or securesystemslib. See + # get_signature_status() there, in addition to any prettier + # verify_signable code I may have swapped in (dunno if that's in yet). + + # TODO: ✅ Consider allowing this func (or another) to accept public keys + # in the form of ed25519.Ed25519PublicKey objects (instead of just + # the hex string representation of the public key bytes). I think + # we'll mostly have the hex strings on hand, but.... + + # Argument validation + if not is_signable(signable): + raise TypeError( + "verify_signable expects a signable dictionary. " + "Given argument failed the test." + ) # TODO: Tidier / expressive. + if not ( + isinstance(authorized_pub_keys, list) + and all([is_hex_key(k) for k in authorized_pub_keys]) + ): + raise TypeError("authorized_pub_keys must be a list of hex strings ") + # if not (isinstance(authorized_pub_keys, list) and all( + # [isinstance(k, ed25519.Ed25519PublicKey) for k in authorized_pub_keys])): + # raise TypeError( + # 'authorized_pub_keys must be a list of ' + # 'ed25519.Ed25519PublicKeyobjects.') + if not isinstance(threshold, int) or threshold <= 0: + raise TypeError("threshold must be a positive integer.") + + # TODO: ✅⚠️ Metadata specification version compatibility check. + # Check to see if signable['signed']['metadata_spec_version'] + # is CLOSE ENOUGH to SECURITY_METADATA_SPEC_VERSION (same + # major version?). If it is not, raise an exception noting + # that the version cannot be verified because either it or the + # client are out of date. If versions are close enough, + # consider a warning instead. If the client is at major spec + # version x, and the metadata obtained is at major spec version + # x + 1, then proceed with a warning that the client must be + # updated. Note that root versions produced must never + # increase by more than one major spec version at a time, as a + # result. + + # Put the 'signed' portion of the data into the format it should be in + # before it is signed, so that we can verify the signatures. + signed_data = canonserialize(signable["signed"]) + + # Even though we're not returning this, we produce this dictionary (instead + # of just counting) to facilitate future checks and logging. + # TODO: ✅ Keep track of unknown keys and bad signatures for diagnostic and + # other logging purposes. + good_sigs_from_trusted_keys = {} + + for pubkey_hex, signature in signable["signatures"].items(): + # Validate the signature data first (make sure it looks right). + if not is_hex_key(pubkey_hex): + # TODO: ✅ Make this a warning instead. + print( + 'Ignoring signature from "key" with public key value that ' + "does not look like a key value: " + str(pubkey_hex) + ) + continue + + if gpg and not is_gpg_signature(signature): + # TODO: ✅ Make this a warning instead. + print( + 'Ignoring "signature" that does not look like a gpg ' + "signature value: " + str(signature) + ) + continue + + if pubkey_hex not in authorized_pub_keys: + # TODO: ✅ Make this an INFO-level log message. + print( + 'Ignoring signature from a key ("' + + str(pubkey_hex) + + '") that is not authorized to sign this metadata.' + ) + continue + + if not gpg: # normal ed25519 signatures using pyca/cryptography + if not is_signature(signature): + # TODO: ✅ Make this a warning instead. + print( + 'Ignoring "signature" that does not look like a hex ' + "signature value: " + str(signature) + ) + continue + + public = PublicKey.from_hex(pubkey_hex) + + try: + verify_signature(signature["signature"], public, signed_data) + + except cryptography.exceptions.InvalidSignature: + # TODO: ✅ Log at debug or info level. + continue + + else: + good_sigs_from_trusted_keys[pubkey_hex] = signature + + else: # expecting OpenPGP ed25519 signatures (RFC 4880-bis08) + assert gpg # code paranoia + + try: + verify_gpg_signature(signature, pubkey_hex, signed_data) + + except cryptography.exceptions.InvalidSignature: + # TODO: ✅ Log at debug or info level. + continue + + else: + good_sigs_from_trusted_keys[pubkey_hex] = signature + + # TODO: ✅ Logging or more detailed info (which keys). + if len(good_sigs_from_trusted_keys) < threshold: + raise SignatureError( + "Expected good signatures from at least " + + str(threshold) + + " unique keys from a set of " + + str(len(authorized_pub_keys)) + + " keys. Saw " + + str(len(signable["signatures"])) + + " signatures, only " + + str(len(good_sigs_from_trusted_keys)) + + " of which were good signatures over the given data from the " + "expected keys." + ) + + # Otherwise, return, indicating success. (Explicit for code editors) + return + + +def verify_gpg_signature(signature, key_value, data): + """ + Verifies a raw ed25519 signature that happens to have been produced by an + OpenPGP signing process (RFC4880). + + NOTE that this code DISREGARDS most OpenPGP semantics: is interested solely + in the verification of a signature over the given data, with the raw + ed25519 public key given (in the form of a hex string). This code does not + care about the GPG public key infrastructure, including key + self-revocation, expiry, or the relationship of any key with any other key + through OpenPGP (subkeys, key-to-key signoff, etc.). + + This codebase uses OpenPGP signatures solely as a means of facilitating a + TUF-style public key infrastructure, where the public key values are + trusted with specific privileges directly. + + + ⚠️💣 ABSOLUTELY DO NOT use this for general purpose verification of GPG + signatures!! It is for our root signatures only, where OpenPGP + signing is just a proxy for a simple ed25519 signature through a + hardware signing mechanism. + + + # TODO: ✅ Proper docstring modeled on verify_signature. + """ + + checkformat_gpg_signature(signature) + checkformat_hex_key(key_value) + checkformat_byteslike(data) + # if not isinstance(data, bytes): # TODO: ✅ use the byteslike checker in conda_content_trust.common. + # raise TypeError() + + public_key = PublicKey.from_hex(key_value) + + # ------- + # This next part takes advantage of code pulled from: + # securesystemslib.gpg.eddsa.verify_signature(), + # securesystemslib.gpg.eddsa.create_pubkey(), + # and securesystemslib.gpg.util.hash_object(). + # + # It has been unrolled, had formatting adjustments, variable + # renaming, unneeded code removal, etc. + # ------- + + # See RFC4880-bis8 14.8. EdDSA and 5.2.4 "Computing Signatures" + # digest = securesystemslib.gpg.util.hash_object( + # unhexlify(signature["other_headers"]), + # hasher(), data) + + # Additional headers in the OpenPGP signature (bleh). + additional_header_data = unhexlify(signature["other_headers"]) + + # As per RFC4880 Section 5.2.4., we need to hash the content, + # signature headers and add a very opinionated trailing header + hasher = cryptography.hazmat.primitives.hashes.Hash( + cryptography.hazmat.primitives.hashes.SHA256(), + cryptography.hazmat.backends.default_backend(), + ) + hasher.update(data) + hasher.update(additional_header_data) + hasher.update(b"\x04\xff") + hasher.update(pack(">I", len(additional_header_data))) + + digest = hasher.finalize() + + # # DEBUG 💣💥 + # # DEBUG 💣💥 + # print('Digest as produced by verify_gpg_signature: ' + str(digest)) + + # Raises cryptography.exceptions.InvalidSignature if not a valid signature. + public_key.verify(unhexlify(signature["signature"]), digest) + + # Return if we succeeded. + return # explicit for clarity diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/cli.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b1e5060218f336a2a8d2f1bb0c2a0779a04c57 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/cli.py @@ -0,0 +1,534 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This module provides the CLI interface for conda-content-trust. +This is intended to provide a command-line signing and metadata update +interface. +""" +from argparse import ArgumentParser +from copy import deepcopy +from json import dumps + +from . import __version__ +from . import authentication as cct_authentication +from . import root_signing as cct_root_signing +from . import signing as cct_signing +from .common import ( + CCT_Error, + PrivateKey, + is_gpg_fingerprint, + is_hex_key, + load_metadata_from_file, + write_metadata_to_file, +) + + +def cli(args=None): + parser = ArgumentParser( + description="Signing and verification tools for Conda", + conflict_handler="resolve", + ) + parser.add_argument( + "-V", + "--version", + action="version", + help="Show the conda-content-trust version number and exit.", + version="conda-content-trust %s" % __version__, + ) + + # Create separate parsers for the subcommands. + sp = parser.add_subparsers(title="subcommands", dest="subcommand_name") + + # subcommand: sign-artifacts + + p_signrepo = sp.add_parser( + "sign-artifacts", + help=( + "Given a repodata.json " + "file, produce signatures over the metadata for each artifact listed, " + "and update the repodata.json file with their individual signatures." + ), + ) + p_signrepo.add_argument( + "repodata_fname", + help=( + "the filename of a repodata.json file from " + "which to retrieve metadata for individual artifacts." + ), + ) + p_signrepo.add_argument( + "private_key_fname", + help=( + "the filename of a file containing a " + "hex string representation of an ed25519 private key to be used " + "to sign each artifact's metadata" + ), + ) + + # subcommand: verify-metadata + + p_verifymd = sp.add_parser( + "verify-metadata", + help=( + "Uses the first (trusted) metadata file " + "to verify the second (not yet trusted) metadata file. For " + "example, " + '"conda-content-trust verify-metadata 4.root.json 5.root.json"' + " to verify version 5 of root based on version 4 of root, or " + '"conda-content-trust verify-metadata 4.root.json key_mgr.json" ' + "to verify key manager metadata based on version 4 of root." + ), + ) + p_verifymd.add_argument( + "trusted_metadata_filename", + help=( + "the filename of the " + "already-trusted metadata file that sets the rules for verifying " + "the untrusted metadata file" + ), + ) + p_verifymd.add_argument( + "untrusted_metadata_filename", + help=("the filename of the " "(untrusted) metadata file to verify"), + ) + + # subcommand: modify-metadata + + p_modifymd = sp.add_parser( + "modify-metadata", + help=( + "Interactive metadata modification. Use " + "this to produce a new version of a metadata file (like root.json " + "or key_mgr.json), or correct an error in an unpublished metadata " + "file, or review and sign a metadata file. This increments " + "version number / timestamp, reports changes on console, etc. For " + 'example, "conda-content-trust modify-metadata 8.root.json" ' + "for assistance in " + "producing a new version of root (version 9) using version 8." + ), + ) + p_modifymd.add_argument( + "metadata_filename", + help=("the filename of the existing metadata " "file to modify"), + ) + + # If we're missing optional requirements for the next few options, note + # that in their help strings. + opt_reqs_str = "" + if not cct_root_signing.SSLIB_AVAILABLE: + opt_reqs_str = ( + "[Unavailable]: Requires optional " + "dependencies: securesystemslib and gpg. " + ) + + # subcommand: gpg-key-lookup + p_gpglookup = sp.add_parser( + "gpg-key-lookup", + help=( + opt_reqs_str + + "Given the OpenPGP fingerprint of an ed25519-type OpenPGP key, fetch " + "the actual ed25519 public key value of the underlying key." + ), + ) + p_gpglookup.add_argument( + "gpg_key_fingerprint", + help=( + "the 40-hex-character key fingerprint (long keyid) for the " + "OpenPGP/GPG key that you want to sign something with. Do not " + 'add prefix "0x".' + ), + ) + + # subcommand: gpg-sign + + p_gpgsign = sp.add_parser( + "gpg-sign", + help=( + opt_reqs_str + "Sign a given " + "piece of metadata using GPG instead of the usual signing " + "mechanisms. Takes an OpenPGP key fingerprint and a filename." + ), + ) + p_gpgsign.add_argument( + "gpg_key_fingerprint", + help=( + "the 40-hex-character key fingerprint (long keyid) for the " + "OpenPGP/GPG key that you want to sign something with. Do not " + 'add prefix "0x".' + ), + ) + p_gpgsign.add_argument( + "filename", help=("the filename of the file that will be signed") + ) + + args = parser.parse_args(args) + + if args.subcommand_name == "gpg-sign": + # TODO: Validate arguments. + + # Strip any whitespace from the key fingerprint and lowercase it. + # GPG pops out keys in a variety of whitespace arrangements and cases, + # so this is necessary for convenience. + gpg_key_fingerprint = "".join(args.gpg_key_fingerprint.split()).lower() + + cct_root_signing.sign_root_metadata_via_gpg(args.filename, gpg_key_fingerprint) + + elif args.subcommand_name == "sign-artifacts": + with open(args.private_key_fname) as key_fobj: + # Lower-case the hex string and ignore any whitespace before and + # after it (in case someone adds some). + private_key_hex = key_fobj.read().strip().lower() + + if not is_hex_key(private_key_hex): + print( + "ABORTED. Expected key file to contain only a hex string " + "representation of an ed25519 key. It does not." + ) + return + + cct_signing.sign_all_in_repodata(args.repodata_fname, args.private_key_hex) + + elif args.subcommand_name == "gpg-key-lookup": + gpg_key_fingerprint = "".join(args.gpg_key_fingerprint.split()).lower() + keyval = cct_root_signing.fetch_keyval_from_gpg(gpg_key_fingerprint) + print("Underlying ed25519 public key value: " + str(keyval)) + + elif args.subcommand_name == "modify-metadata": + # `conda-content-trust update-metadata ` + + # underlying functions: build_delegating_metadata, + # load_metadata_from_file + + # given a metadata file, increment the version number and timestamps, + # reporting the changes on the console + + # strip signatures + + # indicate what signatures are required + + # ask if the user wants to sign; query for the key hex or fname; + # ideally, offer this functionality for both root and non-root keys. + # For root metadata, we can (and should) also report which keys are + # expected / still needed in order for the metadata to be verifiable + # according to the old metadata and the new metadata + + old_metadata = load_metadata_from_file(args.metadata_filename) + + # new_metadata = cct_metadata_construction.interactive_modify_metadata(old_metadata) + # if new_metadata is not None and new_metadata: + # write_metadata_to_file(new_metadata, args.metadata_filename) + + interactive_modify_metadata(old_metadata) + + elif args.subcommand_name == "verify-metadata": + # `conda-content-trust verify-metadata <(optional) role name>` + + # underlying functions: cct_authentication.verify_delegation, + # load_metadata_from_file + + # takes two metadata files, the first being a trusted file that should + # provide the verification criteria (expected keys and expected number + # of keys) for the second file. This should support root-root + # verification (root chaining as currently implemented in + # conda-content-trust) and delegation from one metadata type to another + # (e.g. root to key_mgr) + + # conveys to the user whether or not the file is trusted, and for what + # role. e.g., would convey that the first file is (e.g.) a root + # metadata file, that it provides a delegation to , and that + # the file provides and is signed + # appropriately based on what the root metadata file requires of that + # delegation. + + untrusted_metadata = load_metadata_from_file(args.untrusted_metadata_filename) + + trusted_metadata = load_metadata_from_file(args.trusted_metadata_filename) + + # TODO✅: Argument validation via the check_format_* calls. + + metadata_type = untrusted_metadata["signed"]["type"] + + if metadata_type == "root": + # Verifying root has additional steps beyond verify_delegation. + try: + cct_authentication.verify_root(trusted_metadata, untrusted_metadata) + print("Root metadata verification successful.") + return 0 # success + + except CCT_Error as e: + errorcode = 10 + errorstring = str(e) + + else: + # Verifying anything other than root just uses verify_delegation + # directly. + try: + cct_authentication.verify_delegation( + delegation_name=metadata_type, + untrusted_delegated_metadata=untrusted_metadata, + trusted_delegating_metadata=trusted_metadata, + ) + print("Metadata verification successful.") + return 0 # success + + except CCT_Error as e: + errorcode = 20 + errorstring = str(e) + + # We should only get here if verification failed. + print( + "Verification of untrusted metadata failed. Metadata " + 'type was "' + metadata_type + '". Error reads:\n "' + errorstring + '"' + ) + return errorcode # failure; exit code + + else: + parser.print_help() + + +def interactive_modify_metadata(metadata): + """ """ + + # Update version if there is a version. + # Update timestamp if there is a timestamp. + # + # Show metadata contents ('signed') -- pprint? + # indicate updated version/timestamp + # + # Changes phase: + # Prompt to + # (m) modify a value, (a) add a new entry, (d) delete an entry, + # (r) revert to original, (f) finish and sign ((move on to signing + # prompts)) + # + # Signing phase: + # Show metadata again, ask if metadata looks right + # Show what keys the original was signed by and ask if those should be + # the keys used for the new version. + # ((Later: if root, vet against contents of new and old root versions)) + # Prompt for key (raw key file, raw key data, or gpg key fingerprint) + # Sign using the given key (gpg if gpg, else normal signing mechanism). + # Write (making sure not to overwrite, and -- if root -- making sure to + # prepend "." to root.json file. + + initial_metadata = metadata + metadata = deepcopy(initial_metadata) + + try: + import pygments + import pygments.formatters + import pygments.lexers + except ImportError: + print( + "interactive modify-metadata mode employs pygments for syntax " + "highlighting, if pygments is available. pygments was not " + "found, so the JSON contents will be... uglier than they " + "would otherwise be. If you would like syntax highlighting " + "and prettier printing of JSON, you may install pygments." + ) + pygments = None + from pprint import pprint + + # Build the modification options and prompt. + def promptfor(s): + return input(F_INSTRUCT + "\n----- Please provide " + s + ENDC + ": ") + + def fn_write(): + fname = promptfor("a filename to save this metadata as") + print("Writing to file....") + write_metadata_to_file(metadata, fname) + print("Modified metadata written!") + return 1 + + def fn_abort(): + # TODO✅: Ask to confirm. + print(RED + BOLD + "\nAborting!\n" + ENDC) + return 1 + + def fn_addsig(): + if not cct_root_signing.SSLIB_AVAILABLE: + print( + F_OPTS + "Signing. " + RED + "Please ABORT (control-c) if " + "the metadata above is not EXACTLY what you want to sign!" + ENDC + ) + key = promptfor( + "a key: either:\n - a 40-character-hex-string GPG PUBLIC " + "key fingerprint\n" + " for GPG keys (e.g. root YubiKeys), or \n - a " + "64-character-hex-string PRIVATE key value for normal " + "keys.\n\n Whitespace will be removed and characters will " + "be lowercased.\n Key" + ) + key = "".join(key.split()).lower() + + if is_hex_key(key): + private_key = PrivateKey.from_hex(key) + cct_signing.sign_signable(metadata, private_key) + print(F_OPTS + "\n\n--- Successfully signed! Please save." + ENDC) + + elif is_gpg_fingerprint(key): + try: + cct_root_signing.sign_root_metadata_dict_via_gpg(metadata, key) + except: + print( + F_OPTS + + "\n\n--- " + + RED + + "Signing FAILED." + + F_OPTS + + " Do you have this key loaded in GPG on " + "this system?" + ) + else: + print(F_OPTS + "\n\n--- Successfully signed! Please save." + ENDC) + + else: + print(F_OPTS + RED + "Unable to recognize key. Please try again." + ENDC) + return 0 + + def fn_remsig(): + return 0 + + def fn_update(): + return 0 + + def fn_adddel(): + return 0 + + def fn_remdel(): + return 0 + + def fn_thresh(): + delegation = promptfor( + "a delegation name (one of the entries in the" + '\n "delegations" dictionary in the metadata above). ' + "This will\n be the delegation whose threshold number of " + "required keys we\n will change." + ) + if delegation not in metadata["signed"]["delegations"]: + print( + F_OPTS + "\n\n--- " + RED + "Unable to find that delegation." + " Please try again." + ENDC + ) + return 0 + + new_thresh = promptfor( + "a new threshold value. The current value is " + + str(metadata["signed"]["delegations"][delegation]["threshold"]) + ) + + try: + new_thresh = int(new_thresh) + assert new_thresh >= 1 + except: + print( + F_OPTS + "\n--- " + RED + "Invalid value. Expecting integer " + "greater than or equal to 1. Please try again." + ENDC + ) + return 0 + + metadata["signed"]["delegations"][delegation]["threshold"] = new_thresh + + print(F_OPTS + "\n--- Threshold successfully updated." + ENDC) + + return 0 + + def fn_addkey(): + return 0 + + def fn_remkey(): + return 0 + + options = { + 0: [fn_write, "Done: write and save metadata"], + 1: [fn_abort, "Abort: discard changes -- abort without writing"], + 2: [fn_addsig, "Add a signature (sign with a key you have)"], + 3: [fn_remsig, "Remove a signature"], + 4: [fn_update, "Update any top-level dictionary entry"], + 5: [fn_adddel, "Add a delegation"], + 6: [fn_remdel, "Remove a delegation"], + 7: [fn_thresh, "Change the threshold number of keys for a delegation"], + 8: [fn_addkey, "Add an authorized key to a delegation"], + 9: [fn_remkey, "Remove an authorized key from a delegation"], + } + + option_text = ( + F_INSTRUCT + "\n--- Please choose an operation by entering its " + "number\n" + ENDC + ) + for index in options: + option_text += ( + " " + + F_LABEL + + str(index) + + ENDC + + ": " + + options[index][1] + + ENDC + + "\n" + ) + + done = False + while not done: + print( + F_OPTS + + BOLD + + "\n\n---------------------\n--- Current metadata:\n---------------------\n" + + ENDC + ) + + if pygments is not None: + formatted_metadata = dumps(metadata, sort_keys=True, indent=4) + print( + pygments.highlight( + formatted_metadata.encode("utf-8"), + pygments.lexers.JsonLexer(), + pygments.formatters.TerminalFormatter(), + ) + ) + else: + pprint(metadata) + + print(option_text) + selected = input(F_OPTS + "Choice: " + ENDC) + try: + selected = int(selected) + except: + print(RED + BOLD + "\nInvalid entry. Try again.\n" + ENDC) + continue + if selected not in options: + print(RED + BOLD + "\nInvalid entry. Try again.\n" + ENDC) + continue + + print(F_OPTS + '\nChose "' + options[selected][1] + '"' + ENDC) + + done = options[selected][0]() # Run the func associated with the option. + + # Pull modified from debugging script + # Pull modified from debugging script + # Pull modified from debugging script + + +# Basic text formatting string constants +PINK = "\033[95m" +BLUE = "\033[94m" +CYAN = "\033[96m" +GREEN = "\033[92m" +YELLOW = "\033[93m" +RED = "\033[91m" +ENDC = "\033[0m" +BOLD = "\033[1m" +UNDERLINE = "\033[4m" + +# Complete formats +F_LABEL = ENDC + UNDERLINE + BOLD + PINK +F_INSTRUCT = ENDC + BOLD + PINK +F_OPTS = ENDC + GREEN + + +if __name__ == "__main__": + import sys + + exit_status = cli(sys.argv[1:]) + sys.exit(exit_status) diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/common.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/common.py new file mode 100644 index 0000000000000000000000000000000000000000..862a1bceb5374ed7a3df57532a21331e26443edb --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/common.py @@ -0,0 +1,918 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This module contains functions that provide format validation, serialization, +and some key transformations for the pyca/cryptography library. These are used +across conda_content_trust modules. + +Function Manifest for this Module, by Category + +Encoding: + x canonserialize + +Formats and Validation: + PrivateKey -- extends cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey + PublicKey -- extends cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey + checkformat_string + x is_hex_string + x is_hex_signature + r is_hex_key + r checkformat_hex_key + r checkformat_list_of_hex_keys + x is_signable + x checkformat_byteslike + x checkformat_natural_int + x checkformat_expiration_distance + x checkformat_utc_isoformat + x checkformat_gpg_fingerprint + is_gpg_fingerprint + x checkformat_gpg_signature + is_gpg_signature + checkformat_any_signature + checkformat_delegation + checkformat_delegations + checkformat_delegating_metadata + x iso8601_time_plus_delta + +Crypto Utility: + x sha512256 + x keyfiles_to_keys + x keyfiles_to_bytes + +Exceptions: + CCT_Error + SignatureError + MetadataVerificationError + UnknownRoleError +""" +from __future__ import annotations + +from binascii import hexlify, unhexlify +from datetime import datetime, timedelta +from json import dumps, load +from typing import Any, Protocol + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ed25519 + +# specification version for the metadata produced by conda-content-trust +# Details in the Conda Security Metadata Specification. Note that this +# version string is parsed via setuptools's packaging.version library, and so +# supports PEP 440; however, we should use a limited subset that is numerical +# only, and according to SemVer principles. +# PEP 440 compatibility: +# > None is not re.match(r'^([1-9]\d*!)?(0|[1-9]\d*)(\.(0|[1-9]\d*))*((a|b|rc)(0|[1-9]\d*))?(\.post(0|[1-9]\d*))?(\.dev(0|[1-9]\d*))?$', version_string) +# SemVer compatibility: +# > None is not re.match(r'^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)(?:-(?P(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$', version_string) +# Try, however, to keep to three simple numeric elements separated by periods, +# i.e., things that match this subset of SemVer: +# > None is not re.match(r'^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)$', version_string) +SECURITY_METADATA_SPEC_VERSION = "0.6.0" + +# The only types we're allowed to wrap as "signables" and sign are +# the JSON-serializable types. (There are further constraints to what is +# JSON-serializable in addition to these type constraints.) +SUPPORTED_SERIALIZABLE_TYPES = [dict, list, tuple, str, int, float, bool, type(None)] + +# These are the permissible strings in the "type" field of delegating metadata. +SUPPORTED_DELEGATING_METADATA_TYPES = ["root", "key_mgr"] # May be loosened later. + + +class CCT_Error(Exception): + """ + All errors we raise that are not ValueErrors, TypeErrors, or + certain errors from securesystemslib should be instances of this class or + of subclasses of this class. + """ + + +class SignatureError(CCT_Error): + """ + Indicates that a signable cannot be verified due to issues with the + signature(s) inside it. + """ + + +class MetadataVerificationError(CCT_Error): + """ + Indicates that a chain of authority metadata cannot be verified (e.g. + a metadata update is found on the repository, but could not be + authenticated). + """ + + +class UnknownRoleError(CCT_Error): + """ + Indicates that a piece of role metadata (like root.json, or key_mgr.json) + was expected but not found. + """ + + +def canonserialize(obj): + """ + Given a JSON-compatible object, does the following: + - serializes the dictionary as utf-8-encoded JSON, lazy-canonicalized + such that any dictionary keys in any dictionaries inside + are sorted and indentation is used and set to 2 spaces (using json lib) + + TODO: ✅ Implement the serialization checks from serialization document. + + Note that if the provided object includes a dictionary that is *indexed* + by both strings and integers, a TypeError will be raised complaining about + comparing strings and integers during the sort. (Each dictionary in an + object must be indexed only by strings or only by integers.) + """ + + # Try converting to a JSON string. + try: + # TODO: In the future, assess whether or not to employ more typical + # practice of using no whitespace (instead of NLs and 2-indent). + json_string = dumps(obj, indent=2, sort_keys=True) + except TypeError: + # TODO: ✅ Log or craft/use an appropriate exception class. + raise + + return json_string.encode("utf-8") + + +def load_metadata_from_file(fname): + # TODO ✅: Argument validation for fname. Consider adding "pathvalidate" + # as a dependency, and calling its sanitize_filename() here. + + with open(fname, "rb") as fobj: + metadata = load(fobj) + + # TODO ✅: Consider validating what is read here, for everywhere. + + return metadata + + +def write_metadata_to_file(metadata, filename): + """ + Canonicalizes and serializes JSON-friendly metadata, and writes that to the + given filename. + """ + + # TODO ✅: Argument validation for filename. Consider adding + # "pathvalidate" as a dependency, and calling its + # sanitize_filename() here. + + metadata = canonserialize(metadata) + + with open(filename, "wb") as fobj: + fobj.write(metadata) + + +class MixinKey: + """ + This is a mix-in (https://www.ianlewis.org/en/mixins-and-python) for the + PrivateKey and PublicKey classes, specifically. It provides some + convenience functions. + """ + + @classmethod + def to_hex(cls, key): + return hexlify(cls.to_bytes(key)).decode("utf-8") + + @classmethod + def is_equivalent_to(cls, k1, k2): + """ + Given Ed25519PrivateKey or Ed25519PublicKey objects, determines if the + underlying key data is identical. + """ + checkformat_key(k2) + if type(k1) is not type(k2): + return False + return cls.to_bytes(k1) == cls.to_bytes(k2) + + @classmethod # a class method for inheritors of this mix-in + def from_hex(cls, key_value_in_hex): + # from_private_bytes() and from_public_bytes() both check length (32), + # but do not produce helpful errors if the argument provided it is not + # the right type, so we'll do that here before calling them. + checkformat_hex_key(key_value_in_hex) + key_value_in_bytes = unhexlify(key_value_in_hex) + new_object = cls.from_bytes(key_value_in_bytes) + checkformat_key(new_object) + return new_object + + +class PrivateKey(MixinKey, ed25519.Ed25519PrivateKey): + """ + This class expands the class + cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey + very slightly, adding some functionality from MixinKey. + + Note on the sign() method: + We preserve Ed25519PrivateKey's sign method unchanged. The sign() + method is deterministic and does not depend at any point on the ability + to generate random data (unlike the key generation). The returned + value for sign() is a length 64 bytes() object, a raw ed25519 + signature. + """ + + @classmethod + def to_bytes(cls, key): + return key.private_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PrivateFormat.Raw, + encryption_algorithm=serialization.NoEncryption(), + ) + + @classmethod + def from_bytes(cls, key_value_in_bytes): + """ + Constructs an object of the class based on the given key value. + The "cryptography" library provides from_public_bytes() and + from_private_bytes() class methods for Ed25519PublicKey and + Ed25519PrivateKey classes in place of constructors. We extend provide + a single API for those, and make the created objects objects of the + subclass using this mix-in. + """ + # from_private_bytes() and from_public_bytes() both check length (32), + # but do not produce helpful errors if the argument provided it is not + # the right type, so we'll do that here before calling them. + checkformat_byteslike(key_value_in_bytes) + return super().from_private_bytes(key_value_in_bytes) + + +class PublicKey(MixinKey, ed25519.Ed25519PublicKey): + """ + This class expands the class + cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey + very slightly, adding some functionality from MixinKey. + + We preserve Ed25519PublicKey's verify() method unchanged. + """ + + @classmethod + def to_bytes(cls, key): + """ + Pops out the nice, tidy bytes of a given ed25519 key object, public or + private. + """ + return key.public_bytes( + serialization.Encoding.Raw, serialization.PublicFormat.Raw + ) + + @classmethod + def from_bytes(cls, key_value_in_bytes): + """ + Constructs an object of the class based on the given key value. + The "cryptography" library provides from_public_bytes() and + from_private_bytes() class methods for Ed25519PublicKey and + Ed25519PrivateKey classes in place of constructors. We extend provide + a single API for those, and make the created objects objects of the + subclass using this mix-in. + """ + # from_private_bytes() and from_public_bytes() both check length (32), + # but do not produce helpful errors if the argument provided it is not + # the right type, so we'll do that here before calling them. + checkformat_byteslike(key_value_in_bytes) + return super().from_public_bytes(key_value_in_bytes) + + +# No.... For now, I'll stick with the raw dictionary representations. +# If function profusion makes it inconvenient for folks to use this library, +# it MAY then be time to make signatures into class objects... but it's +# probably best to avoid that potential complexity and confusion. +# class Signature(): +# def __init__(self, ): +# self.is_gpg_sig = False + + +# ✅ TODO: Consider a schema definitions module, e.g. PyPI project "schema" +def is_hex_string(hex_string: Any) -> bool: + """ + Returns True if hex is a hex string with no uppercase characters, no spaces, + etc. Else, False. + """ + try: + checkformat_hex_string(hex_string) + return True + except (ValueError, TypeError): + return False + + +HexString = str + + +def checkformat_hex_string(hex_string: Any) -> HexString: + """ + Throws TypeError if s is not a string. + Throws ValueError if the given string is not a string of hexadecimal + characters (upper-case not allowed to prevent redundancy). + """ + bytes.fromhex(hex_string) + # isalnum() checks for no whitespace which bytes.fromhex() would allow. + if not hex_string.isalnum() or hex_string.lower() != hex_string: + raise ValueError( + "Expected a hex string; non-hexadecimal or upper-case character found." + ) + + return hex_string + + +def is_hex_signature(hex_signature: Any) -> bool: + """ + Returns True if key is a hex string with no uppercase characters, no + spaces, no '0x' prefix(es), etc., and is 128 hexadecimal characters (the + correct length for an ed25519 signature, 64 bytes of raw data represented + as 128 hexadecimal characters). + Else, returns False. + """ + if is_hex_string(hex_signature) and len(hex_signature) == 128: + return True + + return False + + +def is_hex_key(hex_key: Any) -> bool: + """ + Returns True if key is a hex string with no uppercase characters, no + spaces, no '0x' prefix(es), etc., and is 64 hexadecimal characters (the + correct length for an ed25519 key, 32 bytes of raw data represented as 64 + hexadecimal characters). + Else, returns False. + """ + try: + checkformat_hex_key(hex_key) + return True + except (TypeError, ValueError): + return False + + +def is_signable(signable: Any) -> bool: + """ + Returns True if the given dictionary is a signable dictionary as produced + by wrap_as_signable. Note that there MUST be no additional elements beyond + 'signed' and 'signable' in the dictionary. (The only data in the envelope + outside the signed portion of the data should be the signatures; what's + outside of 'signed' is under attacker control.) + """ + return ( + isinstance(signable, dict) + and set(signable) == {"signatures", "signed"} + and isinstance(signable["signatures"], dict) + and type(signable["signed"]) in SUPPORTED_SERIALIZABLE_TYPES + ) + + +Signable = dict + + +# TODO: ✅ Consolidate: switch to use of this wherever is_a_signable is called +# and then an error is raised if the result is False. +def checkformat_signable(signable: Any) -> Signable: + if not is_signable(signable): + raise TypeError( + "Expected a signable dictionary, but the given argument " + "does not match expectations for a signable dictionary " + '(must be a dictionary containing only keys "signatures" and ' + '"signed", where the value for key "signatures" is a dict ' + 'and the value for key "signed" is a supported serializable ' + "type (" + str(SUPPORTED_SERIALIZABLE_TYPES) + ")" + ) + + return signable + + +class BytesLike(Protocol): + def decode(self, *args, **kwargs) -> str: + ... + + +def checkformat_byteslike(byteslike: Any) -> BytesLike: + if not hasattr(byteslike, "decode"): + raise TypeError("Expected a bytes-like object with a decode method.") + + return byteslike + + +def checkformat_natural_int(natural_int: Any) -> int: # Annotated[int, ">= 1"] + # Technically a TypeError or ValueError, depending, but meh. + if int(natural_int) != natural_int or natural_int < 1: + raise ValueError("Expected an integer >= 1.") + + return natural_int + + +# This is not yet widely used. +# TODO: ✅ See to it that anywhere we're checking for a string, we use this. +def checkformat_string(string: Any) -> str: + if not isinstance(string, str): + raise TypeError("Expecting a string") + + return string + + +def checkformat_expiration_distance(expiration_distance: Any) -> timedelta: + if not isinstance(expiration_distance, timedelta): + raise TypeError( + "Expiration distance must be a datetime.timedelta object. " + "Instead received a " + str(type(expiration_distance)) + ) + + return expiration_distance + + +HexKey = HexString # Annotated[HexString, "len() == 64"] + + +def checkformat_hex_key(hex_key: Any) -> HexKey: + checkformat_hex_string(hex_key) + + if 64 != len(hex_key): + raise ValueError("Expected a 64-character hex string representing a key value.") + + return hex_key + + +def checkformat_list_of_hex_keys(list_of_hex_keys: Any) -> list[HexKey]: + """ + Note that this rejects any list of keys that includes any exact duplicates. + """ + if not isinstance(list_of_hex_keys, list): + raise TypeError( + "Expected a list of 64-character hex strings representing keys." + ) + + for hex_key in list_of_hex_keys: + checkformat_hex_key(hex_key) + + if len(set(list_of_hex_keys)) != len(list_of_hex_keys): + raise ValueError( + "The given list of keys in hex string form contains duplicates. " + "Duplicates are not permitted." + ) + + return list_of_hex_keys + + +def checkformat_utc_isoformat(date_string: Any) -> str: + try: + datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%SZ") + except ValueError: + # ValueError: date_string does not match format '%Y-%m-%dT%H:%M:%SZ' + raise TypeError( + "The provided string appears not to be a datetime string " + "formatted as an ISO8601 UTC-specific datetime (e.g. " + '"1999-12-31T23:59:59Z").' + ) from None + + return date_string + + +def is_gpg_fingerprint(gpg_fingerprint: Any) -> bool: + """ + True if the given value is a hex string of length 40 (representing a + 20-byte SHA-1 value, which is what OpenPGP/GPG uses as a key fingerprint). + """ + try: + checkformat_gpg_fingerprint(gpg_fingerprint) + return True + except (TypeError, ValueError): + return False + + +GPGFingerprint = HexKey # Annotated[HexKey, "len()==40"] + + +def checkformat_gpg_fingerprint(gpg_fingerprint: Any) -> GPGFingerprint: + """ + See is_gpg_fingerprint. Raises a TypeError if is_gpg_fingerprint is not + True. + """ + if len(gpg_fingerprint) != 40: + raise ValueError( + 'The given value, "' + str(gpg_fingerprint) + '", is not a full ' + "GPG fingerprint (40 hex characters)." + ) + + # ⚠️ Yes, the following is a redundant test. Please leave it here in case + # code changes elsewhere. + # Prevent multiple possible representations of keys. There are security + # implications. For example, we cannot permit two signatures from the + # same key -- with the key represented differently -- to count as two + # signatures from distinct keys. + # local hex test. isalnum() checks for no whitespace. + bytes.fromhex(gpg_fingerprint) + if not gpg_fingerprint.isalnum() or gpg_fingerprint.lower() != gpg_fingerprint: + raise ValueError( + "Expected a hex string; non-hexadecimal or upper-case character found." + ) + + return gpg_fingerprint + + +def is_gpg_signature(gpg_signature: Any) -> bool: + # TODO: ✅ docstring based on docstring from checkformat_gpg_signature + + try: + checkformat_gpg_signature(gpg_signature) + return True + except (ValueError, TypeError): + return False + + +GPGSignature = dict + + +def checkformat_gpg_signature(gpg_signature: Any) -> GPGSignature: + """ + Raises a TypeError if the given object is not a dictionary representing a + signature in a format that we expect. + + This is similar to BUT NOT THE SAME AS that produced by + securesystemslib.gpg.functions.create_signature(), conforming to + securesystemslib.formats.GPG_SIGNATURE_SCHEMA. + + We use a slightly different format in order to include the raw ed25519 + public key value. This is the format we expect for Root signatures. + + If the given object matches the format, returns silently. + """ + if not isinstance(gpg_signature, dict): + raise TypeError( + "OpenPGP signatures objects must be dictionaries. Received " + "type " + str(type(gpg_signature)) + " instead." + ) + + if sorted(list(gpg_signature.keys())) not in [ + ["other_headers", "signature"], + ["other_headers", "see_also", "signature"], + ]: + raise ValueError( + 'OpenPGP signature objects must include a "signature" and an ' + '"other_headers" entry, and may include a "see_also" entry. No ' + "other entries are permitted." + ) + + if not is_hex_string(gpg_signature["other_headers"]): + raise ValueError( + '"other_headers" entry in OpenPGP signature object must be a ' "hex string." + ) + # TODO ✅: Determine if we can constrain "other_headers" beyond + # limiting it to a hex string. (No length constraint is + # provided here, for example.) + + if not is_hex_signature(gpg_signature["signature"]): + raise ValueError( + '"signature" entry in OpenPGP signature obj must be a hex ' + "string representing an ed25519 signature, 128 hex characters " + "representing 64 bytes of data." + ) + + if "see_also" in gpg_signature: + checkformat_gpg_fingerprint(gpg_signature["see_also"]) + + return gpg_signature + + +def is_signature(signature: Any) -> bool: + """ + Returns True if signature_obj is a dictionary representing an ed25519 + signature, either in the conda-content-trust normal format, or + the format for a GPG signature. + + See conda_content_trust.common.checkformat_signature() docstring for more details. + """ + try: + checkformat_signature(signature) + return True + except (TypeError, ValueError): + return False + + +Signature = dict + + +def checkformat_signature(signature: Any) -> Signature: + """ + Raises a TypeError if the given object is not a dictionary. + Raises a ValueError if the given object is a dictionary, but is not in + our generalized signature format (supports both raw ed25519 signatures + OpenPGP/GPG signatures). + + If the given object matches the format, returns silently. + + The generalized signature format is: + { + (REQUIRED) 'signature': <64-byte value ed25519 signature, as 128 hex chars>, + (GPG SIGS ONLY) 'other_headers': , + (OPTIONAL) 'see_also': <40-hex-character SHA1 OpenPGP/GPG key identifier, for diagnostic purposes> + } + Examples: + { 'signature': 'deadbeef'*32} # normal ed25519 signature (no OpenPGP) + + { 'signature': 'deadbeef'*32, # OpenPGP ed25519 signature + 'other_headers': 'deadbeef'*??} # extra info OpenPGP insists on signing over + + { 'signature': 'deadbeef'*32, # OpenPGP ed25519 signature + 'other_headers': 'deadbeef'*??, + 'see_also': 'deadbeef'*10}} # listing an OpenPGP key fingerprint + """ + if not isinstance(signature, dict): + raise TypeError("Expected a signature object, of type dict.") + elif not ("signature" in signature and is_hex_signature(signature["signature"])): + # Even the minimal required element is not correct, so... + raise ValueError( + "Expected a dictionary representing an ed25519 signature as a " + "128-character hex string. This requires at least key " + '"signature", with value a 128-character hexadecimal string ' + "representing a (64-byte) ed25519 signature." + ) + + # simple ed25519 signature, not an OpenPGP signature + elif len(signature) == 1: + # If this is a simple ed25519 signature, and not an OpenPGP/GPG + # signature, then we're all set, since 'signature' is included and + # has a reasonable value. + return signature + + # Permit an OpenPGP (GPG / RFC 4880) signature noted as defined in + # function is_gpg_signature. + elif is_gpg_signature(signature): + return signature + + else: + raise ValueError( + "Provided signature does not have the correct format for a " + "signature object (neither simple ed25519 sig nor OpenPGP " + "ed25519 sig)." + ) + + +Delegation = dict + + +def checkformat_delegation(delegation: Any) -> Delegation: + """ + A dictionary specifying public key values and threshold of keys + e.g. + { 'pubkeys': ['ff'*32, '1e'*32], + 'threshold': 1} + threshold must be an integer >= 1. pubkeys must be a list of hexadecimal + representations of ed25519 public keys. + + Note that because drafts are allowed, we do not demand here that the list + of pubkeys include enough keys to meet threshold. Not listing pubkeys yet + is okay during writing, but when verifying metadata, one should not accept + delegations with impossible-to-meet requirements (len(pubkeys) < threshold) + """ + if not isinstance(delegation, dict): + raise TypeError( + "Delegation information must be a dictionary specifying " + '"pubkeys" and "threshold" elements.' + ) + elif not ( + set(delegation) == {"threshold", "pubkeys"} + and delegation["threshold"] >= 1 + and isinstance(delegation["pubkeys"], list) + and all([is_hex_key(k) for k in delegation["pubkeys"]]) + ): + raise ValueError( + "Delegation information must be a dictionary specifying " + 'exactly two elements: "pubkeys" (assigned a list of ' + "64-character hex strings representing individual ed25519 " + 'public keys) and "threshold", assigned an integer >= 1.' + ) + + # We have the right type, and the right keys. Check the values. + checkformat_list_of_hex_keys(delegation["pubkeys"]) + checkformat_natural_int(delegation["threshold"]) + + return delegation + + +def checkformat_delegations(delegations: Any) -> dict[str, Delegation]: + """ + A dictionary specifying a delegation for any number of role names. + Index: rolename. Value: delegation (see checkformat_delegation). + e.g. + { 'root.json': + {'pubkeys': ['01'*32, '02'*32, '03'*32], # each is a lower-case hex string w/ length 64 + 'threshold': 2}, # integer >= 1 + 'channeler.json': + {'pubkeys': ['04'*32], 'threshold': 1}} + """ + if not isinstance(delegations, dict): + raise TypeError( + '"Delegations" information must be a dictionary indexed by ' + "role names, with values equal to dictionaries that each " + 'specify elements "pubkeys" and "threshold".' + ) + + for index in delegations: + checkformat_string(index) + checkformat_delegation(delegations[index]) + + return delegations + + +DelegatingMetadata = Signable + + +def checkformat_delegating_metadata(metadata: Any) -> DelegatingMetadata: + """ + Validates argument "metadata" as delegating metadata. Passes if it is, + raises a TypeError or ValueError if it is not. + + The required format is a dictionary containing all contents of a delegating + metadata file, like root.json or key_mgr.json. (This includes both the + signatures portion and the signed contents portion, in the usual envelope + -- see also checkformat_signable.) + + The required structure: + { + 'signatures': {}, # for each entry in the 'signatures' dict: + # - the key must pass checkformat_hex_key + # - the value must pass checkformat_signature() + # or checkformat_gpg_signature() + 'signed': { + 'type': : # must match a string in SUPPORTED_DELEGATING_METADATA_TYPES (e.g. 'root') + 'metadata_spec_version': , + 'delegations': {}, # value must pass checkformat_delegations() + 'expiration': , # date must pass checkformat_utc_isoformat() + + # The 'signed' dict must always include either a 'timestamp' entry, + # a 'version' entry, or both. Further, in root metadata the + # 'signed' dict must always include a 'version' entry (to support + # root chaining). + + 'timestamp': , # if included, must pass checkformat_utc_isoformat() + 'version': # if included, must pass checkformat_natural_int(), i.e. be an integer >= 1 + } + } + + e.g. + { + "signatures": { # 0 or more signatures over the signed contents + : { + "other_headers": "04001608001d162104f075dd2f6f4cb3bd76134bbb81b6ca16ef9cd58905025f0bf546", + "signature": "ab3e03385f757da74e08b46f1bf82709fbc2ce21823c28e2f0e3452415e2a9f1e2c82e418cc44e2908618cf0c7375f32fe0a5a75494909a59a82875ebc703c02", + }, + ... + }, + "signed": { # signed contents + "delegations": { + "key_mgr.json": { + "pubkeys": [ + "013ddd714962866d12ba5bae273f14d48c89cf0773dee2dbf6d4561e521c83f7" + ], + "threshold": 1 + }, + "root.json": { + "pubkeys": [ + "bfbeb6554fca9558da7aa05c5e9952b7a1aa3995dede93f3bb89f0abecc7dc07" + ], + "threshold": 1 + } + }, + "expiration": "2021-07-13T05:46:45Z", + "metadata_spec_version": "0.1.0", + "timestamp": "2020-07-13T05:46:45Z", + "type": "root", + "version": 1 + } + } + """ + # Signing envelope required + checkformat_signable(metadata) + + for k in metadata["signatures"]: + checkformat_any_signature(metadata["signatures"][k]) + + contents = metadata["signed"] + + for entry in [ # required fields + "type", + "metadata_spec_version", + "delegations", + "expiration", + ]: + if entry not in contents: + raise ValueError( + 'Expected a "' + str(entry) + '" entry in the given ' + "delegating metadata." + ) + + checkformat_string(contents["type"]) + if contents["type"] not in SUPPORTED_DELEGATING_METADATA_TYPES: + raise ValueError( + 'Given type entry ("' + contents["type"] + '") is not ' + "one of the supported types of delegating metadata." + ) + + checkformat_string(contents["metadata_spec_version"]) + # TODO ✅⚠️: For metadata_spec_version, add semantic versioning checks: + # - check format + # - check for compatibility with common.SECURITY_METADATA_SPEC_VERSION + + checkformat_delegations(contents["delegations"]) + + checkformat_utc_isoformat(contents["expiration"]) + + # Timestamp and/or Version: + if "timestamp" not in contents and "version" not in contents: + raise ValueError( + 'All metadata must include a "version" entry, or a ' + '"timestamp" entry, or both.' + ) + + if contents["type"] == "root" and "version" not in contents: + raise ValueError("Root metadata must specify its version number.") + # Catch a possible future coding error at the PR stage, here where the + # assumption is being made. + assert "root" in SUPPORTED_DELEGATING_METADATA_TYPES + + if "timestamp" in contents: + checkformat_utc_isoformat(contents["timestamp"]) + if "version" in contents: # optional field for non-root metadata + checkformat_natural_int(contents["version"]) + # TODO ✅: Ensure that expiration > timestamp, to help people not shoot + # themselves in the foot. + + +def checkformat_any_signature(signature: Any) -> Signature | GPGSignature: + if not is_signature(signature) and not is_gpg_signature(signature): + raise ValueError( + "Expected either a hex string representing a raw ed25519 " + "signature (see checkformat_signature) or a dictionary " + "representing an OpenPGP/GPG signature " + "(see checkformat_gpg_signature)." + ) + + return signature + + +def keyfiles_to_bytes(name): + """ + Toy function. Import an ed25519 key pair, in the forms of raw public and + raw private keys, from name.pub and name.pri respectively. + + Cavalier about private key bytes. + Does not perform input validation ('/'...). + + Return the 32 bytes of the private key object and the 32 bytes of the + public key object, in that order. + """ + with open(name + ".pri", "rb") as fobj: + private_bytes = fobj.read() + + with open(name + ".pub", "rb") as fobj: + public_bytes = fobj.read() + + return private_bytes, public_bytes + + +def keyfiles_to_keys(name): + """ + Doesn't perform input validation. + Import an ed25519 key pair, in the forms of raw public key + bytes and raw private key bytes, from name.pub and name.pri respectively. + Cavalier about private key bytes. + Return a private key object and public key object, in that order. + """ + private_bytes, public_bytes = keyfiles_to_bytes(name) + + private = PrivateKey.from_bytes(private_bytes) + public = PublicKey.from_bytes(public_bytes) + + return private, public + + +def checkformat_key(key: Any) -> ed25519.Ed25519PublicKey | ed25519.Ed25519PrivateKey: + """ + Enforces expectation that argument is an object of type + cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey or + cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey. + """ + if not isinstance(key, (ed25519.Ed25519PublicKey, ed25519.Ed25519PrivateKey)): + raise TypeError( + "Expected an Ed25519PublicKey or Ed25519PrivateKey object " + 'from the "cryptography" library. Received object of type ' + + str(type(key)) + + " instead." + ) + + return key + + +def iso8601_time_plus_delta(delta): + """ + Applies a datetime.timedelta to the current time in UTC with microseconds + stripped, then converts to ISO8601 format and appends a 'Z' indicating that + it is UTC time, not local time. We only deal with UTC times! + + This is used for two purposes: + - get current time in ISO8601 format, by passing in a 0 timedelta + - get ISO8601 UTC timestamp for expiration dates + + regex for time: '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$' + """ + checkformat_expiration_distance(delta) + + unix_expiry = datetime.utcnow().replace(microsecond=0) + delta + + return unix_expiry.isoformat() + "Z" diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/metadata_construction.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/metadata_construction.py new file mode 100644 index 0000000000000000000000000000000000000000..b6ac50be43efe49b1a1ba8ca424575c7b2a20fa6 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/metadata_construction.py @@ -0,0 +1,277 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This module contains functions that construct metadata and generate signing +keys. + +Function Manifest for this Module + +Key Creation: + gen_keys + gen_and_write_keys + +Metadata Construction: + build_delegating_metadata + build_root_metadata (wraps build_delegating_metadata) +""" +from datetime import timedelta + +from .common import ( + SECURITY_METADATA_SPEC_VERSION, + PrivateKey, + PublicKey, + checkformat_delegations, + checkformat_natural_int, + checkformat_string, + checkformat_utc_isoformat, + iso8601_time_plus_delta, +) + +# Default expiration distance for repodata_verify.json. +REPODATA_VERIF_MD_EXPIRY_DISTANCE = timedelta(days=31) +ROOT_MD_EXPIRY_DISTANCE = timedelta(days=365) + + +def build_delegating_metadata( + metadata_type, delegations=None, version=1, timestamp=None, expiration=None +): + """ + # ✅ TODO: Docstring + + Builds delegating metadata, e.g. root.json, key_mgr.json. + + See metadata specification at: + anaconda.atlassian.net/wiki/spaces/AD/pages/285147281/Conda+Security+Metadata+Specification + + Arguments: + metadata_type: + The type of this metadata (e.g. root or key_mgr). This should + match the intended filename (without .json) + + delegations (default {} ) + a dictionary defining the delegations this metadata makes. + Each key is the role delegated to, with the value equal to a + dictionary listing the acceptable public keys and threshold + (number of signatures from distinct acceptable public keys) for the + delegated role. e.g. + { 'root.json': + {'pubkeys': ['01'*32, '02'*32, '03'*32], 'threshold': 2}, + 'key_mgr.json': + {'pubkeys': ['04'*32], 'threshold': 1}} + + If not provided, an empty dictionary (no delegations) will be used. + + version (default 1) + the version of the metadata; root metadata must advance one version + at a time (root chaining). For other types of metadata, versions + are advisory. + + timestamp (default: current system time) + UTC time associated with the production of this metadata, in + ISO8601 format (e.g. '2020-10-31T14:45:19Z') + + expiration (default: current system time plus ROOT_MD_EXPIRY_DISTANCE) + UTC time beyond which this metadata should be considered expired + and not verifiable by any client seeking new metadata + """ + + # Handle optional args + if delegations is None: + delegations = {} + if timestamp is None: + timestamp = iso8601_time_plus_delta(timedelta(0)) # now plus 0 + if expiration is None: + expiration = iso8601_time_plus_delta(ROOT_MD_EXPIRY_DISTANCE) + + # Argument validation. Note that this (checkformat_delegations) also + # checks for duplicates in lists of keys, which is important to reduce the + # odds of a developer introducing certain bugs that cause security issues + # (multiple signatures from same key being treated as two unique sigs, + # etc.) + checkformat_string(metadata_type) + # TODO: ✅⚠️ Consider a set of acceptable metadata types (root, key_mgr, + # channel_authority). Have to be careful about backward + # compatibility, though.... + checkformat_utc_isoformat(timestamp) + checkformat_utc_isoformat(expiration) + checkformat_natural_int(version) + checkformat_delegations(delegations) + + md = { + "type": metadata_type, + "version": version, + "metadata_spec_version": SECURITY_METADATA_SPEC_VERSION, + "timestamp": timestamp, + "expiration": expiration, + "delegations": delegations, + } + + # # This very redundant, but might be useful as defensive code. + # checkformat_delegating_metadata(wrap_as_signable(md) + + return md + + +def build_root_metadata( + root_version, + root_pubkeys, + root_threshold, + key_mgr_pubkeys, + key_mgr_threshold, + root_timestamp=None, + root_expiration=None, +): + """ + Wrapper for build_delegating_metadata(). Helpfully requires root to list + itself and key_mgr in its delegations. + + # ✅ TODO: Docstring + + # ✅ TODO: Expand build_root_metadata flexibility for + # directly-root-delegated roles (i.e. in addition to channeler). + """ + + # Note that argument validation is performed in the + # build_delegation_metadata call below. So is some of the optional + # argument default setting (timestamp). We set expiration explicitly here + # in case the defaults for generic delegating metadata and root metadata + # diverge later. + # Note that it is probably best to provide less revealing timestamps for + # root metadata generation (00:00:00 of a past day), since it is a manual + # process and patterns in that information might be somewhat useful to a + # sophisticated attacker. + if root_expiration is None: + root_expiration = iso8601_time_plus_delta(ROOT_MD_EXPIRY_DISTANCE) + # if channeler_pubkeys is None: + # channeler_pubkeys = [] + # if channeler_threshold = None: + # channeler_threshold = max(1, len(channeler_pubkeys)) + + delegations = { + "root": {"pubkeys": root_pubkeys, "threshold": root_threshold}, + "key_mgr": {"pubkeys": key_mgr_pubkeys, "threshold": key_mgr_threshold}, + } + + root_md = build_delegating_metadata( + metadata_type="root", + delegations=delegations, + version=root_version, + timestamp=root_timestamp, + expiration=root_expiration, + ) + + return root_md + + +def gen_and_write_keys(fname): + """ + Generate an ed25519 key pair, then write the key files to disk. + + Given fname, write the private key to fname.pri, and the public key to + fname.pub. Performs no filename validation, etc. Also returns the private + key object and the public key object, in that order. + """ + + # Create an ed25519 key pair, employing OS random generation. + # Note that this just has the private key sitting around. In the real + # implementation, we'll want to use an HSM equipped with an ed25519 key. + private, public = gen_keys() + + # Write the actual bytes of the key values to disk as requested. + # Note that where the private key is concerned, we're just grabbing the + # not-encrypted private key value. + with open(fname + ".pri", "wb") as fobj: + fobj.write(PrivateKey.to_bytes(private)) + with open(fname + ".pub", "wb") as fobj: + fobj.write(PublicKey.to_bytes(public)) + + return private, public + + +def gen_keys(): + """ + Generate an ed25519 key pair and return it (private key, public key). + + Returns two objects: + - a conda_content_trust.common.PrivateKey, a subclass of + cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey + - a conda_content_trust.common.PublicKey, a subclass of + cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey + """ + # Create an ed25519 key pair, employing OS random generation. + # Note that this just has the private key sitting around. In the real + # implementation, we'll want to use an HSM equipped with an ed25519 key. + private = PrivateKey.generate() + public = private.public_key() + + return private, public + + +# This function is not in use. It's here for reference, in case it's useful +# again in the future. +# def build_repodata_verification_metadata( +# repodata_hashmap, channel=None, expiry=None, timestamp=None): +# """ +# # TODO: ✅ Full docstring. + +# # TODO: ✅ Contemplate the addition of "version" to this metadata. As yet, +# # the timestamp serves our purposes.... + +# Note that if expiry or timestamp are not provided or left as None, now is +# used for the timestamp, and expiry is produced using a default expiration +# distance, via iso8601_time_plus_delta(). (It does not mean no expiration!) + +# Channel may be optionally specified, and is only included if specified. + +# Sample input (repodata_hashmap): +# { +# "noarch/current_repodata.json": "908724926552827ab58dfc0bccba92426cec9f1f483883da3ff0d8664e18c0fe", +# "noarch/repodata.json": "...", +# "noarch/repodata_from_packages.json": "...", +# "osx-64/current_repodata.json": "...", +# "osx-64/repodata.json": "...", +# "osx-64/repodata_from_packages.json": "..." +# } + +# Sample output: +# See metadata specification (version defined by +# SECURITY_METADATA_SPEC_VERSION) for definition and samples of type +# "Repodata Verification Metadata". +# """ + +# if expiry is None: +# expiry = iso8601_time_plus_delta(REPODATA_VERIF_MD_EXPIRY_DISTANCE) + +# if timestamp is None: +# timestamp = iso8601_time_plus_delta(timedelta(0)) + +# # TODO: ✅ More argument validation: channel, +# checkformat_utc_isoformat(expiry) +# checkformat_utc_isoformat(timestamp) +# if not ( # dict with string keys and 32-byte-hash-as-hex-string values +# isinstance(repodata_hashmap, dict) +# and all([isinstance(x, string_types) for x in repodata_hashmap]) +# and all([is_hex_hash(repodata_hashmap[x]) for x in repodata_hashmap])): +# raise ValueError( +# 'Argument repodata_hashmap must be a dictionary with strings ' +# 'as keys (filenames of repodata.json files), and values that ' +# 'are 64-character hex strings representing 32-byte hashes (of ' +# 'those repodata.json files)') + +# # TODO: ✅ Really have to make TypeError and ValueError usages consistent +# # with norms throughout this codebase. + + +# rd_v_md = { +# 'type': 'repodata_verify', +# # (Take advantage of iso8601_time_plus_delta() to get current time +# # in the ISO8601 UTC format we want.) +# 'timestamp': timestamp, # version->timestamp in spec v 0.0.5 +# 'metadata_spec_version': SECURITY_METADATA_SPEC_VERSION, +# 'expiration': expiry, +# 'secured_files': repodata_hashmap} + +# if channel is not None: +# rd_v_md['channel'] = channel + +# return rd_v_md diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/plugin.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..4c87162bfcbad518cc9d1dc8404acc48316e5a37 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/plugin.py @@ -0,0 +1,14 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +import conda.plugins + +from .cli import cli + + +@conda.plugins.hookimpl +def conda_subcommands(): + yield conda.plugins.CondaSubcommand( + name="content-trust", + summary="Signing and verification tools for Conda", + action=cli, + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/root_signing.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/root_signing.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d3dae53d75a05c85105a86d06d3ef6d34f5596 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/root_signing.py @@ -0,0 +1,365 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This module contains functions that sign data in an OpenPGP-compliant (i.e. +GPG-friendly) way. Root metadata may be signed in this manner. Functions that +perform simpler, direct signing using raw ed25519 keys are provided in +conda_content_trust.signing instead. + +This library takes advantage of the securesystemslib library for its gpg +signing interface. + +Function Manifest for this Module: + sign_via_gpg # requires securesystemslib + sign_root_metadata_via_gpg # requires securesystemslib + fetch_keyval_from_gpg # requires securesystemslib + +Note that there is a function in conda_content_trust.authentication that verifies these +signatures without requiring securesystemslib. +""" +# securesystemslib is an optional dependency, and required only for signing +# root metadata via GPG. Verification of those signatures, and signing other +# metadata with raw ed25519 signatures, does not require securesystemslib. +try: + import securesystemslib.formats # noqa: F401 + from securesystemslib.gpg import functions as gpg_funcs + + SSLIB_AVAILABLE = True +except ImportError: # pragma: no cover + SSLIB_AVAILABLE = False + +from .common import ( + canonserialize, + checkformat_byteslike, + checkformat_gpg_fingerprint, + checkformat_hex_key, + is_signable, + load_metadata_from_file, + write_metadata_to_file, +) + + +def _check_sslib_available(): + if not SSLIB_AVAILABLE: + raise ImportError( + "The securesystemslib library is required, which appears to be unavailable." + ) + + +def sign_via_gpg(data_to_sign, gpg_key_fingerprint, include_fingerprint=False): + """ + + + This is an alternative to the conda_content_trust.common.PrivateKey.sign() method, for + use with OpenPGP keys, allowing us to use protected keys in YubiKeys + (which provide an OpenPGP interface) to sign data. + + The signature is not simply over data_to_sign, as is the case with the + PrivateKey.sign() function, but over an expanded payload with + metadata about the signature to be signed, as specified by the OpenPGP + standard (RFC 4880). See data_to_sign and Security Note below. + + This process is nominally deterministic, but varies with the precise + time, since there is a timestamp added by GPG into the signed payload. + Nonetheless, this process does not depend at any point on the ability + to generate random data (unlike key generation). + + This function requires securesystemslib, which is otherwise an optional + dependency. + + + + data_to_sign + The raw bytes of interest that will be signed by GPG. Note that + pursuant to the OpenPGP standard, GPG will add to this data: + specifically, it includes metadata about the signature that is + about to be made into the data that will be signed. We do not care + about that metadata, and we do not want to burden signature + verification with its processing, so we essentially ignore it. + This should have negligible security impact, but for more + information, see "A note on security" below. + + + gpg_key_fingerprint + This is a (fairly) unique identifier for an OpenPGP key pair. + Also Known as a "long" GPG keyid, a GPG fingerprint is + 40-hex-character string representing 20 bytes of raw data, the + SHA-1 hash of a collection of the GPG key's properties. + Internally, GPG uses the key fingerprint to identify keys the + client knows of. + + Note that an OpenPGP public key is a larger object identified by a + fingerprint. GPG public keys include two things, from our + perspective: + + - the raw bytes of the actual cryptographic key + (in our case the 32-byte value referred to as "q" for an ed25519 + public key) + + - lots of data that is totally extraneous to us, including a + timestamp, some representations of relationships with other keys + (subkeys, signed-by lists, etc.), Superman's real name + (see also https://bit.ly/38GcaGj), potential key revocations, + etc. + We do not care about this extra data because we are using the + OpenPGP standard not for its key-to-key semantics or any element + of its Public Key Infrastructure features (revocation, vouching + for other keys, key relationships, etc.), but simply as a means + of asking YubiKeys to sign data for us, with ed25519 keys whose + raw public key value ("q") we know to expect. + + + + Returns a dictionary representing a GPG signature. This is similar to + but not *quite* the same as + securesystemslib.formats.GPG_SIGNATURE_SCHEMA (which uses 'keyid' + as the key for the fingerprint, instead of 'gpg_key_fingerprint'). + + Specifically, this looks like: + {'gpg_key_fingerprint': , + 'other_headers': , + 'signature': } + + + This is unlike conda_content_trust.signing.sign(), which simply returns 64 bytes of raw + ed25519 signature. + + + + + A note on the security implications of this treatment of OpenPGP + signatures: + + TL;DR: + It is NOT easier for an attacker to find a collision; however, it + IS easier, IF an attacker CAN find a collision, to do so in a way + that presents a specific, arbitrary payload. + + Note that pursuant to the OpenPGP standard, GPG will add to the data we + ask it to sign (data_to_sign) before signing it. Specifically, GPG will + add, to the payload-to-be-signed, OpenPGP metadata about the signature + it is about to create. We do not care about that metadata, and we do + not want to burden signature verification with its processing (that is, + we do not want to use GPG to verify these signatures; conda will do + that with simpler code). As a result, we will ignore this data when + parsing the signed payload. This will mean that there will be many + different messages that have the same meaning to us: + + signed: + + + + Since we will not be processing the '123456...' above, '654321...' + would have the same effect: as long as the signature is verified, + we don't care what's in that portion of the payload. + + Since there are many, many payloads that mean the same thing to us, an + attacker has a vast space of options all with the same meaning to us in + which to search for (effectively) a useful SHA256 hash collision to + find different data that says something *specific* and still + *succeeds* in signature verification using the same signature. + While that is not ideal, it is difficult enough simply to find a SHA256 + collision that this is acceptable. + """ + _check_sslib_available() + + # Argument validation + checkformat_gpg_fingerprint(gpg_key_fingerprint) + checkformat_byteslike(data_to_sign) + + sig = gpg_funcs.create_signature(data_to_sign, gpg_key_fingerprint) + + # securesystemslib.gpg makes use of the GPG key fingerprint. We don't + # care about that as much -- we want to use the raw ed25519 public key + # value to refer to the key in a manner consistent with the way we refer to + # non-GPG (non-OpenPGP) keys. + keyval = fetch_keyval_from_gpg(gpg_key_fingerprint) + + # ssl gpg sigs look like this: + # + # {'keyid': , + # 'other_headers': , + # 'signature': } + # + # We want to store the real public key instead of just the gpg key + # fingerprint, so we add that, and we'll rename keyid to + # gpg_key_fingerprint. That gives us: + # + # {'gpg_key_fingerprint': , + # 'other_headers': , + # 'signature': } + + # sig['key'] = keyval # q, the 32-byte raw ed25519 public key value, expressed as 64 hex characters + + # The OpenPGP Fingerprint of the OpenPGP key used to sign. This is not + # required for verification, but it's useful for debugging and for + # root keyholder convenience. So it's optional. + if include_fingerprint: + sig["see_also"] = sig[ + "keyid" + ] # strictly not needed, useful for debugging; 20-byte sha1 gpg key identifier per OpenPGP spec, expressed as 40 hex characters + + del sig["keyid"] + + return sig + + +def sign_root_metadata_dict_via_gpg(root_signable, gpg_key_fingerprint): + # Signs root_signable in place, returns nothing. + + _check_sslib_available() + + # Make sure it's the right format. + if not is_signable(root_signable): + raise TypeError("Expected a signable dictionary.") + + # TODO: Add root-specific checks. + + # Canonicalize and serialize the data, putting it in the form we expect to + # sign over. Note that we'll canonicalize and serialize the whole thing + # again once the signatures have been added. + data_to_sign = canonserialize(root_signable["signed"]) + + sig_dict = sign_via_gpg(data_to_sign, gpg_key_fingerprint) + + # sig_dict looks like this: + # {'keyid': 'f075dd2f6f4cb3bd76134bbb81b6ca16ef9cd589', + # 'other_headers': '04001608001d162104f075dd2f6f4cb3bd76134bbb81b6ca16ef9cd58905025dbc3e68', + # 'signature': '29282a8fe75871f9d4cf10a5a9e8d92303f8c361ce4b474a0ce641c9b8a74e4baaf810cc383af318a8e21cbe252789c2c30894d94e8b0288c3c45ceacf6c1d0c'} + # pgp_pubkey looks like this: + # {'creation_time': 1571411344, + # 'hashes': ['pgp+SHA2'], + # 'keyid': 'f075dd2f6f4cb3bd76134bbb81b6ca16ef9cd589', + # 'keyval': {'private': '', + # 'public': {'q': 'bfbeb6554fca9558da7aa05c5e9952b7a1aa3995dede93f3bb89f0abecc7dc07'}}, + # 'method': 'pgp+eddsa-ed25519', + # 'type': 'eddsa'} + + # securesystemslib.gpg makes use of the GPG key fingerprint. We don't + # care about that as much -- we want to use the raw ed25519 public key + # value to refer to the key in a manner consistent with the way we refer to + # non-GPG (non-OpenPGP) keys. + # raw_pubkey = pgp_pubkey['keyval']['public']['q'] + raw_pubkey = fetch_keyval_from_gpg(gpg_key_fingerprint) + + # non-GPG signing here would look like this: + # signature_as_hexstr = serialize_and_sign(signable['signed'], private_key) + # public_key_as_hexstr = binascii.hexlify(key_to_bytes( + # private_key.public_key())).decode('utf-8') + + # Add signature in-place. + root_signable["signatures"][raw_pubkey] = sig_dict + + return root_signable + + +def sign_root_metadata_via_gpg(root_md_fname, gpg_key_fingerprint): + """ + # This is a higher-level function than sign_via_gpg, including code that + # deals with the filesystem. It is not actually limited to root metadata, + # and SHOULD BE RENAMED. + """ + # Read in json + root_signable = load_metadata_from_file(root_md_fname) + + root_signable = sign_root_metadata_dict_via_gpg(root_signable, gpg_key_fingerprint) + + # TODO: Consider removing write_metadata_to_file. It might be better for + # readers to see the canonserialize() call being made (again) here, + # and it's not that much longer.... + write_metadata_to_file(root_signable, root_md_fname) + + +def fetch_keyval_from_gpg(fingerprint): + """ + Retrieve the underlying 32-byte raw ed25519 public key for a GPG key. + + Given a GPG key fingerprint (40-character hex string), retrieve the GPG + key, parse it, and return "q", the 32-byte ed25519 key value. + + This takes advantage of the GPG key parser in securesystemslib. + + The fingerprint will be stripped of spaces and lowercased, so you can use + the GPG output even if it's in a funky format: + 94A3 EED0 806C 1F10 7754  A446 FDAD 11B8 2DD4 0E8C + 94A3 EED0 806C 1F10 7754 A446 FDAD 11B8 2DD4 0E8C # <-- No, this is actually not the same as the previous one, which uses \\xa0.... + 94A3EED0806C1F107754A446FDAD11B82DD40E8C + 94a3eed0806c1f107754a446fdad11b82dd40e8c + etc. + """ + _check_sslib_available() + + fingerprint = ( + fingerprint.lower().replace(" ", "").replace("\xa0", "") + ) # \xa0 is another space character that GPG sometimes outputs + + checkformat_gpg_fingerprint(fingerprint) + + key_parameters = gpg_funcs.export_pubkey(fingerprint) + + return key_parameters["keyval"]["public"]["q"] + + +def _gpg_pubkey_in_ssl_format(fingerprint, q): + """ + THIS IS PROVIDED ONLY FOR TESTING PURPOSES. + We do not need to convert pubkeys to securesystemslib's format, except to + try out securesystemslib's gpg signature verification (which we use only + for comparison during testing). + + Given a GPG key fingerprint (40 hex characters) and a q value (64 hex + characters representing a 32-byte ed25519 public key raw value), produces a + key object in a format that securesystemslib expects, so that we can use + securesystemslib.gpg.functions.verify_signature for part of the GPG + signature verification. For our purposes, this means that we should + produce a dictionary conforming to + securesystemslib.formats._GPG_ED25519_PUBKEY_SCHEMA. + + If securesystemslib.formats._GPG_ED25519_PUBKEY_SCHEMA changes, those + changes will likely need to be reflected here. + + Example value produced: + { + 'type': 'eddsa', + 'method': 'pgp+eddsa-ed25519', + 'hashes': ['pgp+SHA2'], + 'keyid': 'F075DD2F6F4CB3BD76134BBB81B6CA16EF9CD589', + 'keyval': { + 'public': {'q': 'bfbeb6554fca9558da7aa05c5e9952b7a1aa3995dede93f3bb89f0abecc7dc07'}, + 'private': ''} + } + } + """ + checkformat_gpg_fingerprint(fingerprint) + checkformat_hex_key(q) + + ssl_format_key = { + "type": "eddsa", + "method": securesystemslib.formats.GPG_ED25519_PUBKEY_METHOD_STRING, + "hashes": [securesystemslib.formats.GPG_HASH_ALGORITHM_STRING], + "keyid": fingerprint, + "keyval": {"private": "", "public": {"q": q}}, + } + + return ssl_format_key + + +# def _gpgsig_to_sslgpgsig(gpg_sig): +# +# conda_content_trust.common.checkformat_gpg_signature(gpg_sig) +# +# return { +# 'keyid': copy.deepcopy(gpg_sig['key_fingerprint']), +# 'other_headers': copy.deepcopy(gpg_sig[other_headers]), +# 'signature': copy.deepcopy(gpg_sig['signature'])} + + +# def _sslgpgsig_to_gpgsig(ssl_gpg_sig): +# +# securesystemslib.formats.GPG_SIGNATURE_SCHEMA.check_match(ssl_gpg_sig) +# +# return { +# 'key_fingerprint': copy.deepcopy(ssl_gpg_sig['keyid']), +# 'other_headers': copy.deepcopy(ssl_gpg_sig[other_headers]), +# 'signature': copy.depcopy(ssl_gpg_sig['signature']) +# } diff --git a/miniconda3/lib/python3.13/site-packages/conda_content_trust/signing.py b/miniconda3/lib/python3.13/site-packages/conda_content_trust/signing.py new file mode 100644 index 0000000000000000000000000000000000000000..652ce42949607be1a8677b1545f2cb703013d793 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_content_trust/signing.py @@ -0,0 +1,213 @@ +# Copyright (C) 2019 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +""" +This module contains functions that sign data using ed25519 keys, via the +pyca/cryptography library. Functions that perform OpenPGP-compliant (e.g. GPG) +signing are provided instead in root_signing. + +Function Manifest for this Module: + serialize_and_sign + wrap_as_signable + sign_signable +""" +from binascii import hexlify +from copy import deepcopy + +from .common import ( + SUPPORTED_SERIALIZABLE_TYPES, + PrivateKey, + PublicKey, + canonserialize, + checkformat_hex_key, + checkformat_key, + checkformat_signable, + checkformat_signature, + checkformat_string, + load_metadata_from_file, + write_metadata_to_file, +) + + +def serialize_and_sign(obj, private_key): + """ + Given a JSON-compatible object, does the following: + - serializes the dictionary as utf-8-encoded JSON, lazy-canonicalized + such that any dictionary keys in any dictionaries inside + are sorted and indentation is used and set to 2 spaces (using json lib) + - creates a signature over that serialized result using private_key + - returns that signature as a hex string + + See comments in common.canonserialize() + + Arguments: + obj: a JSON-compatible object -- see common.canonserialize() + private_key: a conda_content_trust.common.PrivateKey object + + # TODO ✅: Consider taking the private key data as a hex string instead? + # On the other hand, it's useful to support an object that could + # obscure the key (or provide an interface to a hardware key). + """ + + # Try converting to a JSON string. + serialized = canonserialize(obj) + + signature_as_bytes = private_key.sign(serialized) + + signature_as_hexstr = hexlify(signature_as_bytes).decode("utf-8") + + return signature_as_hexstr + + +def wrap_as_signable(obj): + """ + Given a JSON-serializable object (dictionary, list, string, numeric, etc.), + returns a wrapped copy of that object: + + {'signatures': {}, + 'signed': } + + Expects strict typing matches (not duck typing), for no good reason. + (Trying JSON serialization repeatedly could be too time consuming.) + + TODO: ✅ Consider whether or not the copy can be shallow instead, for speed. + + Raises ❌TypeError if the given object is not a JSON-serializable type per + SUPPORTED_SERIALIZABLE_TYPES + """ + if not type(obj) in SUPPORTED_SERIALIZABLE_TYPES: + raise TypeError( + "wrap_dict_as_signable requires a JSON-serializable object, " + "but the given argument is of type " + str(type(obj)) + ", " + "which is not supported by the json library functions." + ) + + # TODO: ✅ Later on, consider switching back to TUF-style + # signatures-as-a-list. (Is there some reason it's saner?) + # Going with my sense of what's best now, which is dicts instead. + # It's simpler and it naturally avoids duplicates. We don't do it + # this way in TUF, but we also don't depend on it being an ordered + # list anyway, so a dictionary is probably better. + + return {"signatures": {}, "signed": deepcopy(obj)} + + +def sign_signable(signable, private_key): + """ + Given a JSON-compatible signable dictionary (as produced by calling + wrap_dict_as_signable with a JSON-compatible dictionary), calls + serialize_and_sign on the enclosed dictionary at signable['signed'], + producing a signature, and places the signature in + signable['signatures'], in an entry indexed by the public key + corresponding to the given private_key. + + Updates the given signable in place, returning nothing. + Overwrites if there is already an existing signature by the given key. + + # TODO ✅: Take hex string keys for sign_signable and serialize_and_sign + # instead of constructed PrivateKey objects? Add the comment + # below if so: + # # Unlike with lower-level functions, both signatures and public keys are + # # always written as hex strings. + + Raises ❌TypeError if the given object is not a JSON-serializable type per + SUPPORTED_SERIALIZABLE_TYPES + """ + # Argument checking + checkformat_key(private_key) + checkformat_signable(signable) + # if not is_a_signable(signable): + # raise TypeError( + # 'Expected a signable dictionary; the given argument of type ' + + # str(type(signable)) + ' failed the check.') + + # private_key = PrivateKey.from_hex(private_key_hex) + + signature_as_hexstr = serialize_and_sign(signable["signed"], private_key) + + public_key_as_hexstr = PublicKey.to_hex(private_key.public_key()) + + # To fit a general format, we wrap it this way, instead of just using the + # hexstring. This is because OpenPGP signatures that we use for root + # signatures look similar and have a few extra fields beyond the signature + # value itself. + signature_dict = {"signature": signature_as_hexstr} + + checkformat_signature(signature_dict) + + # TODO: ✅⚠️ Log a warning in whatever conda's style is (or conda-build): + # + # if public_key_as_hexstr in signable['signatures']: + # warn( # replace: log, 'warnings' module, print statement, whatever + # 'Overwriting existing signature by the same key on given ' + # 'signable. Public key: ' + public_key + '.') + + # Add signature in-place, in the usual signature format. + signable["signatures"][public_key_as_hexstr] = signature_dict + + +def sign_all_in_repodata(fname, private_key_hex): + """ + Given a repodata.json filename, reads the "packages" entries in that file, + and produces a signature over each artifact, with the given key. The + signatures are then placed in a "signatures" entry parallel to the + "packages" entry in the json file. The file is overwritten. + + Arguments: + fname: filename of a repodata.json file + private_key_hex: + a private ed25519 key value represented as a 64-char hex string + """ + checkformat_hex_key(private_key_hex) + checkformat_string(fname) + # TODO ✅⚠️: Consider filename validation. What does conda use for that? + + private = PrivateKey.from_hex(private_key_hex) + public_hex = PublicKey.to_hex(private.public_key()) + + # Loading the whole file at once instead of reading it as we go, because + # it's less complex and this only needs to run repository-side. + repodata = load_metadata_from_file(fname) + # with open(fname, 'rb') as fobj: + # repodata = json.load(fname) + + # TODO ✅: Consider more validation for the gross structure expected of + # repodata.json + if "packages" not in repodata: + raise ValueError('Expected a "packages" entry in given repodata file.') + + # Add an empty 'signatures' dict to repodata. + # If it's already there for whatever reason, we replace it entirely. This + # avoids leaving existing signatures that might not get replaced -- e.g. if + # the artifact is not in the "packages" dict, but is in the "signatures" + # dict for some reason. What comes out of this process will be limited to + # what we sign in this function. + repodata["signatures"] = {} + + for artifact_name, metadata in repodata["packages"].items(): + # TODO ✅: Further consider the significance of the artifact name + # itself not being part of the signed metadata. The info used + # to generate the name (package name + version + build) is + # part of the signed metadata, but the full name is not. + # Keep in mind attacks that swap metadata among artifacts; + # signatures would still read as correct in that circumstance. + signature_hex = serialize_and_sign(metadata, private) + + # To fit a general format, we wrap it this way, instead of just using + # the hexstring. This is because OpenPGP signatures that we use for + # root signatures look similar and have a few extra fields beyond the + # signature value itself. + signature_dict = {"signature": signature_hex} + + checkformat_signature(signature_dict) + + repodata["signatures"][artifact_name] = {public_hex: signature_dict} + + # Repeat for the .conda packages in 'packages.conda'. + for artifact_name, metadata in repodata.get("packages.conda", {}).items(): + signature_hex = serialize_and_sign(metadata, private) + repodata["signatures"][artifact_name] = { + public_hex: {"signature": signature_hex} + } + + # Note: takes >0.5s on a macbook for large files + write_metadata_to_file(repodata, fname) diff --git a/miniconda3/lib/python3.13/site-packages/conda_env/README.md b/miniconda3/lib/python3.13/site-packages/conda_env/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eabe15a8365bc305c14411caf7d18cef4b4391de --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_env/README.md @@ -0,0 +1,90 @@ +# conda-env + +Provides the `conda env` interface to Conda environments. + +## Installing + +`conda env` is included in `conda` itself. + +## Usage + +All of the usage is documented via the `--help` flag. + +```bash +$ conda env --help +usage: conda-env [-h] {create,export,list,remove,update,config} ... + +positional arguments: + {create,export,list,remove,update,config} + create Create an environment based on an environment file + export Export a given environment + list List the Conda environments + remove Remove an environment + update Update the current environment based on environment file + config Configure a conda environment + +optional arguments: + -h, --help Show this help message and exit. +``` + + +## `environment.yml` + +conda-env allows creating environments using the `environment.yml` +specification file. This allows you to specify a name, channels to use when +creating the environment, and the dependencies. For example, to create an +environment named `stats` with numpy and pandas, create an `environment.yml` +file with this as the contents: + +```yaml +name: stats +dependencies: + - numpy + - pandas +``` + +Then run this from the command line: + +```bash +$ conda env create +Fetching package metadata: ... +Solving package specifications: .Linking packages ... +[ COMPLETE ] |#################################################| 100% +# +# To activate this environment, use: +# $ conda activate stats +# +# To deactivate this environment, use: +# $ conda deactivate +# +``` + +Your output might vary a little bit, depending on whether you have the packages +in your local package cache. + +You can explicitly provide an environment spec file using `-f` or `--file` +and the name of the file you would like to use. + +The default channels can be excluded by adding `nodefaults` to the list of +channels. This is equivalent to passing the `--override-channels` option +to most `conda` commands, and is like `defaults` in the `.condarc` +channel configuration but with the reverse logic. + +## Environment file example + +```yaml +name: stats +channels: + - javascript +dependencies: + - python=3.4 # or 2.7 if you are feeling nostalgic + - bokeh=0.9.2 + - numpy=1.9.* + - nodejs=0.10.* + - flask + - pip + - pip: + - Flask-Testing +``` + +**Recommendation:** Always create your `environment.yml` file by hand. diff --git a/miniconda3/lib/python3.13/site-packages/conda_env/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4bdaacf082c9ba5a0d0b8c285c4776f423b354e0 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_env/__init__.py @@ -0,0 +1,6 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from conda import __version__ # noqa: F401 +from conda.deprecations import deprecated + +deprecated.module("25.9", "26.3") diff --git a/miniconda3/lib/python3.13/site-packages/conda_env/cli/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_env/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..257be2505e2176a8a934a36dfca503610426787f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_env/cli/__init__.py @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from conda.deprecations import deprecated + +deprecated.module("25.9", "26.3") diff --git a/miniconda3/lib/python3.13/site-packages/conda_env/installers/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_env/installers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..257be2505e2176a8a934a36dfca503610426787f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_env/installers/__init__.py @@ -0,0 +1,5 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +from conda.deprecations import deprecated + +deprecated.module("25.9", "26.3") diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..658a7637871919fad01ae60e30c42bc9cc4fa2ab --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/METADATA @@ -0,0 +1,85 @@ +Metadata-Version: 2.4 +Name: conda-libmamba-solver +Version: 25.11.0 +Summary: The fast mamba solver, now in conda +Project-URL: homepage, https://github.com/conda/conda-libmamba-solver +Author-email: "Anaconda, Inc." +License: BSD 3-Clause License + + Copyright (c) 2022, Anaconda, Inc. + Copyright (c) 2023, conda + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * 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 NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + --- + + This work also includes code borrowed from mamba.utils v0.19, licensed as BSD 3-Clause +License-File: AUTHORS.md +License-File: LICENSE +Classifier: License :: OSI Approved :: BSD License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.10 +Requires-Dist: boltons>=23.0.0 +Requires-Dist: conda>=25.9 +Requires-Dist: msgpack>=1.1.1 +Requires-Dist: requests<3,>=2.28.0 +Requires-Dist: zstandard>=0.15 +Description-Content-Type: text/markdown + +# conda-libmamba-solver + +The fast mamba solver, now in conda! + +## What is this exactly? + +conda-libmamba-solver is a new solver for the +[conda package manager](https://docs.conda.io/) which uses the solver from the +[mamba project](https://mamba.readthedocs.io/) behind the scenes, while +carefully implementing conda's functionality and expected behaviors on top. +The library used by mamba to do the heavy-lifting is called [libsolv](https://github.com/openSUSE/libsolv). + +Additional information about the project can be found in the blog post on Anaconda's weblog: +[A Faster Solver for Conda: Libmamba](https://www.anaconda.com/blog/a-faster-conda-for-a-growing-community). + +## Documentation + +Check the [documentation](https://conda.github.io/conda-libmamba-solver/) for +instructions on how to install, use and make the most out the new conda solver! + + +## Build status + +| [![Build status](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml/badge.svg)](https://github.com/conda/conda-libmamba-solver/actions/workflows/tests.yml?query=branch%3Amain) [![Docs status](https://github.com/conda/conda-libmamba-solver/actions/workflows/docs.yml/badge.svg)](https://github.com/conda/conda-libmamba-solver/actions/workflows/docs.yml?query=branch%3Amain) [![codecov](https://codecov.io/gh/conda/conda-libmamba-solver/branch/main/graph/badge.svg)](https://codecov.io/gh/conda/conda-libmamba-solver) [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/conda/conda-libmamba-solver/main.svg)](https://results.pre-commit.ci/latest/github/conda/conda-libmamba-solver/main) [![CalVer version used YY.MM.MICRO](https://img.shields.io/badge/calver-YY.MM.MICRO-22bfda.svg?style=flat-square)](https://calver.org) | [![Anaconda-Server Badge](https://anaconda.org/conda-canary/conda-libmamba-solver/badges/latest_release_date.svg)](https://anaconda.org/conda-canary/conda-libmamba-solver) | +| --- | :-: | +| [`conda install defaults::conda-libmamba-solver`](https://anaconda.org/anaconda/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/anaconda/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/anaconda/conda-libmamba-solver) | +| [`conda install conda-forge::conda-libmamba-solver`](https://anaconda.org/conda-forge/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/conda-forge/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/conda-forge/conda-libmamba-solver) | +| [`conda install conda-canary/label/dev::conda-libmamba-solver`](https://anaconda.org/conda-canary/conda-libmamba-solver) | [![Anaconda-Server Badge](https://anaconda.org/conda-canary/conda-libmamba-solver/badges/version.svg)](https://anaconda.org/conda-canary/conda-libmamba-solver) | diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..e3c3f9d776e094e2d73e75d07a67c378c33804bc --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/RECORD @@ -0,0 +1,37 @@ +conda_libmamba_solver-25.11.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda_libmamba_solver-25.11.0.dist-info/METADATA,sha256=o_oBj8RWJpOCXYes0y_xHvd0ah1I0_yWpKtS5297cQw,5662 +conda_libmamba_solver-25.11.0.dist-info/RECORD,, +conda_libmamba_solver-25.11.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_libmamba_solver-25.11.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +conda_libmamba_solver-25.11.0.dist-info/direct_url.json,sha256=rNWoGbk7ksTJ2DfIZjsYd-dXx8QUlaoMivpQcp2YVPU,103 +conda_libmamba_solver-25.11.0.dist-info/entry_points.txt,sha256=JHAxZa0f1SAUCgVquOdUUOGqSRcMyz3rkpiXL1Ploc8,61 +conda_libmamba_solver-25.11.0.dist-info/licenses/AUTHORS.md,sha256=_NosLCcbDN9KQZSQXyQmP-0kWKdoxEHt3K3OdocuyuE,460 +conda_libmamba_solver-25.11.0.dist-info/licenses/LICENSE,sha256=s5c3lMy_FgHDSK7ltL_gNFw7zSHcDcgKOEQbmUBf67A,1663 +conda_libmamba_solver/__init__.py,sha256=Er13Z9pJpQJ1pZna7WBWjS2q-ZWP6MbTRvNbtuE8GVs,564 +conda_libmamba_solver/__pycache__/__init__.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/conda_build_exceptions.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/exceptions.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/index.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/mamba_utils.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/plugin.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/repoquery.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards_cache.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards_subset.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/shards_typing.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/solver.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/state.cpython-314.pyc,, +conda_libmamba_solver/__pycache__/utils.cpython-314.pyc,, +conda_libmamba_solver/conda_build_exceptions.py,sha256=uPc7PKn9IN-V44wEpKeZHZpojiH2hwuQKdBzCfZHEK0,1396 +conda_libmamba_solver/exceptions.py,sha256=AqESkZmhveRKxUfRTo-QSPEWFb1DIeX6W8-wYZ9qhvM,485 +conda_libmamba_solver/index.py,sha256=xTcHO8lr29eRrz_e3qsWlB4lZOLuoDf8LHmaRTRWXLQ,31625 +conda_libmamba_solver/mamba_utils.py,sha256=aWL-IXqPx9akbkk7jgOeJgjhdzYOBZqluEyrR9LJxCE,6879 +conda_libmamba_solver/plugin.py,sha256=_P6NUwil6vTEt5Pp1jm9qkKUmq4qou5vePBdfG_I2AU,1149 +conda_libmamba_solver/repoquery.py,sha256=2IrzDBcfeM6Gq7vN0fkmJN5TKWMM8TvvpdH1dIbhOf8,7610 +conda_libmamba_solver/shards.py,sha256=RK3Caz2e42FHsi-Go8b6eUU1pJMlPE9HwdQ2fVA5xb4,24542 +conda_libmamba_solver/shards_cache.py,sha256=-KR98kr8at8-lAt_w1coRmMfRxCGLo-9BEz-QwJjGTY,5005 +conda_libmamba_solver/shards_subset.py,sha256=EorIgQAD-f9rmnElwY1-D9vDrX8fzIgkeCPvp-DqOok,21890 +conda_libmamba_solver/shards_typing.py,sha256=xxeOQzb9nqk0gN8bJyr0bhM7I30mk3RVpy81fBgSADU,1574 +conda_libmamba_solver/solver.py,sha256=KSk3mNq-PbytZaCSwvrjOz1ezjedAm-LG0NxZH_8mAA,48671 +conda_libmamba_solver/state.py,sha256=BPWt8O706ArlKBtumRuGJNkO3ZNFIzA3j-TcX2PzlRU,33572 +conda_libmamba_solver/utils.py,sha256=QoorafpuqtBbn4YPhmjprAelIsp-2SInA84z0QhztW0,3833 diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..4d30df6a4bee0031fb0524608eb58f4cf9c67a4d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///C:/miniconda3/conda-bld/conda-libmamba-solver_1764245615235/work/src"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..4423474395b8f751cbe687c9fe1d6a598a7ca838 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[conda] +conda-libmamba-solver = conda_libmamba_solver.plugin diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/licenses/AUTHORS.md b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/licenses/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..1ccc2c01627b7c6a4c98d0d48236ae019d6e3bd9 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/licenses/AUTHORS.md @@ -0,0 +1,22 @@ +All of the people who have made at least one contribution to conda-libmamba-solver. +Authors are sorted alphabetically. + +* Agriya Khetarpal +* Albert DeFusco +* Christopher Ostrouchov +* Daniel Holth +* Jaime Rodríguez-Guerra +* Jannis Leidel +* John Kirkham +* Jonathan J. Helmus +* Julien Jerphanion +* Ken Odegard +* Kevin Markham +* Klaus Zimmermann +* Matthew R. Becker +* Stacy Noland +* Thomas Lam +* Travis Hathaway +* conda-bot +* dependabot[bot] +* pre-commit-ci[bot] diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..70fdcd18028fa237ed54c358cf64750ec9bae45e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver-25.11.0.dist-info/licenses/LICENSE @@ -0,0 +1,32 @@ +BSD 3-Clause License + +Copyright (c) 2022, Anaconda, Inc. +Copyright (c) 2023, conda +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * 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 NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--- + +This work also includes code borrowed from mamba.utils v0.19, licensed as BSD 3-Clause diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d02862b91df94a84d4d535adbc2b280ba4f20f40 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/__init__.py @@ -0,0 +1,21 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +try: + from ._version import version as __version__ +except ImportError: + try: + from importlib.metadata import version + + __version__ = version("conda_libmamba_solver") + del version + except ImportError: + __version__ = "0.0.0.unknown" + + +def get_solver_class(key: str = "libmamba"): + if key == "libmamba": + from .solver import LibMambaSolver + + return LibMambaSolver + raise ValueError("Key must be 'libmamba'") diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/conda_build_exceptions.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/conda_build_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..da68fe937adfd5eacaf1e02d74337694ff85c671 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/conda_build_exceptions.py @@ -0,0 +1,46 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +This exception is only used in conda-build, so we can't import it directly. +conda_build is not a dependency, but we only import this when conda-build is calling the +solver, so it's fine to import it here. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable + + from conda.models.match_spec import MatchSpec + +from conda_build.exceptions import DependencyNeedsBuildingError + + +class ExplainedDependencyNeedsBuildingError(DependencyNeedsBuildingError): + """ + We need to subclass this to add the explanation to the error message. + We also add a couple of attributes to make it easier to set up. + """ + + def __init__( + self, + matchspecs: Iterable[MatchSpec] | None = None, + explanation: str | None = None, + *args, + **kwargs, + ): + super().__init__(*args, **kwargs) + self.matchspecs = self.matchspecs or matchspecs or [] + self.explanation = explanation + + def __str__(self) -> str: + msg = self.message + if not self.explanation: + # print simple message in log.warning() calls + return msg + return "\n".join([msg, self.explanation]) diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/exceptions.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..ab72895e345f09b9d09576bd0af68d82079e8c5d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/exceptions.py @@ -0,0 +1,17 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Exceptions used in conda-libmamba-solver +""" + +from conda.exceptions import UnsatisfiableError + + +class LibMambaUnsatisfiableError(UnsatisfiableError): + """An exception to report unsatisfiable dependencies. + The error message is passed directly as a str. + """ + + def __init__(self, message: str, **kwargs): + super(UnsatisfiableError, self).__init__(str(message)) diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/index.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/index.py new file mode 100644 index 0000000000000000000000000000000000000000..fffdc42ce791eb84ac1233dff9a86759679a863d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/index.py @@ -0,0 +1,780 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +This module provides a convenient interface between `libmamba.Solver` +and conda's `PrefixData`. In other words, it allows to expose channels +loaded in `conda` to the `libmamba` machinery without using the +`libmamba` networking stack. + +Internally, the `libmamba`'s index is made of: + +- A 'Pool' object, exposed to libsolv. +- The pool is made of `Repo` objects. +- Each repo corresponds to a repodata.json file. +- Each repodata comes from a channel+subdir combination. + +Some notes about channels +------------------------- + +In a way, conda channels are an abstraction over a collection of +channel subdirs. For example, when the user wants 'conda-forge', it +actually means 'repodata.json' files from the configured platform subdir +and 'noarch'. Some channels are actually 'MultiChannel', which provide +a collection of channels. The most common example is 'defaults', which +includes 'main', 'r' and 'msys2'. + +So, for conda-forge on Linux amd64 we get: + +- https://conda.anaconda.org/conda-forge/linux-64 +- https://conda.anaconda.org/conda-forge/noarch + +For defaults on macOS with Apple Silicon (M1 and friends): + +- https://repo.anaconda.org/main/osx-arm64 +- https://repo.anaconda.org/main/noarch +- https://repo.anaconda.org/r/osx-arm64 +- https://repo.anaconda.org/r/noarch +- https://repo.anaconda.org/msys2/osx-arm64 +- https://repo.anaconda.org/msys2/noarch + +However, users will just say 'defaults' or 'conda-forge', for convenience. +This means that we need to deal with several formats of channel information, +which ultimately lead to a collection of subdir-specific URLs: + +- Channel names from the CLI or configuration files / env-vars +- Channel URLs if names are not available (channel not served in anaconda.org) +- conda.models.channel.Channel objects + +Their origins can be: + +- Specified by the user on the command-line (-c arguments) +- Specified by the configuration files (.condarc) or environment vars (context object) +- Added from channel-specific MatchSpec (e.g. `conda-forge::python`) +- Added from installed packages in target environment (e.g. a package that was installed + from a non-default channel remembers where it comes from) + +Also note that a channel URL might have authentication in the form: + +- https://user:password@server.com/channel +- https://server.com/t/your_token_goes_here/channel + +Finally, a channel can be mounted in a local directory and referred to via +a regular path, or a file:// URL, with or without normalization on Windows. + +The approach +------------ +We pass the subdir-specific, authenticated URLs to conda's 'SubdirData.repo_patch', +which download the JSON files but do not process them to PackageRecords. +Once the cache has been populated, we can instantiate 'libmamba.Repo' objects directly. +We maintain a map of subdir-specific URLs to `conda.model.channel.Channel` +and `libmamba.Repo` objects. +""" + +from __future__ import annotations + +import logging +import os +from dataclasses import dataclass +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING + +from conda.base.constants import KNOWN_SUBDIRS, REPODATA_FN, ChannelPriority +from conda.base.context import context +from conda.common.compat import on_win +from conda.common.io import DummyExecutor, ThreadLimitedThreadPoolExecutor, time_recorder +from conda.common.url import path_to_url, remove_auth, split_anaconda_token +from conda.core.package_cache_data import PackageCacheData +from conda.core.subdir_data import SubdirData +from conda.models.channel import Channel +from conda.models.match_spec import MatchSpec +from conda.models.records import PackageRecord +from libmambapy import MambaNativeException, Query +from libmambapy.solver.libsolv import ( + Database, + PackageTypes, + PipAsPythonDependency, + Priorities, + RepodataOrigin, +) +from libmambapy.specs import ( + Channel as LibmambaChannel, +) +from libmambapy.specs import ( + ChannelResolveParams, + CondaURL, + NoArchType, + PackageInfo, +) + +from conda_libmamba_solver.shards_subset import build_repodata_subset + +from .mamba_utils import logger_callback + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + from typing import Any, Literal + + from conda.common.path import PathsType + from conda.gateways.repodata import RepodataState + from libmambapy import QueryResult + from libmambapy.solver.libsolv import RepoInfo + + from conda_libmamba_solver.shards import ShardBase + + from .shards_typing import PackageRecordDict + from .state import SolverInputState + + +log = logging.getLogger(f"conda.{__name__}") + + +@dataclass +class _ChannelRepoInfo: + "A dataclass mapping conda Channels, libmamba Repos and URLs" + + channel: Channel | None + repo: RepoInfo + url_w_cred: str + url_no_cred: str + + @property + def canonical_name(self) -> str: + if self.channel: + return self.channel.canonical_name + url_parts = self.url_no_cred.split("/") + if url_parts[-1] in KNOWN_SUBDIRS: + return url_parts[-2] + return url_parts[-1] + + +def _is_sharded_repodata_enabled(): + """ + Flag to see whether we should check for sharded repodata. + """ + return context.plugins.use_sharded_repodata is True # type: ignore + + +_SUPPORTS_PYTHON_SITE_PACKAGES = hasattr(PackageInfo, "python_site_packages_path") + + +def _package_info_from_package_dict( + record: PackageRecordDict, filename: str, url: str, channel_id: str +) -> PackageInfo: + """ + Build libmamba PackageInfo from an unprocessed repodata "packages", "packages.conda" entry. + """ + if (noarch := record.get("noarch")) in ("python", "generic"): + noarch = NoArchType(noarch.title()) + else: + noarch = NoArchType("No") + # include the python_site_packages_path attribute if libmambapy includes support + if _SUPPORTS_PYTHON_SITE_PACKAGES: + extra = { + "python_site_packages_path": record.get("python_site_packages_path") or "", + } + else: + extra = {} + + # the dict has not been "enriched" with channel, subdir, url, filename + + # channel examples + # 'https://repo.anaconda.com/pkgs/main' + # Channel("pkgs/main"), Channel('@') + + # package_url examples, full URL to package or "" for a virtual package, + # possibly a local package + + # filename, the key from repodata + + return PackageInfo( + name=record["name"], + version=record["version"], + build_string=record.get("build", ""), + build_number=record.get("build_number", 0), + channel=channel_id, + package_url=url, + platform=record.get("subdir") or "", + filename=filename, + license=record.get("license") or "", # does the solver use this? + md5=record.get("md5") or "", + sha256=record.get("sha256") or "", + signatures=record.get("signatures") or "", + # conda can have list or tuple, but libmamba only accepts lists + track_features=list(record.get("track_features") or []), + depends=list(record.get("depends") or []), + constrains=list(record.get("constrains") or []), + defaulted_keys=list(record.get("defaulted_keys") or []), + noarch=noarch, + size=record.get("size") or 0, + timestamp=int( + (record.get("timestamp") or 0) * 1000 + ), # XXX packages may have either seconds or milliseconds timestamps, see convert-if-out-of-range code in conda + **extra, + ) + + +class LibMambaIndexHelper: + """ + Interface between conda and libmamba for the purpose of building the "index". + The index is the collection of package records that can be part of a solution. + It is built by collecting all the repodata.json files from channels and their + subdirs. For existing environments, the installed packages are also added to + the index (this helps with simplifying solutions and outputs). The local cache + can also be added as a "channel", which is useful in offline mode or with no + channels configured. + """ + + def __init__( + self, + channels: Iterable[Channel], + subdirs: Iterable[str] = (), + repodata_fn: str = REPODATA_FN, + installed_records: Iterable[PackageRecord] = (), + pkgs_dirs: PathsType = (), + in_state: SolverInputState | None = None, + ): + platform_less_channels = [] + for channel in channels: + if channel.platform: + # When .platform is defined, .urls() will ignore subdirs kw. Remove! + log.info( + "Platform-aware channels are not supported. " + "Ignoring platform %s from channel %s. " + "Use subdirs keyword if necessary.", + channel.platform, + channel, + ) + channel = Channel(**{k: v for k, v in channel.dump().items() if k != "platform"}) + platform_less_channels.append(channel) + self.channels = platform_less_channels + self.subdirs = subdirs or context.subdirs + self.repodata_fn = repodata_fn + self.in_state = in_state + self.db = self._init_db() + + self.repos: list[_ChannelRepoInfo] = self._load_channels() + if pkgs_dirs: + self.repos.extend(self._load_pkgs_cache(pkgs_dirs)) + if installed_records: + self.repos.append(self._load_installed(installed_records)) + self._set_repo_priorities() + + # These are to support lazy self.repos, but it's not currently lazy. + self._pkgs_dirs = pkgs_dirs + self._installed_records = installed_records + + @classmethod + def from_platform_aware_channel(cls, channel: Channel) -> LibMambaIndexHelper: + if not channel.platform: + raise ValueError(f"Channel {channel} must define 'platform' attribute.") + subdir = channel.platform + channel = Channel(**{k: v for k, v in channel.dump().items() if k != "platform"}) + return cls(channels=(channel,), subdirs=(subdir,)) + + def n_packages( + self, + repos: Iterable[RepoInfo] | None = None, + filter_: Callable | None = None, + ) -> int: + repos = repos or [repo_info.repo for repo_info in self.repos] + count = 0 + for repo in repos: + if filter_: + for pkg in self.db.packages_in_repo(repo): + if filter_(pkg): + count += 1 + else: + count += len(self.db.packages_in_repo(repo)) + return count + + def reload_channel(self, channel: Channel) -> None: + urls = {} + for url in channel.urls(with_credentials=False, subdirs=self.subdirs): + for repo_info in self.repos: + if repo_info.url_no_cred == url: + log.debug("Reloading repo %s", repo_info.url_no_cred) + urls[repo_info.url_w_cred] = channel + self.db.remove_repo(repo_info.repo) + for new_repo_info in self._load_channels(urls, try_solv=False): + for repo_info in self.repos: + if repo_info.url_no_cred == new_repo_info.url_no_cred: + repo_info.repo = new_repo_info.repo + self._set_repo_priorities() + + def _init_db(self) -> Database: + custom_channels = { + # Add custom channels as a workaround for this weird conda behavior + # See https://github.com/conda/conda/issues/13501 + **{c.name: c for c in self.channels if c.location != context.channel_alias.location}, + **context.custom_channels, + } + custom_channels = { + name: LibmambaChannel( + url=CondaURL.parse(channel.base_url.replace(" ", "%20")), + display_name=name, + platforms=set(self.subdirs), + ) + for (name, channel) in custom_channels.items() + if channel.base_url + } + custom_multichannels = { + channel_name: [ + custom_channels.get( + channel.name, + LibmambaChannel( + url=CondaURL.parse(channel.base_url.replace(" ", "%20")), + display_name=channel.name, + platforms=set(self.subdirs), + ), + ) + for channel in channels + if channel.base_url + ] + for channel_name, channels in context.custom_multichannels.items() + } + params = ChannelResolveParams( + platforms=set(self.subdirs), + channel_alias=CondaURL.parse(str(context.channel_alias)), + custom_channels=ChannelResolveParams.ChannelMap(custom_channels), + custom_multichannels=ChannelResolveParams.MultiChannelMap(custom_multichannels), + home_dir=str(Path.home()), + current_working_dir=os.getcwd(), + ) + db = Database(params) + db.set_logger(logger_callback) + return db + + def _load_channels( + self, + urls_to_channel: dict[str, Channel] | None = None, + try_solv: bool = True, + ) -> list[_ChannelRepoInfo]: + if urls_to_channel is None: + urls_to_channel = self._channel_urls() + + # conda.common.url.path_to_url does not %-encode spaces + encoded_urls_to_channel = {} + for url, channel in urls_to_channel.items(): + if url.startswith("file://"): + url = url.replace(" ", "%20") + encoded_urls_to_channel[url] = channel + urls_to_channel = encoded_urls_to_channel + + # Prefer sharded repodata loading if it's enabled + if self.in_state and _is_sharded_repodata_enabled(): + # TODO: It may be better to directly pass channel objects without URL encoding + return self._load_channel_repo_info_shards(urls_to_channel) + + # Fallback to repodata.json loading + return self._load_channel_repo_info_json(urls_to_channel, try_solv) + + def _load_channel_repo_info_shards( + self, urls_to_channel: dict[str, Channel] + ) -> list[_ChannelRepoInfo]: + """ + Load repository information from sharded repodata cache. + """ + # make a subset of possible dependencies + root_packages = (*self.in_state.installed.keys(), *self.in_state.requested) + channel_data = build_repodata_subset(root_packages, urls_to_channel) + channel_repo_infos = self._load_repo_info_from_repodata_dict(channel_data) + + return channel_repo_infos + + def _load_channel_repo_info_json( + self, urls_to_channel: dict[str, Channel], try_solv: bool + ) -> list[_ChannelRepoInfo]: + """ + Load repository information from repodata.json files. + """ + urls_to_json_path_and_state = self._fetch_repodata_jsons(tuple(urls_to_channel.keys())) + + channel_repo_infos = [] + for url_w_cred, (json_path, state) in urls_to_json_path_and_state.items(): + url_no_token, _ = split_anaconda_token(url_w_cred) + url_no_cred = remove_auth(url_no_token) + repo = self._load_repo_info_from_json_path( + json_path, + url_no_cred, + state, + try_solv=(try_solv and not self.in_state), + ) + channel_repo_infos.append( + _ChannelRepoInfo( + channel=urls_to_channel[url_w_cred], + repo=repo, + url_w_cred=url_w_cred, + url_no_cred=url_no_cred, + ) + ) + return channel_repo_infos + + def _channel_urls(self) -> dict[str, Channel]: + "Maps authenticated URLs to channel objects" + urls = {} + seen_noauth = set() + channels_with_subdirs = [] + for channel in self.channels: + for url in channel.urls(with_credentials=True, subdirs=self.subdirs): + channels_with_subdirs.append(Channel(url)) + for channel in channels_with_subdirs: + noauth_urls = [ + url + for url in channel.urls(with_credentials=False) + if url.endswith(tuple(self.subdirs)) + ] + if seen_noauth.issuperset(noauth_urls): + continue + auth_urls = [ + url.replace(" ", "%20") + for url in channel.urls(with_credentials=True) + if url.endswith(tuple(self.subdirs)) + ] + if noauth_urls != auth_urls: # authed channel always takes precedence + urls.update({url: channel for url in auth_urls}) + seen_noauth.update(noauth_urls) + continue + # at this point, we are handling an unauthed channel; in some edge cases, + # an auth'd variant of the same channel might already be present in `urls`. + # we only add them if we haven't seen them yet + for url in noauth_urls: + if url not in seen_noauth: + urls[url] = channel + seen_noauth.add(url) + return urls + + def _fetch_repodata_jsons(self, urls: Iterable[str]) -> dict[str, tuple[str, RepodataState]]: + Executor = ( + DummyExecutor + if context.debug or context.repodata_threads == 1 + else partial(ThreadLimitedThreadPoolExecutor, max_workers=context.repodata_threads) + ) + with Executor() as executor: + return { + url: (str(path), state) + for (url, path, state) in executor.map(self._fetch_one_repodata_json, urls) + } + + def _fetch_one_repodata_json(self, url: str) -> tuple[str, os.PathLike, RepodataState]: + channel = Channel.from_url(url) + if not channel.subdir: + raise ValueError("Channel URLs must specify a subdir!") + + if "PYTEST_CURRENT_TEST" in os.environ: + # Workaround some testing issues - TODO: REMOVE + # Fix conda.testing.helpers._patch_for_local_exports by removing last line + for key, cached in list(SubdirData._cache_.items()): + if not isinstance(key, tuple): + continue # should not happen, but avoid IndexError just in case + if key[:2] == (url, self.repodata_fn) and cached._mtime == float("inf"): + del SubdirData._cache_[key] + # /Workaround + + subdir_data = SubdirData(channel, repodata_fn=self.repodata_fn) + if context.offline or context.use_index_cache: + # This might not exist (yet, anymore), but that's ok because we'll check + # for existence later and safely ignore if needed + json_path = subdir_data.cache_path_json + state = subdir_data.repo_cache.load_state() + else: + # TODO: This method loads reads the whole JSON file (does not parse) + json_path, state = subdir_data.repo_fetch.fetch_latest_path() + return url, json_path, state + + def _load_repo_info_from_json_path( + self, json_path: str, channel_url: str, state: RepodataState | None, try_solv: bool = True + ) -> RepoInfo | None: + if try_solv and on_win: + # .solv loading is so slow on Windows is not even worth it. Use JSON instead. + # https://github.com/mamba-org/mamba/pull/2753#issuecomment-1739122830 + log.debug("Overriding truthy 'try_solv' as False on Windows for performance reasons.") + try_solv = False + json_path = Path(json_path) + solv_path = json_path.with_suffix(".solv") + if state: + repodata_origin = RepodataOrigin(url=channel_url, etag=state.etag, mod=state.mod) + else: + repodata_origin = None + channel = Channel(channel_url) + channel_id = self._channel_to_id(channel) + if try_solv and repodata_origin: + try: + log.debug( + "Loading %s (%s) from SOLV repodata at %s", channel_id, channel_url, solv_path + ) + return self.db.add_repo_from_native_serialization( + path=str(solv_path), + expected=repodata_origin, + channel_id=channel_id, + add_pip_as_python_dependency=PipAsPythonDependency( + context.add_pip_as_python_dependency + ), + ) + except Exception as exc: + log.debug("Failed to load from SOLV. Trying JSON.", exc_info=exc) + try: + log.debug( + "Loading %s (%s) from JSON repodata at %s", channel_id, channel_url, json_path + ) + repo = self.db.add_repo_from_repodata_json( + path=str(json_path), + url=channel_url, + channel_id=channel_id, + add_pip_as_python_dependency=PipAsPythonDependency( + context.add_pip_as_python_dependency + ), + package_types=( + PackageTypes.TarBz2Only + if context.use_only_tar_bz2 + else PackageTypes.CondaOrElseTarBz2 + ), + ) + except MambaNativeException as exc: + if "does not exist" in str(exc) and context.offline: + # Ignore errors in offline mode. This is needed to pass + # tests/test_create.py::test_offline_with_empty_index_cache. + # In offline mode, with no repodata cache available, conda can still + # create a channel from the pkgs/ content. For that to work, we must + # not error out this early. If the package is still not found, the solver + # will complain that the package cannot be found. + log.warning("Could not load repodata for %s.", channel_id) + log.debug("Ignored MambaNativeException in offline mode: %s", exc, exc_info=exc) + return None + raise exc + if try_solv and repodata_origin: + try: + self.db.native_serialize_repo( + repo=repo, path=str(solv_path), metadata=repodata_origin + ) + except MambaNativeException as exc: + log.debug("Ignored SOLV writing error for %s", channel_id, exc_info=exc) + return repo + + def _channel_to_id(self, channel: Channel): + channel_id = channel.canonical_name + if channel_id in context.custom_multichannels: + # In multichannels, the canonical name of a "subchannel" is the multichannel name + # which makes it ambiguous for `channel::specs`. In those cases, take the channel + # regular name; e.g. for repo.anaconda.com/pkgs/main, do not take defaults, but + # pkgs/main instead. + channel_id = channel.name + return channel_id + + def _load_installed(self, records: Iterable[PackageRecord]) -> _ChannelRepoInfo: + packages = [self._package_info_from_package_record(record) for record in records] + repo = self.db.add_repo_from_packages( + packages=packages, + name="installed", + add_pip_as_python_dependency=PipAsPythonDependency.No, + ) + self.db.set_installed_repo(repo) + return _ChannelRepoInfo( + channel=None, repo=repo, url_w_cred="installed", url_no_cred="installed" + ) + + def _load_pkgs_cache(self, pkgs_dirs: PathsType) -> list[RepoInfo]: + repos = [] + for path in pkgs_dirs: + package_cache_data = PackageCacheData(path) + package_cache_data.load() + packages = [ + self._package_info_from_package_record(record) + for record in package_cache_data.values() + ] + repo = self.db.add_repo_from_packages(packages=packages, name=path) + # path_to_url does not %-encode spaces + path_as_url = path_to_url(path).replace(" ", "%20") + repos.append( + _ChannelRepoInfo( + channel=None, repo=repo, url_w_cred=path_as_url, url_no_cred=path_as_url + ) + ) + return repos + + @time_recorder(module_name=__name__) + def _load_repo_info_from_repodata_dict( + self, repodata_subset: dict[str, ShardBase] + ) -> list[_ChannelRepoInfo]: + """ + Load repository information from deserialized repodata.json-like + structures. + """ + repos = [] + for channel_url, shardlike in repodata_subset.items(): + repodata = shardlike.build_repodata() + # Don't like going back and forth between channel objects and URLs; + # build_repodata_subset() expands channels into per-subdir URLs as + # part of fetch: + channel_object = Channel(channel_url) + channel_id = self._channel_to_id(channel_object) + # must be appropriate for string concatenation: + base_url = shardlike.base_url + + packages = [] + for package_group in ("packages", "packages.conda"): + for filename, record in repodata.get(package_group, {}).items(): + package = _package_info_from_package_dict( + record, + filename, + url=f"{base_url}{filename}", + channel_id=channel_id, + ) + packages.append(package) + + repo = self.db.add_repo_from_packages(packages=packages, name=channel_url) + repos.append( + _ChannelRepoInfo( + channel=channel_object, + repo=repo, + url_w_cred=channel_url, + url_no_cred=channel_url, + ) + ) + + return repos + + def _package_info_from_package_record(self, record: PackageRecord) -> PackageInfo: + if record.get("noarch", None) and record.noarch.value in ("python", "generic"): + noarch = NoArchType(record.noarch.value.title()) + else: + noarch = NoArchType("No") + # include the python_site_packages_path attribute if libmambapy includes support + if _SUPPORTS_PYTHON_SITE_PACKAGES: + extra = { + "python_site_packages_path": record.get("python_site_packages_path") or "", + } + else: + extra = {} + + return PackageInfo( + name=record.name, + version=record.version, + build_string=record.build or "", + build_number=record.build_number or 0, + channel=str(record.channel), + package_url=record.get("url") or "", + platform=record.subdir, + filename=record.fn or f"{record.name}-{record.version}-{record.build or ''}", + license=record.get("license") or "", + md5=record.get("md5") or "", + sha256=record.get("sha256") or "", + signatures=record.get("signatures") or "", + # conda can have list or tuple, but libmamba only accepts lists + track_features=list(record.get("track_features") or []), + depends=list(record.get("depends") or []), + constrains=list(record.get("constrains") or []), + defaulted_keys=list(record.get("defaulted_keys") or []), + noarch=noarch, + size=record.get("size") or 0, + timestamp=int((record.get("timestamp") or 0) * 1000), + **extra, + ) + + def _set_repo_priorities(self) -> None: + has_priority = context.channel_priority in ( + ChannelPriority.STRICT, + ChannelPriority.FLEXIBLE, + ) + + subprio_index = len(self.repos) + if has_priority: + # max channel priority value is the number of unique channels + channel_prio = len({repo.canonical_name for repo in self.repos}) + current_channel_name = self.repos[0].canonical_name + + for repo_info in self.repos: + if repo_info.repo is None: + continue + if has_priority: + if repo_info.canonical_name != current_channel_name: + channel_prio -= 1 + current_channel_name = repo_info.canonical_name + priority = channel_prio + else: + priority = 0 + if has_priority: + # NOTE: -- This was originally 0, but we need 1. + # Otherwise, conda/conda @ test_create::test_force_remove fails :shrug: + subpriority = 1 + else: + subpriority = subprio_index + subprio_index -= 1 + + log.debug( + "Channel: %s, prio: %s : %s", + repo_info.url_no_cred, + priority, + subpriority, + ) + self.db.set_repo_priority(repo_info.repo, Priorities(priority, subpriority)) + + # region Repoquery + ################# + + def search( + self, + queries: Iterable[str | MatchSpec] | str | MatchSpec, + return_type: Literal["records", "dict", "raw"] = "records", + ) -> list[PackageRecord] | dict[str, Any] | QueryResult: + if isinstance(queries, (str, MatchSpec)): + queries = [queries] + queries = list(map(str, queries)) + result = Query.find(self.db, queries) + return self._process_query_result(result, return_type) + + def depends( + self, + query: str | MatchSpec, + tree: bool = False, + return_type: Literal["records", "dict", "raw"] = "records", + ) -> list[PackageRecord] | dict[str, Any] | QueryResult: + query = str(query) + result = Query.depends(self.db, query, tree) + return self._process_query_result(result, return_type) + + def whoneeds( + self, + query: str | MatchSpec, + tree: bool = False, + return_type: Literal["records", "dict", "raw"] = "records", + ) -> list[PackageRecord] | dict[str, Any] | QueryResult: + query = str(query) + result = Query.whoneeds(self.db, query, tree) + return self._process_query_result(result, return_type) + + def explicit_pool(self, specs: Iterable[MatchSpec]) -> tuple[str, ...]: + """ + Returns all the package names that (might) depend on the passed specs + """ + explicit_pool: set[str] = set() + for spec in specs: + pkg_records = self.depends(spec.dist_str()) + for record in pkg_records: + explicit_pool.add(record.name) + return tuple(explicit_pool) + + def _process_query_result( + self, + result: QueryResult, + return_type: Literal["records", "dict", "raw"] = "records", + ) -> list[PackageRecord] | dict[str, Any] | QueryResult: + if return_type == "raw": + return result + result = result.to_dict() + if result.get("result", {}).get("status") != "OK": + query_type = result.get("query", {}).get("type", "") + query = result.get("query", {}).get("query", "") + error_msg = result.get("result", {}).get("msg", f"Faulty response: {result.json()}") + raise ValueError(f"{query_type} query '{query}' failed: {error_msg}") + if return_type == "records": + pkg_records = [] + for pkg in result["result"]["pkgs"]: + record = PackageRecord(**pkg) + pkg_records.append(record) + return pkg_records + # return_type == "dict" + return result + + # endregion diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/mamba_utils.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/mamba_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc4ee6c981372fb6a5214ae1201a538cc26f16d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/mamba_utils.py @@ -0,0 +1,183 @@ +# Copyright (C) 2019 QuantStack and the Mamba contributors. +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause + +# TODO: Temporarily vendored from mamba.utils v0.19 on 2021.12.02 +# Decide what to do with it when we split into a plugin +# 2022.02.15: updated vendored parts to v0.21.2 +# 2022.11.14: only keeping channel prioritization and context initialization logic now +# 2024.09.24: parameterize init_api_context + +from __future__ import annotations + +import os +import logging +import sys +from collections.abc import Iterable +from functools import lru_cache +from importlib.metadata import version +from pathlib import Path +from typing import TYPE_CHECKING, Iterable + +import libmambapy +from conda.base.constants import ChannelPriority +from conda.base.context import context +from conda.common.compat import on_win + +if TYPE_CHECKING: + from .index import _ChannelRepoInfo + + + +log = logging.getLogger(f"conda.{__name__}") +_db_log = logging.getLogger("conda.libmamba.db") +_libmamba_context = None + +@lru_cache(maxsize=1) +def mamba_version() -> str: + return version("libmambapy") + + +def _get_base_url(url: str, name: str | None = None) -> str: + tmp = url.rsplit("/", 1)[0] + if name: + if tmp.endswith(name): + return tmp.rsplit("/", 1)[0] + return tmp + + +def init_libmamba_context( + channels: Iterable[str] | None = None, + platform: str | None = None, + target_prefix: str | None = None, +) -> libmambapy.Context: + global _libmamba_context + if _libmamba_context is None: + # This function has to be called BEFORE 1st initialization of the context + _libmamba_context = libmambapy.Context( + libmambapy.ContextOptions( + enable_signal_handling=False, + enable_logging=True, + ) + ) + libmamba_context = _libmamba_context + + # Output params + libmamba_context.output_params.json = context.json + if libmamba_context.output_params.json: + libmambapy.cancel_json_output(libmamba_context) + libmamba_context.output_params.quiet = context.quiet + libmamba_context.output_params.verbosity = context.verbosity + libmamba_context.set_log_level( + { + 4: libmambapy.LogLevel.TRACE, + 3: libmambapy.LogLevel.DEBUG, + 2: libmambapy.LogLevel.INFO, + 1: libmambapy.LogLevel.WARNING, + 0: libmambapy.LogLevel.ERROR, + }[context.verbosity] + ) + + # Prefix params + libmamba_context.prefix_params.conda_prefix = context.conda_prefix + libmamba_context.prefix_params.root_prefix = context.root_prefix + libmamba_context.prefix_params.target_prefix = str( + target_prefix if target_prefix is not None else context.target_prefix + ) + + # Networking params -- we always operate offline from libmamba's perspective + libmamba_context.remote_fetch_params.user_agent = context.user_agent + libmamba_context.local_repodata_ttl = context.local_repodata_ttl + libmamba_context.offline = True + libmamba_context.use_index_cache = True + + # General params + libmamba_context.add_pip_as_python_dependency = context.add_pip_as_python_dependency + libmamba_context.always_yes = context.always_yes + libmamba_context.dry_run = context.dry_run + libmamba_context.envs_dirs = context.envs_dirs + libmamba_context.pkgs_dirs = context.pkgs_dirs + libmamba_context.use_lockfiles = False + libmamba_context.use_only_tar_bz2 = context.use_only_tar_bz2 + + # Channels and platforms + libmamba_context.platform = platform if platform is not None else context.subdir + libmamba_context.channels = list(channels) if channels is not None else context.channels + libmamba_context.channel_alias = str( + _get_base_url(context.channel_alias.url(with_credentials=True)) + ) + + RESERVED_NAMES = {"local", "defaults"} + additional_custom_channels = {} + for el in context.custom_channels: + if context.custom_channels[el].canonical_name not in RESERVED_NAMES: + additional_custom_channels[el] = _get_base_url( + context.custom_channels[el].url(with_credentials=True), el + ) + libmamba_context.custom_channels = additional_custom_channels + + additional_custom_multichannels = { + "local": list(context.conda_build_local_paths), + "defaults": [channel.url(with_credentials=True) for channel in context.default_channels], + } + for el in context.custom_multichannels: + if el not in RESERVED_NAMES: + additional_custom_multichannels[el] = [] + for c in context.custom_multichannels[el]: + additional_custom_multichannels[el].append( + _get_base_url(c.url(with_credentials=True)) + ) + libmamba_context.custom_multichannels = additional_custom_multichannels + + libmamba_context.default_channels = [ + _get_base_url(x.url(with_credentials=True)) for x in context.default_channels + ] + + if context.channel_priority is ChannelPriority.STRICT: + libmamba_context.channel_priority = libmambapy.ChannelPriority.Strict + elif context.channel_priority is ChannelPriority.FLEXIBLE: + libmamba_context.channel_priority = libmambapy.ChannelPriority.Flexible + elif context.channel_priority is ChannelPriority.DISABLED: + libmamba_context.channel_priority = libmambapy.ChannelPriority.Disabled + + return libmamba_context + + +def logger_callback(level: libmambapy.solver.libsolv.LogLevel, msg: str, logger: logging.Logger =_db_log) -> None: + # from libmambapy.solver.libsolv import LogLevel + # levels = { + # LogLevel.Debug: logging.DEBUG, # 0 -> 10 + # LogLevel.Warning: logging.WARNING, # 1 -> 30 + # LogLevel.Error: logging.ERROR, # 2 -> 40 + # LogLevel.Fatal: logging.FATAL, # 3 -> 50 + # } + if level.value == 0: + # This incurs a large performance hit! + logger.debug(msg) + else: + logger.log((level.value + 2) * 10, msg) + + +def palettes_and_formats() -> tuple[libmambapy.solver.ProblemsMessageFormat, libmambapy.solver.ProblemsMessageFormat]: + # _indents = ["│ ", " ", "├─ ", "└─ "] + if os.getenv("NO_COLOR"): + use_color = False + elif os.getenv("FORCE_COLOR"): + use_color = True + else: + use_color = all([sys.stdout.isatty(), sys.stdin.isatty()]) + palette_no_color = libmambapy.Palette.no_color() + problems_format_nocolor = libmambapy.solver.ProblemsMessageFormat() + problems_format_nocolor.unavailable = palette_no_color.failure + problems_format_nocolor.available = palette_no_color.success + problems_format_auto = ( + libmambapy.solver.ProblemsMessageFormat() + if use_color + else problems_format_nocolor + ) + + return problems_format_auto, problems_format_nocolor + + +problems_format_auto, problems_format_nocolor = palettes_and_formats() diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/plugin.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..61dd314e171486d1e93fba590ded9dc209aa336d --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/plugin.py @@ -0,0 +1,46 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Entry points for the conda plugin system +""" + +from conda.common.configuration import PrimitiveParameter +from conda.plugins import hookimpl +from conda.plugins.types import CondaSetting, CondaSolver, CondaSubcommand + +from .repoquery import configure_parser, repoquery +from .solver import LibMambaSolver + + +@hookimpl +def conda_solvers(): + """ + The conda plugin hook implementation to load the solver into conda. + """ + yield CondaSolver( + name="libmamba", + backend=LibMambaSolver, + ) + + +@hookimpl +def conda_subcommands(): + yield CondaSubcommand( + name="repoquery", + summary="Advanced search for repodata.", + action=repoquery, + configure_parser=configure_parser, + ) + + +@hookimpl +def conda_settings(): + """ + Define all settings specific to the conda-libmamba-solver plugin. + """ + yield CondaSetting( + name="use_sharded_repodata", + description="Enable use of sharded repodata when available.", + parameter=PrimitiveParameter(False, element_type=bool), + ) diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/repoquery.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/repoquery.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc708cd4f5acc8cd865ea64d9f242c1c882385b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/repoquery.py @@ -0,0 +1,216 @@ +# Copyright (C) 2019, QuantStack +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Implementation of the 'conda repoquery' subcommand. + +Based on 'mamba repoquery' for v1.x. +""" + +import argparse +import json +import sys +from itertools import chain + +from conda.base.context import context +from conda.cli import conda_argparse +from conda.core.prefix_data import PrefixData +from conda.exceptions import CondaError +from conda.models.channel import Channel +from conda.models.match_spec import MatchSpec +from conda.reporters import get_spinner +from libmambapy import Context as LibmambaContext + +from .index import LibMambaIndexHelper + + +def configure_parser(parser: argparse.ArgumentParser): + package_cmds = argparse.ArgumentParser(add_help=False) + package_cmds.add_argument("specs", help="The target package(s).", nargs="+") + package_grp = package_cmds.add_argument_group("Subcommand options") + package_grp.add_argument( + "-i", + "--installed", + action="store_true", + default=True, + help=argparse.SUPPRESS, + ) + package_grp.add_argument( + "-p", + "--platform", + default=context.subdir, + help="Platform/subdir to search packages for. Defaults to current platform.", + ) + package_grp.add_argument( + "--no-installed", action="store_true", help="Do not search currently installed packages." + ) + package_grp.add_argument( + "--pretty", action="store_true", help="Prettier output with more details." + ) + + package_grp.add_argument( + "-a", + "--all-channels", + action="store_true", + help="Look at all channels (for depends / whoneeds).", + ) + package_grp.add_argument( + "--use-cache-only", + action="store_true", + help="Search in pkgs_dirs too", + ) + + view_cmds = argparse.ArgumentParser(add_help=False) + view_grp = view_cmds.add_argument_group("Dependency options") + view_grp.add_argument( + "-t", "--tree", action="store_true", help="Show dependencies in a tree-like format." + ) + view_grp.add_argument( + "--recursive", action="store_true", help="Show dependencies recursively." + ) + + subparser = parser.add_subparsers(dest="subcmd") + + whoneeds = subparser.add_parser( + "whoneeds", + help="Show packages that depend on this package.", + parents=[package_cmds, view_cmds], + ) + + depends = subparser.add_parser( + "depends", + help="Show dependencies of this package.", + parents=[package_cmds, view_cmds], + ) + + search = subparser.add_parser( + "search", + help="Show all available package versions.", + parents=[package_cmds], + ) + + for cmd in (whoneeds, search, depends): + conda_argparse.add_parser_channels(cmd) + conda_argparse.add_parser_networking(cmd) + conda_argparse.add_parser_known(cmd) + conda_argparse.add_parser_json(cmd) + + +def repoquery(args: argparse.Namespace) -> int: + if not args.subcmd: + print("repoquery needs a subcommand (search, depends or whoneeds), e.g.:", file=sys.stderr) + print(" conda repoquery search python\n", file=sys.stderr) + return 1 + + cli_flags = [getattr(args, attr, False) for attr in ("tree", "recursive", "pretty")] + if sum([context.json, *cli_flags]) > 1: + print("Use only one of --json, --tree, --recursive and --pretty.", file=sys.stderr) + return 1 + + if hasattr(args, "channel"): + channels = args.channel + else: + channels = None + if args.all_channels or channels is None: + if channels: + print("WARNING: Using all channels instead of configured channels\n", file=sys.stderr) + channels = context.channels + + use_installed = args.installed + if args.no_installed: + use_installed = False + + # if we're asking for depends and channels are given, disregard + # installed packages to prevent weird mixing + if args.subcmd in ("depends", "whoneeds") and use_installed and channels: + use_installed = False + + if args.subcmd == "search" and not args.installed: + only_installed = False + elif args.all_channels or (channels and len(channels)): + only_installed = False + else: + only_installed = True + + if only_installed and args.no_installed: + print("No channels selected. Use -a to search all channels.", file=sys.stderr) + return 1 + + if use_installed: + prefix_data = PrefixData(context.target_prefix) + prefix_data.load() + installed_records = prefix_data.iter_records() + else: + installed_records = () + + if args.use_cache_only: + with get_spinner("Collecting package metadata from pkgs_dirs"): + index = LibMambaIndexHelper( + installed_records=(), + channels=(), + subdirs=(args.platform, "noarch"), + repodata_fn=context.repodata_fns[-1], + pkgs_dirs=context.pkgs_dirs, + ) + else: + channels_from_specs = [] + for spec in args.specs: + ms = MatchSpec(spec) + channel = ms.get_exact_value("channel") + if channel: + channels_from_specs.append(channel) + with get_spinner("Collecting package metadata"): + index = LibMambaIndexHelper( + installed_records=installed_records, + channels=[ + Channel(c) for c in chain(channels or (), dict.fromkeys(channels_from_specs)) + ], + subdirs=(args.platform, "noarch"), + repodata_fn=context.repodata_fns[-1], + ) + + if args.subcmd == "search": + result = index.search(args.specs, return_type="raw") + if context.json: + print(json.dumps(result.groupby("name").to_dict(), indent=2)) + elif getattr(args, "pretty", None): + print(result.pretty(show_all_builds=True)) + else: + print(result.groupby("name").table()) + elif args.subcmd == "depends": + if len(args.specs) > 1: + raise CondaError("Only one query supported for 'depends'.") + result = index.depends( + args.specs[0], + tree=getattr(args, "tree", False) or getattr(args, "recursive", False), + return_type="raw", + ) + if context.json: + print(json.dumps(result.to_dict(), indent=2)) + elif getattr(args, "tree", None) or getattr(args, "pretty", None): + # TODO: Report upstream + raise CondaError("--tree currently not available for this subcommand.") + print(result.tree(LibmambaContext.instance().graphics_params)) + else: + print(result.sort("name").table()) + elif args.subcmd == "whoneeds": + if len(args.specs) > 1: + raise CondaError("Only one query supported for 'whoneeds'.") + result = index.whoneeds( + args.specs[0], + tree=getattr(args, "tree", False) or getattr(args, "recursive", False), + return_type="raw", + ) + if context.json: + print(json.dumps(result.to_dict(), indent=2)) + elif getattr(args, "tree", None) or getattr(args, "pretty", None): + # TODO: Report upstream + raise CondaError("--tree currently not available for this subcommand.") + print(result.tree(LibmambaContext.instance().graphics_params)) + else: + print(result.sort("name").table()) + else: + raise CondaError(f"Unrecognized subcommand: {args.subcmd}") + + return 0 diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards.py new file mode 100644 index 0000000000000000000000000000000000000000..ccdbc539cd2021e4294e7f667b2664c89477275e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards.py @@ -0,0 +1,708 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Models for sharded repodata, and to make monolithic repodata look like sharded +repodata. +""" + +from __future__ import annotations + +import abc +import concurrent.futures +import functools +import json +import logging +from collections import defaultdict +from pathlib import Path +from typing import TYPE_CHECKING +from urllib.parse import urljoin + +import conda.gateways.repodata +import msgpack +import zstandard +from conda.base.context import context +from conda.core.subdir_data import SubdirData +from conda.gateways.connection.session import get_session +from conda.gateways.repodata import ( + _add_http_value_to_dict, + conda_http_errors, +) +from conda.models.channel import Channel +from libmambapy.bindings import specs +from requests import HTTPError + +from . import shards_cache + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + from collections.abc import Iterable, KeysView + + from conda.gateways.repodata import RepodataCache + from requests import Response + + from conda_libmamba_solver.shards_typing import RepodataDict, ShardsIndexDict + + from .shards_typing import PackageRecordDict, ShardDict + +SHARDS_CONNECTIONS_DEFAULT = 10 +ZSTD_MAX_SHARD_SIZE = 2**20 * 16 # maximum size necessary when compressed data has no size header +# For reference, the largest shard "conda-forge/linux-64/vim" is 2608283 bytes +# or < 2**19*5 decompressed (486155 bytes compressed); the index is 575219 bytes +# decompressed (514039 bytes compressed) and is mostly uncompressible hash data. + + +def _shards_connections() -> int: + """ + If context.repodata_threads is not set, find the size of the connection pool + in a typical https:// session. This should significantly reduce dropped + connections. We match requests' default 10. + + Is this shared between all sessions? Or do we get a different pool for a + different get_session(url)? + + Other adapters (file://, s3://) used in conda would have different + concurrency behavior; we are not prepared to have separate threadpools per + connection type. + """ + if context.repodata_threads is not None: + return context.repodata_threads + return SHARDS_CONNECTIONS_DEFAULT + + +def ensure_hex_hash(record: PackageRecordDict): + """ + Convert bytes checksums to hex; leave unchanged if already str. + """ + for hash_type in "sha256", "md5": + if hash_value := record.get(hash_type): + if not isinstance(hash_value, str): + record[hash_type] = bytes(hash_value).hex() + return record + + +@functools.cache +def spec_to_package_name(spec: str) -> str: + """ + Given a dependency spec, return the package name. + """ + # Note: hope for no MatchSpec-without-name in repodata, although it is + # possible in the MatchSpec grammar. + parsed_spec = specs.MatchSpec.parse(spec) + name = str(parsed_spec.name) + return name + + +def shard_mentioned_packages(shard: ShardDict) -> Iterable[str]: + """ + Return all dependency names mentioned in a shard, not including the shard's + own package name. + """ + unique_specs = set() + for package in (*shard["packages"].values(), *shard["packages.conda"].values()): + ensure_hex_hash(package) # otherwise we could do this at serialization + for spec in (*package.get("depends", ()),): # , *package.get("constrains", ())): + if spec in unique_specs: + continue + unique_specs.add(spec) + name = spec_to_package_name(spec) + yield name # not much improvement from only yielding unique names + + +class ShardBase(abc.ABC): + """ + Abstract base class for shard-like objects. + + Defines the common interface for both sharded repodata (Shards) + and traditional repodata presented as shards (ShardLike). + """ + + url: str + repodata_no_packages: RepodataDict + visited: dict[str, ShardDict | None] + _base_url: str + + @property + @abc.abstractmethod + def package_names(self) -> KeysView[str]: + """Return the names of all packages available in this shard collection.""" + ... + + @property + def base_url(self) -> str: + """ + Return self.url joined with base_url from repodata, or self.url if no + base_url was present. Packages are found here. + + Note base_url can be a relative or an absolute url. + The double urljoin ensures proper URL normalization: + first join with _base_url, then with "." to add trailing slash + if needed. + """ + return urljoin(urljoin(self.url, self._base_url), ".") + + def __contains__(self, package: str) -> bool: + """Check if a package is available in this shard collection.""" + return package in self.package_names + + @abc.abstractmethod + def shard_url(self, package: str) -> str: + """ + Return shard URL for a given package. For monolithic repodata, should + not be fetched but is a unique identifier. + + Raise KeyError if package is not in the index. + """ + ... + + @abc.abstractmethod + def shard_loaded(self, package: str) -> bool: + """ + Return True if the given package's shard is in memory. + """ + ... + + def visit_package(self, package: str) -> ShardDict: + """ + Return a shard that is already loaded in memory and mark as visited. + """ + ... + + def visit_shard(self, package: str, shard: ShardDict): + """ + Store new shard data in the visited dict. + """ + self.visited[package] = shard + + @abc.abstractmethod + def fetch_shard(self, package: str) -> ShardDict: + """ + Fetch an individual shard for the given package. + """ + ... + + @abc.abstractmethod + def fetch_shards(self, packages: Iterable[str]) -> dict[str, ShardDict]: + """ + Fetch multiple shards in one go. + """ + ... + + def build_repodata(self) -> RepodataDict: + """ + Return monolithic repodata including all visited shards. + """ + repodata = self.repodata_no_packages.copy() + repodata.update({"packages": {}, "packages.conda": {}}) + for _, shard in self.visited.items(): + if shard is None: + continue # recorded visited but not available shards + for package_group in ("packages", "packages.conda"): + repodata[package_group].update(shard[package_group]) + return repodata + + +class ShardLike(ShardBase): + """ + Present a "classic" repodata.json as per-package shards. + """ + + def __init__(self, repodata: RepodataDict, url: str = ""): + """ + url: must be unique for all ShardLike used together. + """ + self.repodata_no_packages: RepodataDict = { + **repodata, + "packages": {}, + "packages.conda": {}, + } + all_packages = { + "packages": repodata.get("packages", {}), + "packages.conda": repodata.get("packages.conda", {}), + } + self.url = url + + shards = defaultdict(lambda: {"packages": {}, "packages.conda": {}}) + + for group_name, group in all_packages.items(): + for package, record in group.items(): + name = record["name"] + shards[name][group_name][package] = record + + # defaultdict behavior no longer wanted + self.shards: dict[str, ShardDict] = dict(shards) # type: ignore + + # used to write out repodata subset + self.visited: dict[str, ShardDict | None] = {} + + # alternate location for packages, if not self.url + try: + base_url = self.repodata_no_packages["info"]["base_url"] + if not isinstance(base_url, str): + log.warning(f'repodata["info"]["base_url"] was not a str, got {type(base_url)}') + raise TypeError() + self._base_url = base_url + except KeyError: + self._base_url = "" + + def __repr__(self): + left, right = super().__repr__().split(maxsplit=1) + return f"{left} {self.url} {right}" + + @property + def package_names(self) -> KeysView[str]: + return self.shards.keys() + + def shard_url(self, package: str) -> str: + """ + Return shard URL for a given package. + + Raise KeyError if package is not in the index. + """ + self.shards[package] + return f"{self.url}#{package}" + + def shard_loaded(self, package: str) -> bool: + """ + Return True if the given package's shard is in memory. + """ + return package in self.shards + + def visit_package(self, package: str) -> ShardDict: + """ + Return a shard that is already in memory and mark as visited. + """ + shard = self.fetch_shard(package) + assert shard is not None + return shard + + def fetch_shard(self, package: str) -> ShardDict: + """ + "Fetch" an individual shard. + + Update self.visited with all not-None packages. + + Raise KeyError if package is not in the index. + """ + shard = self.shards[package] + self.visited[package] = shard + return shard + + def fetch_shards(self, packages: Iterable[str]) -> dict[str, ShardDict]: + """ + Fetch multiple shards in one go. + + Update self.visited with all not-None packages. + """ + return {package: self.fetch_shard(package) for package in packages} + + +def _shards_base_url(url, shards_base_url) -> str: + """ + Return shards_base_url joined with base_url and url. + Note shards_base_url can be a relative or an absolute url. + """ + if shards_base_url and not shards_base_url.endswith("/"): + shards_base_url += "/" + return urljoin(urljoin(url, shards_base_url), ".") + + +class Shards(ShardBase): + """ + Handle repodata_shards.msgpack.zst and individual per-package shards. + """ + + # cache for shards_base_url() + _shards_base_url = "" + _shards_base_url_key = (None, None) + + def __init__(self, shards_index: ShardsIndexDict, url: str, cache: shards_cache.ShardCache): + """ + Args: + shards_index: raw parsed msgpack dict + url: URL of repodata_shards.msgpack.zst + """ + self.shards_index = shards_index + self.url = url + self.shards_cache = cache + + # Use the channel's base URL to share session amongst subdir locations + channel_base_url = Channel(self.shards_base_url).base_url + self.session = get_session(channel_base_url) + + self.repodata_no_packages = { + "info": shards_index["info"], + "packages": {}, + "packages.conda": {}, + "repodata_version": 2, + } + + # used to write out repodata subset + # not used in traversal algorithm + self.visited: dict[str, ShardDict | None] = {} + + # https://github.com/conda/conda-index/pull/209 ensures that sharded + # repodata will always include base_url, even if it is an empty string; + # rattler/pixi require these keys. + self._base_url = shards_index["info"]["base_url"] + + @property + def package_names(self): + return self.packages_index.keys() + + @property + def packages_index(self): + return self.shards_index["shards"] + + @property + def shards_base_url(self) -> str: + """ + Return self.url joined with shards_base_url. + Note shards_base_url can be a relative or an absolute url. + """ + # could be simplified by restricting self.shards_index assignment + shards_base_url_ = self.shards_index["info"].get("shards_base_url", "") + cache_key = (self.url, shards_base_url_) + if self._shards_base_url_key != cache_key: + self._shards_base_url_key = cache_key + self._shards_base_url = _shards_base_url(self.url, shards_base_url_) + return self._shards_base_url + + def shard_url(self, package: str) -> str: + """ + Return shard URL for a given package. + + Raise KeyError if package is not in the index. + """ + shard_name = f"{bytes(self.packages_index[package]).hex()}.msgpack.zst" + # "Individual shards are stored under the URL .msgpack.zst" + return f"{self.shards_base_url}{shard_name}" + + def shard_loaded(self, package: str) -> bool: + """ + Return True if the given package's shard is in memory. + """ + return package in self.visited + + def visit_package(self, package: str) -> ShardDict: + """ + Return a shard that is already in memory and mark as visited. + """ + shard = self.visited[package] + return shard + + def fetch_shard(self, package: str) -> ShardDict: + """ + Fetch an individual shard for the given package. + + Default implementation calls fetch_shards() with a single package. + Subclasses may override for more efficient single-fetch operations. + + Raise KeyError if package is not in the index. + """ + return self.fetch_shards([package])[package] + + def fetch_shards(self, packages: Iterable[str]) -> dict[str, ShardDict]: + """ + Return mapping of *package names* to Shard for given packages. + + If a shard is already in self.visited, it is not fetched again. + """ + results = {} + + def fetch(s, url, package_to_fetch): + response = s.get(url) + response.raise_for_status() + data = response.content + + return shards_cache.AnnotatedRawShard( + url=url, package=package_to_fetch, compressed_shard=data + ) + + packages = sorted(list(packages)) + urls_packages = {} # package shards to fetch + for package in packages: + if package in self.visited: + results[package] = self.visited[package] + else: + urls_packages[self.shard_url(package)] = package + + with concurrent.futures.ThreadPoolExecutor(max_workers=_shards_connections()) as executor: + futures = { + executor.submit(fetch, self.session, url, package): (url, package) + for url, package in urls_packages.items() + if package not in results + } + for future in concurrent.futures.as_completed(futures): + log.debug(". %s", futures[future]) + url, package = futures[future] + self._process_fetch_result(future, url, package, results) + + self.visited.update(results) + + return results + + def _process_fetch_result(self, future, url, package, results): + """ + Process a single fetched shard. + """ + with conda_http_errors(url, package): + fetch_result = future.result() + + # Decompress and save record + results[fetch_result.package] = msgpack.loads( + zstandard.decompress( + fetch_result.compressed_shard, max_output_size=ZSTD_MAX_SHARD_SIZE + ) + ) + + # Cache fetched shard + self.shards_cache.insert(fetch_result) + + +def repodata_shards(url, cache: RepodataCache) -> bytes: + """ + Fetch shards index with cache. + + Update cache state. + + Return shards data, either newly fetched or from cache. + """ + session = get_session(url) + + state = cache.state + headers = {} + etag = state.etag + last_modified = state.mod + if etag: + headers["If-None-Match"] = str(etag) + if last_modified: + headers["If-Modified-Since"] = str(last_modified) + filename = "repodata_shards.msgpack.zst" + + with conda_http_errors(url, filename): + timeout = ( + context.remote_connect_timeout_secs, + context.remote_read_timeout_secs, + ) + response: Response = session.get( + url, headers=headers, proxies=session.proxies, timeout=timeout + ) + response.raise_for_status() + response_bytes = response.content + + if response.status_code == 304: + # should we save cache-control to state here to put another n + # seconds on the "make a remote request" clock and/or touch cache + # mtime + return cache.cache_path_shards.read_bytes() + + saved_fields = {conda.gateways.repodata.URL_KEY: url} + for header, key in ( + ("Etag", conda.gateways.repodata.ETAG_KEY), + ( + "Last-Modified", + conda.gateways.repodata.LAST_MODIFIED_KEY, + ), + ("Cache-Control", conda.gateways.repodata.CACHE_CONTROL_KEY), + ): + _add_http_value_to_dict(response, header, saved_fields, key) + + state.update(saved_fields) + + # should we return the response and let caller save cache data to state? + return response_bytes + + +def fetch_shards_index( + sd: SubdirData, cache: shards_cache.ShardCache | None = None +) -> Shards | None: + """ + Check a SubdirData's URL for shards. + + Return shards index bytes from cache or network. + Return None if not found; caller should fetch normal repodata. + + TODO: If this function fails to retrieve the sharded repodata index file, it will + mark it is as not supporting this feature in cache. This can problematic + because sometimes server errors can happen which will lead it to wrongly + assuming the channel doesn't support sharding. We need to rethink our + logic for determining shard support. + """ + + fetch = sd.repo_fetch + repo_cache = fetch.repo_cache + + # cache.load_state() will clear the file on JSONDecodeError but cache.load() + # will raise the exception. + # repo_cache.load_state( + # binary=True + # ) # won't succeed when .msgpack.zst is missing as it wants to compare the timestamp (returns empty state) + + # Load state ourselves to avoid clearing when binary cached data is missing. + # If we fall back to monolithic repodata.json, the standard fetch code will + # load the state again in text mode. + try: + with repo_cache.lock("r+") as state_file: + # cannot use pathlib.read_text / write_text on any locked file, as + # it will release the lock early + state = json.loads(state_file.read()) + repo_cache.state.update(state) + except (FileNotFoundError, json.JSONDecodeError): + pass + + cache_state = repo_cache.state + + if cache is None: + cache = shards_cache.ShardCache(Path(conda.gateways.repodata.create_cache_dir())) + + if cache_state.should_check_format("shards"): + # look for shards index + shards_data = None + shards_index_url = f"{sd.url_w_subdir}/repodata_shards.msgpack.zst" + + if not repo_cache.cache_path_shards.exists(): + # avoid 304 not modified if we don't have the file + cache_state.etag = "" + cache_state.mod = "" + elif not repo_cache.stale(): + # load from cache without network request + shards_data = repo_cache.cache_path_shards.read_bytes() + + if shards_data is None: + try: + shards_data = repodata_shards(shards_index_url, repo_cache) + cache_state.set_has_format("shards", True) + # this will also set state["refresh_ns"] = time.time_ns(); we could + # call cache.refresh() if we got a 304 instead: + repo_cache.save(shards_data) + except (HTTPError, conda.gateways.repodata.RepodataIsEmpty): + # fetch repodata.json / repodata.json.zst instead + cache_state.set_has_format("shards", False) + repo_cache.refresh() + + if shards_data: + # basic parse (move into caller?) + shards_index: ShardsIndexDict = msgpack.loads( + zstandard.decompress(shards_data, max_output_size=ZSTD_MAX_SHARD_SIZE) + ) # type: ignore + shards = Shards(shards_index, shards_index_url, cache) + return shards + + return None + + +def batch_retrieve_from_cache(sharded: list[Shards], packages: list[str]): + """ + Given a list of Shards objects and a list of package names, fetch all URLs + from a shared local cache, and update Shards with those per-package shards. + Return the remaining URLs that must be fetched from the network. + """ + sharded = [shardlike for shardlike in sharded if isinstance(shardlike, Shards)] + + wanted = [] + # XXX update batch_retrieve_from_cache to work with (Shards, package name) + # tuples instead of broadcasting across shards itself. + for shard in sharded: + for package_name in packages: + if package_name in shard: # and not package_name in shard.visited + wanted.append((shard, package_name, shard.shard_url(package_name))) + + log.debug("%d shards to fetch", len(wanted)) + + if not sharded: + log.debug("No sharded channels found.") + return wanted + + shared_shard_cache = sharded[0].shards_cache + from_cache = shared_shard_cache.retrieve_multiple([shard_url for *_, shard_url in wanted]) + + # add fetched Shard objects to Shards objects visited dict + for shard, package, shard_url in wanted: + if from_cache_shard := from_cache.get(shard_url): + shard.visit_shard(package, from_cache_shard) + + return wanted + + +def batch_retrieve_from_network(wanted: list[tuple[Shards, str, str]]): + """ + Given a list of (Shards, package name, shard URL) tuples, group by Shards and call fetch_shards + with a list of all URLs for that Shard. + """ + shard_packages: dict[Shards, list[str]] = defaultdict(list) + for shard, package, _ in wanted: + shard_packages[shard].append(package) + + # XXX it might be better to pull networking and Session() out of Shards(), + # so that we can e.g. use the same session for a Channel(); typically a + # noarch+arch pair of subdirs. + # Could we share a ThreadPoolExecutor and see better session utilization? + for shard, packages in shard_packages.items(): + shard.fetch_shards(packages) + + +def fetch_channels(channels: Iterable[Channel | str]) -> dict[str, ShardBase]: + """ + Return a dict mapping of a channel URL to a `Shard` or `ShardLike` object. + + Attempt to fetch the sharded index first and then fall back to retrieving + a traditional `repodata.json` file. + """ + # metaclass returns same channel, or casts to channel. + channels = [Channel(c) for c in channels] # type: ignore + + # Eliminate duplicates for example if this class is called with + # channels=[Channel(f"{load_channel}/linux-64")], + # subdirs=( + # "noarch", + # "linux-64", + # ), + url_to_channel = dict( + (channel_url, Channel(channel_url)) + for channel in channels + for channel_url in channel.urls(True, context.subdirs) + ) + + channel_data: dict[str, ShardBase] = {} + + # share single disk cache for all Shards() instances + cache = shards_cache.ShardCache(Path(conda.gateways.repodata.create_cache_dir())) + + # The parallel version may reorder channels, does this matter? + + with concurrent.futures.ThreadPoolExecutor(max_workers=_shards_connections()) as executor: + futures = { + executor.submit(fetch_shards_index, SubdirData(channel), cache): channel_url + for (channel_url, channel) in url_to_channel.items() + } + futures_non_sharded = {} + + for future in concurrent.futures.as_completed(futures): + channel_url = futures[future] + found = future.result() + if found: + channel_data[channel_url] = found + else: + futures_non_sharded[ + executor.submit( + SubdirData(Channel(channel_url)).repo_fetch.fetch_latest_parsed + ) + ] = channel_url + + # if all are None then don't do ShardLike... + + for future in concurrent.futures.as_completed(futures_non_sharded): + channel_url = futures_non_sharded[future] + repodata_json, _ = future.result() + # the filename is not strictly repodata.json since we could have + # fetched the same data from repodata.json.zst; but makes the + # urljoin consistent with shards which end with + # /repodata_shards.msgpack.zst + url = f"{channel_url}/repodata.json" + found = ShardLike(repodata_json, url) + channel_data[channel_url] = found + + return channel_data diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_cache.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e682d2b02ed0bd06c2592215e1075d294640c593 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_cache.py @@ -0,0 +1,159 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Cache suitable for shards, not allowed to change because they are named +after their own sha256 hash. +""" + +from __future__ import annotations + +import logging +import sqlite3 +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import msgpack +import zstandard +from conda.gateways.disk.delete import unlink_or_rename_to_trash + +if TYPE_CHECKING: + from pathlib import Path + + from .shards_typing import ShardDict + +log = logging.getLogger(__name__) + +SHARD_CACHE_NAME = "repodata_shards.db" +ZSTD_MAX_SHARD_SIZE = 2**20 * 16 # maximum size necessary when compresed data has no size header + + +@dataclass +class AnnotatedRawShard: + def __init__(self, url: str, package: str, compressed_shard: bytes): + # prevent easy mistake of swapping url, package + assert "://" in url + assert "://" not in package + + self.url = url + self.package = package # remove this field to avoid confusion? + self.compressed_shard = compressed_shard + + url: str + package: str + compressed_shard: bytes + + +def connect(dburi="cache.db"): + """ + Get database connection. + + dburi: uri-style sqlite database filename; accepts certain ?= parameters. + """ + conn = sqlite3.connect(dburi, uri=True) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + return conn + + +class ShardCache: + """ + Handle caching for individual shards (not the index of shards). + """ + + def __init__(self, base: Path, create=True): + """ + base: directory and filename prefix for cache. + """ + self.base = base + self.connect() + + def copy(self): + """ + Copy cache with new connection. Useful for threads. + """ + return ShardCache(self.base, create=False) + + def connect(self, create=True): + """ + Args: + create: if True, create table if not exists. + """ + dburi = (self.base / SHARD_CACHE_NAME).as_uri() + self.conn = connect(dburi) + if not create: + return + # this schema will also get confused if we merge packages into a single + # shard, but the package name should be advisory. + self.conn.execute( + "CREATE TABLE IF NOT EXISTS shards (" + "url TEXT PRIMARY KEY, package TEXT, shard BLOB, " + "timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" + ) + + def insert(self, raw_shard: AnnotatedRawShard): + """ + Args: + url: of shard + package: package name + raw_shard: msgpack.zst compressed shard data + """ + # decompress and return shard for convenience, also to validate? unless + # caller would rather retrieve the shard from another thread. + with self.conn as c: + c.execute( + "INSERT OR IGNORE INTO SHARDS (url, package, shard) VALUES (?, ?, ?)", + (raw_shard.url, raw_shard.package, raw_shard.compressed_shard), + ) + + def retrieve(self, url) -> ShardDict | None: + with self.conn as c: + row = c.execute("SELECT shard FROM shards WHERE url = ?", (url,)).fetchone() + return ( + msgpack.loads( + zstandard.decompress(row["shard"], max_output_size=ZSTD_MAX_SHARD_SIZE) + ) + if row + else None + ) # type: ignore + + def retrieve_multiple(self, urls: list[str]) -> dict[str, ShardDict | None]: + """ + Query database for cached shard urls. + + Return a dict of urls in cache mapping to the Shard or None if not present. + """ + if not urls: + return {} # this optimization does not save a noticeable amount of time. + + # In one test reusing the context saves difference between .006s and .01s + # We could make this a threadlocal. + dctx = zstandard.ZstdDecompressor() + + query = f"SELECT url, shard FROM shards WHERE url IN ({','.join(('?',) * len(urls))}) ORDER BY url" + with self.conn as c: + result: dict[str, ShardDict | None] = { + row["url"]: msgpack.loads( + dctx.decompress(row["shard"], max_output_size=ZSTD_MAX_SHARD_SIZE) + ) + if row + else None + for row in c.execute(query, urls) # type: ignore + } + return result + + def clear_cache(self): + """ + Truncate the database by removing all rows from tables + """ + with self.conn as c: + c.execute("DELETE FROM shards") + + def remove_cache(self): + """ + Remove the sharded cache database. + """ + # This function appears to support `Path()` except on Windows + # `os.rename(path, path + ".conda_trash")` fails: + self.conn.close() + unlink_or_rename_to_trash(str(self.base / SHARD_CACHE_NAME)) diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_subset.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..913bff289f33563d65fcf53c3e556186d476d747 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_subset.py @@ -0,0 +1,590 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Sharded repodata subsets. + +Traverse dependencies of installed and to-be-installed packages to generate a +useful subset for the solver. + +The algorithm developed here is a direct result of the following CEP: + +- https://conda.org/learn/ceps/cep-0016 (Sharded Repodata) + +In this algorithm we treat a (channel, package name) as a node, its dependencies +as edges. We then traverse all edges to discover all reachable (channel, package +name) tuples. The solver should be able to find a solution with only this +subset. + +This subset is overgenerous since the user is unlikely to want to install very +old packages and their dependencies. If this is too slow, we could deploy +heuristics that automatically ignore older package versions. We could also allow +the user to configure minimum versions of common packages and ignore older +versions and their dependencies, falling back to a full solve if unsatisfiable. + +We treat both sharded and monolithic repodata as if they were made up of +per-package shards, computing a subset of both. This is because it is possible +for the monolithic repodata to mention packages that exist in the true sharded +repodata but would not be found by only traversing the shards. + +We treat all repodata as sharded, even if no actual sharded repodata has been +found. + +## Example usage + +The following constructs several repodata (`noarch` and `linux-64`) from a +single channel name and a list of root packages: + +``` from conda.models.channel import Channel from +conda_libmamba_solver.shards_subset import build_repodata_subset + +channel = Channel("conda-forge-sharded/linux-64") channel_data = +build_repodata_subset(["python", "pandas"], [channel.url()]) repodata = {} + +for url in channel_data: + repodata[url] = channel_data.build_repodata() + +# ... this is what's fed to the solver ``` + +""" + +from __future__ import annotations + +import functools +import logging +import queue +import sys +import threading +from collections import deque +from concurrent.futures import Future, ThreadPoolExecutor +from contextlib import suppress +from dataclasses import dataclass +from pathlib import Path +from queue import SimpleQueue +from typing import TYPE_CHECKING + +import conda.gateways.repodata +import msgpack +import zstandard + +from conda_libmamba_solver import shards_cache +from conda_libmamba_solver.shards_cache import AnnotatedRawShard + +from .shards import ( + ZSTD_MAX_SHARD_SIZE, + Shards, + _shards_connections, + batch_retrieve_from_cache, + batch_retrieve_from_network, + fetch_channels, + shard_mentioned_packages, +) + +log = logging.getLogger(__name__) + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + from queue import SimpleQueue as Queue + from typing import Literal, TypeVar + + from conda.models.channel import Channel + + from conda_libmamba_solver.shards_cache import ShardCache + from conda_libmamba_solver.shards_typing import ShardDict + + from .shards import ( + ShardBase, + ) + +# Waiting for worker threads to shutdown cleanly, or raise error. +THREAD_WAIT_TIMEOUT = 5 # seconds +REACHABLE_PIPELINED_MAX_TIMEOUTS = 10 # number of times we can timeout waiting for shards + + +@dataclass(order=True) +class Node: + distance: int = sys.maxsize + package: str = "" + channel: str = "" + visited: bool = False + shard_url: str = "" + + def to_id(self) -> NodeId: + return NodeId(self.package, self.channel, self.shard_url) + + +@dataclass(order=True, eq=True, frozen=True) +class NodeId: + package: str + channel: str + shard_url: str = "" + + def __hash__(self): + return hash((self.package, self.channel, self.shard_url)) + + +def _nodes_from_packages( + root_packages: list[str], shardlikes: Iterable[ShardBase] +) -> Iterator[tuple[NodeId, Node]]: + """ + Yield (NodeId, Node) for all root packages found in shardlikes. + """ + for package in root_packages: + for shardlike in shardlikes: + if package in shardlike: + node = Node(0, package, shardlike.url, shard_url=shardlike.shard_url(package)) + node_id = node.to_id() + yield node_id, node + + +@dataclass +class RepodataSubset: + nodes: dict[NodeId, Node] + shardlikes: Sequence[ShardBase] + DEFAULT_STRATEGY = "pipelined" + + def __init__(self, shardlikes: Iterable[ShardBase]): + self.nodes = {} + self.shardlikes = list(shardlikes) + + @classmethod + def has_strategy(cls, strategy: str) -> bool: + """ + Return True if this class provides the named shard traversal strategy. + """ + return hasattr(cls, f"reachable_{strategy}") + + def neighbors(self, node: Node) -> Iterator[Node]: + """ + Retrieve all unvisited neighbors of a node + + Neighbors in the context are dependencies of a package + """ + discovered = set() + + for shardlike in self.shardlikes: + if node.package not in shardlike: + continue + + # check that we don't fetch the same shard twice... + shard = shardlike.fetch_shard( + node.package + ) # XXX this is the only place that in-memory (repodata.json) shards are found for the first time + + for package in shard_mentioned_packages(shard): + node_id = NodeId(package, shardlike.url) + + if node_id not in self.nodes: + self.nodes[node_id] = Node(node.distance + 1, package, shardlike.url) + yield self.nodes[node_id] + + if package not in discovered: + # now this is per package name, not per (name, channel) tuple + discovered.add(package) + + def outgoing(self, node: Node): + """ + All nodes that can be reached by this node, plus cost. + """ + # If we set a greater cost for sharded repodata than the repodata that + # is already in memory and tracked nodes as (channel, package) tuples, + # we might be able to find more shards-to-fetch-in-parallel more + # quickly. On the other hand our goal is that the big channels will all + # be sharded. + for n in self.neighbors(node): + yield n, 1 + + def reachable_bfs(self, root_packages): + """ + Fetch all packages reachable from `root_packages`' by following + dependencies using the "breadth-first search" algorithm. + + Update associated `self.shardlikes` to contain enough data to build a + repodata subset. + """ + self.nodes = dict(_nodes_from_packages(root_packages, self.shardlikes)) + + node_queue = deque(self.nodes.values()) + sharded = [s for s in self.shardlikes if isinstance(s, Shards)] + + while node_queue: + # Batch fetch all nodes at current level + to_retrieve = {node.package for node in node_queue if not node.visited} + if to_retrieve: + not_in_cache = batch_retrieve_from_cache(sharded, sorted(to_retrieve)) + batch_retrieve_from_network(not_in_cache) + + # Process one level + level_size = len(node_queue) + for _ in range(level_size): + node = node_queue.popleft() + if node.visited: # pragma: no cover + continue # we should never add visited nodes to node_queue + node.visited = True + + for next_node, _ in self.outgoing(node): + if not next_node.visited: + node_queue.append(next_node) + + def reachable_pipelined(self, root_packages): + """ + Fetch all packages reachable from `root_packages`' by following + dependencies. + + Build repodata subset using concurrent threads to follow dependencies, + fetch from cache, and fetch from network. + """ + + # Ignore cache on shards object, use our own. Necessary if there are no + # sharded channels. + cache = shards_cache.ShardCache(Path(conda.gateways.repodata.create_cache_dir())) + + cache_in_queue: SimpleQueue[list[NodeId] | None] = SimpleQueue() + shard_out_queue: SimpleQueue[list[tuple[NodeId, ShardDict]] | Exception] = SimpleQueue() + cache_miss_queue: SimpleQueue[list[NodeId] | None] = SimpleQueue() + + cache_thread = threading.Thread( + target=cache_fetch_thread, + args=(cache_in_queue, shard_out_queue, cache_miss_queue, cache), + daemon=True, # may have to set to False if we ever want to run in a subinterpreter + ) + + network_thread = threading.Thread( + target=network_fetch_thread, + args=(cache_miss_queue, shard_out_queue, cache, self.shardlikes), + daemon=True, + ) + + try: + cache_thread.start() + network_thread.start() + self.pipelined_main_thread( + root_packages, cache_in_queue, shard_out_queue, cache_thread, network_thread + ) + finally: + cache_in_queue.put(None) + # These should finish almost immediately, but if not, raise an error: + cache_thread.join(THREAD_WAIT_TIMEOUT) + network_thread.join(THREAD_WAIT_TIMEOUT) + + def pipelined_main_thread( + self, root_packages, cache_in_queue, shard_out_queue, cache_thread, network_thread + ): + """ + Run reachibility algorithm given queues to submit and receive shards. + """ + shardlikes_by_url = {s.url: s for s in self.shardlikes} + pending: set[NodeId] = set() + in_flight: set[NodeId] = set() + timeouts = 0 + shutdown_initiated = False + + self.nodes = {} + + # create start condition + parent_node = Node(0) + self.visit_node(pending, parent_node, root_packages) + + def pump(): + """ + Find shards we already have and those we need. Submit those need to + cache_in_queue, those we have to shard_out_queue. + """ + have, need = self.drain_pending(pending, shardlikes_by_url) + if need: + in_flight.update(need) + cache_in_queue.put(need) + if have: + in_flight.update(node_id for node_id, _ in have) + shard_out_queue.put(have) + return len(have) + len(need) + + running = True + while running: + pump() + try: + new_shards = shard_out_queue.get(timeout=1) + if new_shards is None: + running = False + continue # or break + if isinstance(new_shards, Exception): # error propagated from worker thread + raise new_shards + except queue.Empty: + pump_count = pump() + log.debug("Shard timeout %s, pump_count=%d", timeouts, pump_count) + log.debug("pending: %s...", sorted(str(node_id) for node_id in pending)[:10]) + log.debug("in_flight: %s...", sorted(str(node_id) for node_id in in_flight)[:10]) + log.debug("nodes: %d", len(self.nodes)) + log.debug("cache_thread.is_alive(): %s", cache_thread.is_alive()) + log.debug("network_thread.is_alive(): %s", network_thread.is_alive()) + log.debug("shard_out_queue.qsize(): %s", shard_out_queue.qsize()) + if not pending and not in_flight: + log.debug("All shards have finished processing") + break + timeouts += 1 + if timeouts > REACHABLE_PIPELINED_MAX_TIMEOUTS: + raise TimeoutError( + f"Timeout waiting for shard_out_queue after {timeouts} attempts. " + f"pending={len(pending)}, in_flight={len(in_flight)}, " + f"cache_thread_alive={cache_thread.is_alive()}, " + f"network_thread_alive={network_thread.is_alive()}" + ) + continue # immediately calls pump() at top of loop + + for node_id, shard in new_shards: + in_flight.remove(node_id) + + # add shard to appropriate ShardLike + parent_node = self.nodes[node_id] + shardlike = shardlikes_by_url[node_id.channel] + shardlike.visit_shard(node_id.package, shard) + + self.visit_node(pending, parent_node, shard_mentioned_packages(shard)) + + if not pending and not in_flight and not shutdown_initiated: + log.debug("Initiating shutdown: sending None to cache_in_queue") + cache_in_queue.put(None) + shutdown_initiated = True + + def visit_node( + self, pending: set[NodeId], parent_node: Node, mentioned_packages: Iterable[str] + ): + """Broadcast mentioned packages across channels to pending.""" + # NOTE we have visit for Nodes which is used in the graph traversal + # algorithm, and a separate visit for ShardBase which means "include + # this package in the output repodata". + for package in mentioned_packages: + for shardlike in self.shardlikes: + if package in shardlike: + new_node_id = NodeId(package, shardlike.url, shardlike.shard_url(package)) + if new_node_id not in self.nodes: + new_node = Node( + distance=parent_node.distance + 1, + package=new_node_id.package, + channel=new_node_id.channel, + shard_url=new_node_id.shard_url, + ) + self.nodes[new_node_id] = new_node + pending.add(new_node_id) + + parent_node.visited = True + + def drain_pending( + self, pending: set[NodeId], shardlikes_by_url: dict[str, ShardBase] + ) -> tuple[list[tuple[NodeId, ShardDict]], list[NodeId]]: + """ + Check pending for in-memory shards. + Clear pending. + + Return a list of shards we have and shards we need to fetch. + """ + shards_need = [] + shards_have = [] + for node_id in pending: + # we should already have these nodes. + shardlike = shardlikes_by_url[node_id.channel] + if shardlike.shard_loaded(node_id.package): # for monolithic repodata + shards_have.append((node_id, shardlike.visit_package(node_id.package))) + else: + if self.nodes[node_id].visited: # pragma: no cover + log.debug("Skip visited, should not be reached") + continue + shards_need.append(node_id) + pending.clear() + return shards_have, shards_need + + +def build_repodata_subset( + root_packages: Iterable[str], + channels: dict[str, Channel], + algorithm: Literal["bfs", "pipelined"] = RepodataSubset.DEFAULT_STRATEGY, +) -> dict[str, ShardBase]: + """ + Retrieve all necessary information to build a repodata subset. + + Params: + root_packages: iterable of installed and requested package names + channels: iterable of Channel objects + algorithm: desired traversal algorithm + """ + if isinstance(channels, dict): # True when called by LibMambaIndexHelper + channels_: list[Channel] = list(channels.values()) + else: + channels_ = channels + channel_data = fetch_channels(channels_) + + subset = RepodataSubset((*channel_data.values(),)) + getattr(subset, f"reachable_{algorithm}")(root_packages) + log.debug("%d (channel, package) nodes discovered", len(subset.nodes)) + + return channel_data + + +# region workers + +if TYPE_CHECKING: + _T = TypeVar("_T") + + +def combine_batches_until_none( + in_queue: Queue[Sequence[_T] | None], +) -> Iterator[Sequence[_T]]: + """ + Combine lists from in_queue until we see None. Yield combined lists. + """ + running = True + while running: + try: + # Add timeout to prevent indefinite blocking if producer thread fails + batch = in_queue.get(timeout=5) + if batch is None: + break + except queue.Empty: + # If we timeout, continue waiting - producer might still send data + continue + + node_ids = list(batch) + with suppress(queue.Empty): + while True: # loop exits with break or queue.Empty exception + batch = in_queue.get_nowait() + if batch is None: + # do the work but then quit + running = False + break + else: + node_ids.extend(batch) + yield node_ids + + +def exception_to_queue(func): + """ + Decorator to send unhandled exceptions to the second argument out_queue. + """ + + @functools.wraps(func) + def wrapper(in_queue, out_queue, *args, **kwargs): + try: + return func(in_queue, out_queue, *args, **kwargs) + except Exception as e: + in_queue.put(None) # signal termination + out_queue.put(e) + + return wrapper + + +@exception_to_queue +def cache_fetch_thread( + in_queue: Queue[Sequence[NodeId] | None], + shard_out_queue: Queue[Sequence[tuple[NodeId, ShardDict] | Exception] | None], + network_out_queue: Queue[Sequence[NodeId] | None], + cache: ShardCache, +): + """ + Fetch batches of shards from cache until in_queue sees None. Enqueue found + shards to shard_out_queue, and not found shards to network_out_queue. + + When we see None on in_queue, send None to both out queues and exit. + + Args: + in_queue: NodeId (URLs) to fetch. + shard_out_queue: fetched shards sent to queue. + network_out_queue: cache misses forwarded to queue. Same queue is + network_fetch_thread's in_queue. + cache: used to retrieve shards. + """ + cache = cache.copy() + + for node_ids in combine_batches_until_none(in_queue): + cached = cache.retrieve_multiple([node_id.shard_url for node_id in node_ids]) + + # should we add this into retrieve_multiple? + found: list[tuple[NodeId, ShardDict]] = [] + not_found: list[NodeId] = [] + for node_id in node_ids: + if shard := cached.get(node_id.shard_url): + found.append((node_id, shard)) + else: + not_found.append(node_id) + + # Might wake up the network thread by calling it first: + if not_found: + network_out_queue.put(not_found) + if found: + shard_out_queue.put(found) + + network_out_queue.put(None) + shard_out_queue.put(None) + + +@exception_to_queue +def network_fetch_thread( + in_queue: Queue[Sequence[NodeId | Future] | None], + shard_out_queue: Queue[list[tuple[NodeId, ShardDict] | Exception] | None], + cache: ShardCache, + shardlikes: list[ShardBase], +): + """ + Fetch shards from the network that are received on in_queue, until we see + None. + + Unhandled exceptions also go to shard_out_queue, and exit this thread. + + Args: + in_queue: NodeId (URLs) to fetch. + shard_out_queue: fetched shards sent to queue. + cache: once shards are decoded they are stored in cache. + shardlikes: list of (network-only) shard index objects. + """ + cache = cache.copy() + dctx = zstandard.ZstdDecompressor(max_window_size=ZSTD_MAX_SHARD_SIZE) + shardlikes_by_url = {s.url: s for s in shardlikes} + + def fetch(s, url: str, node_id: NodeId): + response = s.get(url) + response.raise_for_status() + data = response.content + return url, node_id, data + + def submit(node_id: NodeId): + # this worker should only receive network node_id's: + shardlike = shardlikes_by_url[node_id.channel] + if not isinstance(shardlike, Shards): + raise TypeError("network_fetch_thread got non-network shardlike") + session = shardlike.session + url = shardlikes_by_url[node_id.channel].shard_url(node_id.package) + return executor.submit(fetch, session, url, node_id) + + def handle_result(future: Future): + url, node_id, data = future.result() + log.debug("Fetch thread got %s (%s bytes)", url, len(data)) + # Decompress and parse. If it decodes as + # msgpack.zst, insert into cache. Then put "known + # good" shard into out queue. + shard: ShardDict = msgpack.loads( + dctx.decompress(data, max_output_size=ZSTD_MAX_SHARD_SIZE) + ) # type: ignore[assign] + # We could send this back into the cache thread instead to + # serialize access to sqlite3 if lock contention becomes an issue. + cache.insert(AnnotatedRawShard(url, node_id.package, data)) + shard_out_queue.put([(node_id, shard)]) + + def result_to_in_queue(future: Future): + # Simplify waiting by putting responses back into in_queue. This + # function is called in the ThreadPoolExecutor's thread, but we want to + # serialize result processing in the network_fetch_thread. + in_queue.put([future]) + + with ThreadPoolExecutor(max_workers=_shards_connections()) as executor: + for node_ids_and_results in combine_batches_until_none(in_queue): + for node_id_or_result in node_ids_and_results: + if isinstance(node_id_or_result, Future): + handle_result(node_id_or_result) + else: + future = submit(node_id_or_result) + future.add_done_callback(result_to_in_queue) + # TODO call executor.shutdown(cancel_futures=True) on error or otherwise + # prevent new HTTP requests from being started e.g. "skip" flag in + # fetch() function. Also possible to shutdown(wait=False). + + +# endregion diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_typing.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..e022694ff8a777177fcc6ce3b11f115d7be0a335 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/shards_typing.py @@ -0,0 +1,68 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +TypedDict declarations for shards. + +These are helpful for auto-complete, but do not validate at runtime and are not +normative. They are intentionally not shared with another project (conda) to +reduce coupling. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, TypedDict + +if TYPE_CHECKING: + from typing import NotRequired + + +class PackageRecordDict(TypedDict): + """ + Basic package attributes that this module cares about. + """ + + name: str + version: str + build: str + build_number: int + sha256: NotRequired[str | bytes] + md5: NotRequired[str | bytes] + depends: list[str] + constrains: NotRequired[list[str]] + noarch: NotRequired[str] + + +# in this style because "packages.conda" is not a Python identifier +ShardDict = TypedDict( + "ShardDict", + { + "packages": dict[str, PackageRecordDict], + "packages.conda": dict[str, PackageRecordDict], + }, +) + + +class RepodataInfoDict(TypedDict): # noqa: F811 + base_url: str # where packages are stored + shards_base_url: str # where shards are stored + subdir: str + + +class RepodataDict(ShardDict): + """ + Packages plus info. + """ + + info: RepodataInfoDict + repodata_version: int + + +class ShardsIndexDict(TypedDict): + """ + Shards index as deserialized from repodata_shards.msgpack.zst + """ + + info: RepodataInfoDict + version: int # TODO conda-index currently uses 'repodata_version' here + shards: dict[str, bytes] diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/solver.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/solver.py new file mode 100644 index 0000000000000000000000000000000000000000..ac2aec2c4b7ec64e8484092ea836fc8c6e32b86e --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/solver.py @@ -0,0 +1,1107 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (C) 2024 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +This module defines the conda.core.solve.Solver interface and its immediate helpers +""" + +from __future__ import annotations + +import json +import logging +import os +import re +import sys +from collections import defaultdict +from contextlib import suppress +from functools import cache +from inspect import stack +from itertools import chain +from textwrap import dedent +from typing import TYPE_CHECKING + +from conda import __version__ as _conda_version +from conda.base.constants import ( + PREFIX_FROZEN_FILE, + REPODATA_FN, + UNKNOWN_CHANNEL, + ChannelPriority, +) +from conda.base.context import context +from conda.common.constants import NULL +from conda.common.io import time_recorder +from conda.common.path import paths_equal +from conda.common.url import percent_decode +from conda.core.solve import Solver +from conda.exceptions import ( + CondaValueError, + PackagesNotFoundError, + UnsatisfiableError, +) +from conda.models.channel import Channel +from conda.models.match_spec import MatchSpec +from conda.models.records import PackageRecord, PrefixRecord +from conda.models.version import VersionOrder +from conda.reporters import get_spinner +from libmambapy.solver import Request, Solution +from libmambapy.solver.libsolv import Solver as LibsolvSolver +from libmambapy.specs import MatchSpec as LibmambaMatchSpec +from libmambapy.specs import NoArchType + +from . import __version__ +from .exceptions import LibMambaUnsatisfiableError +from .index import LibMambaIndexHelper +from .mamba_utils import ( + init_libmamba_context, + mamba_version, + problems_format_auto, + problems_format_nocolor, +) +from .state import SolverInputState, SolverOutputState + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping, Sequence + + from boltons.setutils import IndexedSet + from conda.auxlib import _Null + from conda.base.constants import ( + DepsModifier, + UpdateModifier, + ) + from conda.common.path import PathType + from libmambapy.solver.libsolv import Database, UnSolvable + from libmambapy.specs import PackageInfo + +log = logging.getLogger(f"conda.{__name__}") + + +class LibMambaSolver(Solver): + MAX_SOLVER_ATTEMPTS_CAP = 10 + _uses_ssc = False + + @staticmethod + @cache + def user_agent() -> str: + """ + Expose this identifier to allow conda to extend its user agent if required + """ + return f"conda-libmamba-solver/{__version__} libmambapy/{mamba_version()}" + + def __init__( + self, + prefix: PathType, + channels: Iterable[Channel | str], + subdirs: Iterable[str] = (), + specs_to_add: Iterable[MatchSpec | str] = (), + specs_to_remove: Iterable[MatchSpec | str] = (), + repodata_fn: str = REPODATA_FN, + command: str | _Null = NULL, + ): + if specs_to_add and specs_to_remove: + raise ValueError( + "Only one of `specs_to_add` and `specs_to_remove` can be set at a time" + ) + if specs_to_remove and command is NULL: + command = "remove" + + super().__init__( + os.fspath(prefix), + channels, + subdirs=subdirs, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + repodata_fn=repodata_fn, + command=command, + ) + if self.subdirs is NULL or not self.subdirs: + self.subdirs = context.subdirs + if "noarch" not in self.subdirs: + # Problem: Conda build generates a custom index which happens to "forget" about + # noarch on purpose when creating the build/host environments, since it merges + # both as if they were all in the native subdir. This causes package-not-found + # errors because we are not using the patched index. + # Fix: just add noarch to subdirs because it should always be there anyway. + self.subdirs = (*self.subdirs, "noarch") + + self._repodata_fn = self._maybe_ignore_current_repodata() + self._libmamba_context = init_libmamba_context( + channels=tuple(c.canonical_name for c in self.channels), + platform=next(s for s in self.subdirs if s != "noarch"), + target_prefix=str(self.prefix), + ) + + def solve_final_state( + self, + update_modifier: UpdateModifier | _Null = NULL, + deps_modifier: DepsModifier | _Null = NULL, + prune: bool | _Null = NULL, + ignore_pinned: bool | _Null = NULL, + force_remove: bool | _Null = NULL, + should_retry_solve: bool = False, + ) -> IndexedSet[PackageRecord]: + self._log_info() + in_state = SolverInputState( + prefix=self.prefix, + requested=self.specs_to_add or self.specs_to_remove, + update_modifier=update_modifier, + deps_modifier=deps_modifier, + prune=prune, + ignore_pinned=ignore_pinned, + force_remove=force_remove, + command=self._command, + ) + out_state = SolverOutputState(solver_input_state=in_state) + + # These tasks do _not_ require a solver... + maybe_final_state = out_state.early_exit() + if maybe_final_state is not None: + return maybe_final_state + + channels = self._collect_channel_list(in_state) + conda_build_channels = self._collect_channels_subdirs_from_conda_build(seen=set(channels)) + with get_spinner( + self._collect_all_metadata_spinner_message(channels, conda_build_channels), + ): + # only called here by c-l-s + index = self._collect_all_metadata( + channels=channels, + conda_build_channels=conda_build_channels, + subdirs=self.subdirs, + in_state=in_state, + ) + out_state.check_for_pin_conflicts(index) + + with get_spinner( + self._solving_loop_spinner_message(), + ): + # This function will copy and mutate `out_state` + # Make sure we get the latest copy to return the correct solution below + out_state = self._solving_loop(in_state, out_state, index) + self.neutered_specs = tuple(out_state.neutered.values()) + solution = out_state.current_solution + + # Check whether conda can be updated; this is normally done in .solve_for_diff() + # but we are doing it now so we can reuse the index + self._notify_conda_outdated(None, index, solution) + + return solution + + # region Metadata collection + ############################ + + def _collect_all_metadata_spinner_message( + self, + channels: Iterable[Channel], + conda_build_channels: Iterable[Channel | str] = (), + ) -> str: + if self._called_from_conda_build(): + msg = "Reloading output folder" + if conda_build_channels: + names = list( + dict.fromkeys([Channel(c).canonical_name for c in conda_build_channels]) + ) + msg += f" ({', '.join(names)})" + return msg + + canonical_names = list(dict.fromkeys([c.canonical_name for c in channels])) + canonical_names_dashed = "\n - ".join(canonical_names) + return ( + f"Channels:\n" + f" - {canonical_names_dashed}\n" + f"Platform: {context.subdir}\n" + f"Collecting package metadata ({self._repodata_fn})" + ) + + def _collect_channel_list(self, in_state: SolverInputState) -> list[Channel]: + # Aggregate channels and subdirs + deduped_channels = {} + for channel in chain( + self.channels, in_state.channels_from_specs(), in_state.maybe_free_channel() + ): + if channel_platform := getattr(channel, "platform", None): + if channel_platform not in self.subdirs: + log.info( + "Channel %s defines platform %s which is not part of subdirs=%s. " + "Ignoring platform attribute...", + channel, + channel_platform, + self.subdirs, + ) + # Remove 'Channel.platform' to avoid missing subdirs. Channel.urls() will ignore + # our explicitly passed subdirs if .platform is defined! + channel = Channel(**{k: v for k, v in channel.dump().items() if k != "platform"}) + deduped_channels[channel] = None + return list(deduped_channels) + + def _collect_channels_subdirs_from_conda_build( + self, + seen: set[Channel] | None = None, + ) -> list[Channel]: + if self._called_from_conda_build(): + seen = seen or set() + # We need to recover the local dirs (conda-build's local, output_folder, etc) + # from the index. This is a bit of a hack, but it works. + conda_build_channels = {} + for record in self._index or {}: + if record.channel.scheme == "file": + # Remove 'Channel.platform' to avoid missing subdirs. Channel.urls() + # will ignore our explicitly passed subdirs if .platform is defined! + channel = Channel( + **{k: v for k, v in record.channel.dump().items() if k != "platform"} + ) + if channel not in seen: + conda_build_channels.setdefault(channel) + return list(conda_build_channels) + return [] + + @time_recorder(module_name=__name__) + def _collect_all_metadata( + self, + channels: Iterable[Channel], + conda_build_channels: Iterable[Channel], + subdirs: Iterable[str], + in_state: SolverInputState | None, + ) -> LibMambaIndexHelper: + index = LibMambaIndexHelper( + channels=[*conda_build_channels, *channels], + subdirs=subdirs, + repodata_fn=self._repodata_fn, + installed_records=( + *in_state.installed.values(), + *in_state.virtual.values(), + ), + pkgs_dirs=context.pkgs_dirs if context.offline else (), + in_state=in_state, + ) + for channel in conda_build_channels: + index.reload_channel(channel) + return index + + # endregion + + # region Solving + ################ + + def _solving_loop_spinner_message(self) -> str: + """This shouldn't be our responsibility, but the CLI / app's...""" + prefix_name = os.path.basename(self.prefix) + if self._called_from_conda_build(): + if "_env" in prefix_name: + env_name = "_".join(prefix_name.split("_")[:3]) + return f"Solving environment ({env_name})" + else: + # https://github.com/conda/conda-build/blob/e0884b626a/conda_build/environ.py#L1035-L1036 + return "Getting pinned dependencies" + return "Solving environment" + + @time_recorder(module_name=__name__) + def _solving_loop( + self, + in_state: SolverInputState, + out_state: SolverOutputState, + index: LibMambaIndexHelper, + ) -> IndexedSet[PackageRecord]: + for attempt in range(1, self._max_attempts(in_state) + 1): + try: + solved, outcome = self._solve_attempt(in_state, out_state, index, attempt=attempt) + if solved: + break + except (UnsatisfiableError, PackagesNotFoundError): + solved = False + break # try with last attempt + else: # didn't solve yet, but can retry + out_state = SolverOutputState( + solver_input_state=in_state, + records=dict(out_state.records), + for_history=dict(out_state.for_history), + neutered=dict(out_state.neutered), + conflicts=dict(out_state.conflicts), + pins=dict(out_state.pins), + ) + if not solved: + log.debug("Last attempt: reporting all installed as conflicts") + out_state.conflicts.update( + { + name: record.to_match_spec() + for name, record in in_state.installed.items() + if not record.is_unmanageable + } + ) + solved, outcome = self._solve_attempt(in_state, out_state, index, attempt=attempt + 1) + if not solved: + message = self._prepare_problems_message(outcome, index.db, out_state) + exc = LibMambaUnsatisfiableError(message) + exc.allow_retry = False + raise exc + + # We didn't fail? Nice, let's return the calculated state + self._export_solution(index, out_state, outcome) + + # Run post-solve tasks + out_state.post_solve(solver=self) + + return out_state + + def _solve_attempt( + self, + in_state: SolverInputState, + out_state: SolverOutputState, + index: LibMambaIndexHelper, + attempt: int = 1, + ) -> tuple[bool, Solution | UnSolvable]: + log.info("Solver attempt: #%d", attempt) + log.debug("Current conflicts (including learnt ones): %r", out_state.conflicts) + flags = self._solver_flags(in_state) + jobs = self._specs_to_request_jobs(in_state, out_state) + request = Request(jobs=jobs, flags=flags) + solver = LibsolvSolver() + outcome = solver.solve(index.db, request) + if isinstance(outcome, Solution): + out_state.conflicts.clear() + return True, outcome + old_conflicts = out_state.conflicts.copy() + new_conflicts = self._maybe_raise_for_problems(outcome, index, out_state, old_conflicts) + if log.isEnabledFor(logging.DEBUG): + problems_as_str = outcome.problems_to_str(index.db) + log.debug( + "Attempt %d failed with %s conflicts:\n%s", + attempt, + len(new_conflicts), + problems_as_str, + ) + out_state.conflicts.update(new_conflicts) + return False, outcome + + def _solver_flags(self, in_state: SolverInputState) -> Request.Flags: + flags = { + "allow_downgrade": True, + # About flags.allow_uninstall = True: + # We used to set this to False on a global basis and then add jobs + # individually with ALLOW_UNINSTALL=True. Libmamba v2 has a Keep job instead now. + "allow_uninstall": True, + "force_reinstall": in_state.force_reinstall, + "keep_dependencies": True, + "keep_user_specs": True, + # we do the sorting ourselves, but we need it as True anyway to + # make test_solver.py::test_pytorch_gpu pass + "order_request": True, + "strict_repo_priority": context.channel_priority is ChannelPriority.STRICT, + } + if log.isEnabledFor(logging.DEBUG): + log.debug("Using solver flags:\n%s", json.dumps(flags, indent=2)) + return Request.Flags(**flags) + + def _specs_to_request_jobs( + self, + in_state: SolverInputState, + out_state: SolverOutputState, + ) -> list[Request.Job]: + if in_state.is_removing: + jobs = self._specs_to_request_jobs_remove(in_state, out_state) + elif self._called_from_conda_build(): + jobs = self._specs_to_request_jobs_conda_build(in_state, out_state) + else: + jobs = self._specs_to_request_jobs_add(in_state, out_state) + + request_jobs = [] + json_friendly = {} + for JobType, specs in jobs.items(): + for idx, conda_spec in enumerate(specs, 1): + libmamba_spec = self._conda_spec_to_libmamba_spec(conda_spec) + request_jobs.append(JobType(libmamba_spec)) + if log.isEnabledFor(logging.INFO): + json_friendly.setdefault(JobType.__name__, []).append(str(conda_spec)) + if JobType == Request.Pin: + conda_spec = MatchSpec(conda_spec) + out_state.pins[f"pin-{idx}"] = conda_spec + if log.isEnabledFor(logging.INFO): + json_str = json.dumps(json_friendly, indent=2) + log.info("The solver will handle these requests:\n%s", json_str) + return request_jobs + + def _specs_to_request_jobs_add( + self, + in_state: SolverInputState, + out_state: SolverOutputState, + ) -> dict[Request, list[MatchSpec | str]]: + tasks = defaultdict(list) + + # Protect history and aggressive updates from being uninstalled if possible. From libsolv + # docs: "The matching installed packages are considered to be installed by a user, thus not + # installed to fulfill some dependency. This is needed input for the calculation of + # unneeded packages for jobs that have the SOLVER_CLEANDEPS flag set." + user_installed = { + pkg + for pkg in ( + *in_state.history, + *in_state.aggressive_updates, + *in_state.pinned, + *in_state.do_not_remove, + ) + if pkg in in_state.installed + } + + # Fast-track python version changes (Part 1/2) + # ## When the Python version changes, this implies all packages depending on + # ## python will be reinstalled too. This can mean that we'll have to try for every + # ## installed package to result in a conflict before we get to actually solve everything + # ## A workaround is to let all non-noarch python-depending specs to "float" by marking + # ## them as a conflict preemptively + python_version_might_change = False + installed_python = in_state.installed.get("python") + to_be_installed_python = out_state.specs.get("python") + if installed_python and to_be_installed_python: + python_version_might_change = not to_be_installed_python.match(installed_python) + + for name in out_state.specs: + installed: PackageRecord = in_state.installed.get(name) + if installed: + installed_spec = self._check_spec_compat(installed.to_match_spec()) + else: + installed_spec = None + requested: MatchSpec = self._check_spec_compat(in_state.requested.get(name)) + history: MatchSpec = self._check_spec_compat(in_state.history.get(name)) + pinned: MatchSpec = self._check_spec_compat(in_state.pinned.get(name)) + conflicting: MatchSpec = self._check_spec_compat(out_state.conflicts.get(name)) + + if name in user_installed and not in_state.prune and not conflicting: + tasks[Request.Keep].append(installed_spec) + + # These specs are explicit in some sort of way + if pinned and not pinned.is_name_only_spec: + # these are the EXPLICIT pins; conda also uses implicit pinning to + # constrain updates too but those can be overridden in case of conflicts. + # name-only pins are treated as locks when installed, see below + tasks[Request.Pin].append(pinned) + # in libmamba, pins and installs are compatible tasks (pin only constrains, + # does not 'request' a package). In classic, pins were actually targeted installs + # so they were exclusive + if requested: + if requested.is_name_only_spec and pinned and not pinned.is_name_only_spec: + # for name-only specs, this is a no-op; we already added the pin above + # but we will constrain it again in the install task to have better + # error messages if not solvable + spec = pinned + else: + spec = requested + if installed: + tasks[Request.Update].append(spec) + if name not in (MatchSpec(spec).name for spec in tasks[Request.Keep]): + tasks[Request.Keep].append(name) + else: + tasks[Request.Install].append(spec) + elif name in in_state.always_update: + tasks[Request.Update].append(name) + # These specs are "implicit"; the solver logic massages them for better UX + # as long as they don't cause trouble + elif in_state.prune: + continue + elif name == "python" and installed and not pinned: + pyver = ".".join(installed.version.split(".")[:2]) + tasks[Request.Pin].append(f"python {pyver}.*") + elif history: + if conflicting and history.strictness == 3: + # relax name-version-build (strictness=3) history specs that cause conflicts + # this is called neutering and makes test_neutering_of_historic_specs pass + version = str(history.version or "") + if version.startswith("=="): + spec_str = f"{name} {version[2:]}" + elif version.startswith(("!=", ">", "<")): + spec_str = f"{name} {version}" + elif version: + spec_str = f"{name} {version}.*" + else: + spec_str = name + tasks[Request.Install].append(spec_str) + else: + tasks[Request.Install].append(history) + elif installed: + if conflicting: + # NOTE: We don't do anything now with conflicting installed. + # We rely on Flags.allow_uninstall = True doing the right thing. + # We are protecting important things with Keep or Freeze instead. + pass + else: + # we freeze everything else as installed + lock = in_state.update_modifier.FREEZE_INSTALLED + if pinned and pinned.is_name_only_spec: + # name-only pins are treated as locks when installed + lock = True + if python_version_might_change and installed.noarch is None: + for dep in installed.depends: + if MatchSpec(dep).name in ("python", "python_abi"): + lock = False + break + if lock: + tasks[Request.Freeze].append(installed_spec) + # enabling this else branch makes + # conda/conda's tests/core/test_solve.py::test_freeze_deps_1[libmamba] fail + # else: + # tasks[Request.Keep].append(name) + + # Sort tasks by priority + # This ensures that more important tasks are added to the solver first + returned_tasks = {} + for task_type in ( + Request.Pin, + Request.Install, + Request.Update, + Request.Keep, + Request.Freeze, + ): + if task_type in tasks: + returned_tasks[task_type] = tasks[task_type] + return returned_tasks + + def _specs_to_request_jobs_remove( + self, in_state: SolverInputState, out_state: SolverOutputState + ) -> dict[Request, list[MatchSpec | str]]: + # TODO: Consider merging add/remove in a single logic this so there's no split + + tasks = defaultdict(list) + + # Protect history and aggressive updates from being uninstalled if possible + for name, record in out_state.records.items(): + if name in in_state.history or name in in_state.aggressive_updates: + # MatchSpecs constructed from PackageRecords get parsed too + # strictly if exported via str(). Use .conda_build_form() directly. + spec = record.to_match_spec().conda_build_form() + tasks[Request.Keep].append(spec) + + # No complications here: delete requested and their deps + # TODO: There are some flags to take care of here, namely: + # --all + # --no-deps + # --deps-only + for name, spec in in_state.requested.items(): + spec = self._check_spec_compat(spec) + tasks[Request.Remove].append(str(spec)) + + return dict(tasks) + + def _specs_to_request_jobs_conda_build( + self, in_state: SolverInputState, out_state: SolverOutputState + ) -> dict[Request, list[MatchSpec | str]]: + tasks = defaultdict(list) + for name, spec in in_state.requested.items(): + if name.startswith("__"): + continue + spec = self._check_spec_compat(spec) + spec = self._fix_version_field_for_conda_build(spec) + tasks[Request.Install].append(spec.conda_build_form()) + + return dict(tasks) + + # endregion + + # region Export to conda + ######################## + + def _export_solution( + self, + index: LibMambaIndexHelper, + out_state: SolverOutputState, + solution: Solution, + ) -> SolverOutputState: + for action in solution.actions: + record_to_install: PackageInfo = getattr(action, "install", None) + record_to_remove: PackageInfo = getattr(action, "remove", None) + if record_to_install: + if record_to_install.name.startswith("__"): + continue + record = self._package_info_to_package_record(record_to_install, index) + out_state.records[record.name] = record + elif record_to_remove: + if record_to_remove.name.startswith("__"): + continue + record = self._package_info_to_package_record(record_to_remove, index) + out_state.records.pop(record.name, None) + return out_state + + def _package_info_to_package_record( + self, + pkg: PackageInfo, + index: LibMambaIndexHelper, + ) -> PackageRecord: + if pkg.noarch == NoArchType.Python: + noarch = "python" + elif pkg.noarch == NoArchType.Generic: + noarch = "generic" + else: + noarch = None + # The package download logic needs the URL with credentials + for repo_info in index.repos: + if pkg.package_url.startswith(repo_info.url_no_cred): + url = pkg.package_url.replace(repo_info.url_no_cred, repo_info.url_w_cred) + break + else: + url = pkg.package_url + url = percent_decode(url) + + # Signature verification requires channel information _with_ subdir data + channel = Channel(pkg.channel) + if not channel.subdir: + # conda caches channels created using single values + # Avoid the cache by using keyword arguments + channel = Channel( + scheme=channel.scheme, + auth=channel.auth, + location=channel.location, + token=channel.token, + name=channel.name, + platform=pkg.platform, + package_filename=channel.package_filename, + ) + + return PackageRecord( + name=pkg.name, + version=pkg.version, + build=pkg.build_string, # NOTE: Different attribute name + build_number=pkg.build_number, + channel=channel, + url=url, + subdir=pkg.platform, # NOTE: Different attribute name + fn=pkg.filename, # NOTE: Different attribute name + license=pkg.license, + python_site_packages_path=getattr(pkg, "python_site_packages_path", "") or None, + md5=pkg.md5, + sha256=pkg.sha256, + signatures=pkg.signatures, + track_features=pkg.track_features, + depends=pkg.dependencies, # NOTE: Different attribute name + constrains=pkg.constrains, + defaulted_keys=pkg.defaulted_keys, + noarch=noarch, + size=pkg.size, + timestamp=pkg.timestamp, + ) + + # endregion + + # region Error reporting + ######################## + + @classmethod + def _parse_problems(cls, unsolvable: UnSolvable, db: Database) -> Mapping[str, MatchSpec]: + """ + Problems can signal either unsatisfiability or unavailability. + First will raise LibmambaUnsatisfiableError. + Second will raise PackagesNotFoundError. + + Libmamba can return spec strings in two formats: + - With dashes, e.g. package-1.2.3-h5487548_0 + - à la conda-build, e.g. package 1.2.* * + - just names, e.g. package + """ + conflicts = [] + not_found = [] + problems = [] + has_unsupported = False + for problem in unsolvable.problems(db): + if problem == "unsupported request": + has_unsupported = True + else: + problems.append(problem) + if has_unsupported: # we put it at the end to prioritize other more meaningful problems + problems.append("unsupported request") + + try: + explained_problems = unsolvable.explain_problems(db, problems_format_nocolor) + except Exception as exc: + log.debug("Cannot explain problems", exc_info=exc) + explained_problems = "" + for line in problems: + words = line.split() + if "none of the providers can be installed" in line: + if words[0] != "package" or words[2] != "requires": + raise ValueError(f"Unknown message: {line}") + conflicts.append(cls._matchspec_from_error_str(words[1])) + end = words.index("but") + conflicts.append(cls._matchspec_from_error_str(words[3:end])) + elif "nothing provides" in line: + start, marker = None, None + for i, word in enumerate(words): + if word == "needed": + marker = i + elif word == "provides": + start = i + 1 + if marker is not None: + conflicts.append(cls._matchspec_from_error_str(words[-1])) + not_found.append(cls._matchspec_from_error_str(words[start:marker])) + elif "has constraint" in line and "conflicting with" in line: + # package libzlib-1.2.11-h4e544f5_1014 has constraint zlib 1.2.11 *_1014 + # conflicting with zlib-1.2.13-h998d150_0 + conflicts.append(cls._matchspec_from_error_str(words[-1])) + elif "cannot install both pin-" in line and "and pin-" in line: + # a pin is in conflict with another pin + pin_a = words[3].rsplit("-", 1)[0] + pin_b = words[5].rsplit("-", 1)[0] + conflicts.append(MatchSpec(pin_a)) + conflicts.append(MatchSpec(pin_b)) + elif "is excluded by strict repo priority" in line: + # package python-3.7.6-h0371630_2 is excluded by strict repo priority + conflicts.append(cls._matchspec_from_error_str(words[1])) + elif line == "unsupported request": + # libmamba v2 has this message for package not found errors + # we need to double check with the explained problem + for explained_line in explained_problems.splitlines(): + explained_line = explained_line.lstrip("│├└─ ").strip() + explained_words = explained_line.split() + if "does not exist" in explained_line and "which" not in explained_line: + end = explained_words.index("does") + not_found.append(cls._matchspec_from_error_str(explained_words[:end])) + break + else: + log.debug("! Problem line not recognized: %s", line) + + return { + "conflicts": {s.name: s for s in conflicts}, + "not_found": {s.name: s for s in not_found}, + } + + def _maybe_raise_for_problems( + self, + unsolvable: UnSolvable, + index: LibMambaIndexHelper, + out_state: SolverOutputState, + previous_conflicts: Mapping[str, MatchSpec] = None, + ) -> None: + parsed_problems = self._parse_problems(unsolvable, index.db) + # We allow conda-build (if present) to process the exception early + self._maybe_raise_for_conda_build( + {**parsed_problems["conflicts"], **parsed_problems["not_found"]}, + message=self._prepare_problems_message(unsolvable, index.db, out_state), + ) + + unsatisfiable = parsed_problems["conflicts"] + not_found = parsed_problems["not_found"] + if not unsatisfiable and not_found: + if log.isEnabledFor(logging.DEBUG): + log.debug( + "Inferred PackagesNotFoundError %s from conflicts:\n%s", + tuple(not_found.keys()), + unsolvable.explain_problems(index.db, problems_format_nocolor), + ) + # This is not a conflict, but a missing package in the channel + exc = PackagesNotFoundError(tuple(not_found.values()), tuple(index.channels)) + exc.allow_retry = False + raise exc + + previous = previous_conflicts or {} + previous_set = set(previous.values()) + current_set = set(unsatisfiable.values()) + + diff = current_set.difference(previous_set) + if len(diff) > 1 and "python" in unsatisfiable: + # Only report python as conflict if it's the only conflict reported + # This helps us prioritize neutering for other dependencies first + unsatisfiable.pop("python") + + if (previous and (previous_set == current_set)) or len(diff) >= 10: + # We have same or more (up to 10) unsatisfiable now! Abort to avoid recursion + message = self._prepare_problems_message(unsolvable, index.db, out_state) + exc = LibMambaUnsatisfiableError(message) + # do not allow conda.cli.install to try more things + exc.allow_retry = False + raise exc + return unsatisfiable + + def _prepare_problems_message( + self, unsolvable: UnSolvable, db: Database, out_state: SolverOutputState + ) -> str: + message = unsolvable.problems_to_str(db) + explain = True + if " - " not in message: + # This makes 'explain_problems()' crash. Anticipate. + message = "Failed with empty error message." + explain = False + elif "is excluded by strict repo priority" in message: + # This will cause a lot of warnings until implemented in detail explanations + log.info("Skipping error explanation. Excluded by strict repo priority.") + explain = False + + if explain: + try: + explained_errors = unsolvable.explain_problems(db, problems_format_auto) + message += "\n" + explained_errors + except Exception as exc: + log.warning("Failed to explain problems", exc_info=exc) + if out_state.pins and "pin on " in message: # add info about pins for easier debugging + pin_message = "Pins seem to be involved in the conflict. Currently pinned specs:\n" + for _, spec in out_state.pins.items(): + pin_message += f" - {spec}\n" + message += f"\n\n{pin_message}" + return message + + def _maybe_raise_for_conda_build( + self, + conflicting_specs: Mapping[str, MatchSpec], + message: str = None, + ) -> None: + # TODO: Remove this hack for conda-build compatibility >_< + # conda-build expects a slightly different exception format + # good news is that we don't need to retry much, because all + # conda-build envs are fresh - if we found a conflict, we report + # right away to let conda build handle it + if not self._called_from_conda_build(): + return + if not conflicting_specs: + return + from .conda_build_exceptions import ExplainedDependencyNeedsBuildingError + + # the patched index should contain the arch we are building this env for + # if the index is empty, we default to whatever platform we are running on + subdir = next((subdir for subdir in self.subdirs if subdir != "noarch"), context.subdir) + exc = ExplainedDependencyNeedsBuildingError( + packages=list(conflicting_specs.keys()), + matchspecs=list(conflicting_specs.values()), + subdir=subdir, + explanation=message, + ) + raise exc + + # endregion + + # region General helpers + ######################## + + def _log_info(self) -> None: + log.info("conda version: %s", _conda_version) + log.info("conda-libmamba-solver version: %s", __version__) + log.info("libmambapy version: %s", mamba_version()) + log.info("Target prefix: %r", self.prefix) + log.info("Command: %s", sys.argv) + + def _called_from_conda_build(self) -> bool: + """ + conda build calls the solver via `conda.plan.install_actions`, which + overrides Solver._index (populated in the classic solver, but empty for us) + with a custom index. We can use this to detect whether conda build is in use + and apply some compatibility fixes. + """ + return ( + # conda_build.environ.get_install_actions will always pass a custom 'index' + # which conda.plan.install_actions uses to override our null Solver._index + getattr(self, "_index", None) + # Is conda build in use? In that case, it should have been imported + and "conda_build" in sys.modules + # Confirm conda_build.environ's 'get_install_actions' and conda.plan's + # 'install_actions' are in the call stack. We don't check order or + # contiguousness, but what are the chances at this point...? + # frame[3] contains the name of the function in that frame of the stack + and {"install_actions", "get_install_actions"} <= {frame[3] for frame in stack()} + ) + + def _check_spec_compat(self, spec: MatchSpec | None) -> MatchSpec | None: + if spec is None: + return + spec_fields = {} + for field in spec.FIELD_NAMES: + value = spec.get_raw_value(field) + if value: + if field == "channel": + if str(value) == "": + continue + if not getattr(value, "name", ""): + # channels like http://localhost:8000 don't have a name + # this makes mamba choke so we should skip it + # however the subdir is still useful information; keep it! + if getattr(value, "platform", ""): + spec_fields["subdir"] = value.platform + continue + spec_fields[field] = value + return MatchSpec(**spec_fields) + + def _conda_spec_to_libmamba_spec(self, spec: MatchSpec) -> LibmambaMatchSpec: + return LibmambaMatchSpec.parse(str(spec)) + + @staticmethod + def _fix_version_field_for_conda_build(spec: MatchSpec) -> MatchSpec: + """Fix taken from mambabuild""" + if spec.version: + only_dot_or_digit_re = re.compile(r"^[\d\.]+$") + version_str = str(spec.version) + if re.match(only_dot_or_digit_re, version_str): + spec_fields = spec.conda_build_form().split() + if version_str.count(".") <= 1: + spec_fields[1] = version_str + ".*" + else: + spec_fields[1] = version_str + "*" + return MatchSpec(" ".join(spec_fields)) + return spec + + @staticmethod + def _matchspec_from_error_str(spec: str | Sequence[str]) -> MatchSpec: + try: + if isinstance(spec, str): + name, version, build = spec.rsplit("-", 2) + return MatchSpec(name=name, version=version, build=build) + else: + kwargs = {"name": spec[0].rstrip(",")} + if len(spec) >= 2 and spec[1] != "=*": + if spec[1].startswith("==") or not spec[1].startswith("="): + kwargs["version"] = spec[1].rstrip(",") + else: + kwargs["version"] = spec[1][1:].rstrip(",") + ".*" + if len(spec) == 3 and spec[2] != "*": + kwargs["build"] = spec[2].rstrip(",") + return MatchSpec(**kwargs) + except Exception as exc: + raise ValueError(f"Could not parse spec: {spec}") from exc + + def _maybe_ignore_current_repodata(self) -> str: + is_repodata_fn_set = False + for config in context.collect_all().values(): + for key, value in config.items(): + if key == "repodata_fns" and value: + is_repodata_fn_set = True + break + if self._repodata_fn == "current_repodata.json" and not is_repodata_fn_set: + log.debug( + "Ignoring repodata_fn='current_repodata.json', defaulting to %s", + REPODATA_FN, + ) + return REPODATA_FN + return self._repodata_fn + + def _max_attempts(self, in_state: SolverInputState, default: int = 1) -> int: + from_env_var = os.environ.get("CONDA_LIBMAMBA_SOLVER_MAX_ATTEMPTS") + installed_count = len(in_state.installed) + if from_env_var: + try: + max_attempts_from_env = int(from_env_var) + except ValueError: + raise CondaValueError( + f"CONDA_LIBMAMBA_SOLVER_MAX_ATTEMPTS='{from_env_var}'. Must be int." + ) + if max_attempts_from_env < 1: + raise CondaValueError( + f"CONDA_LIBMAMBA_SOLVER_MAX_ATTEMPTS='{max_attempts_from_env}'. Must be >=1." + ) + elif max_attempts_from_env > installed_count: + log.warning( + "CONDA_LIBMAMBA_SOLVER_MAX_ATTEMPTS='%s' is higher than the number of " + "installed packages (%s). Using that one instead.", + max_attempts_from_env, + installed_count, + ) + return installed_count + else: + return max_attempts_from_env + elif in_state.update_modifier.FREEZE_INSTALLED and installed_count: + # this the default, but can be overriden with --update-specs + # we cap at MAX_SOLVER_ATTEMPTS_CAP attempts to avoid things + # getting too slow in large environments + return min(self.MAX_SOLVER_ATTEMPTS_CAP, installed_count) + else: + return default + + def _notify_conda_outdated( + self, + link_precs: Iterable[PackageRecord], + index: LibMambaIndexHelper | None = None, + final_state: Iterable[PackageRecord] | None = None, + ) -> None: + """ + We are overriding the base class implementation, which gets called in + Solver.solve_for_diff() once 'link_precs' is available. However, we + are going to call it before (in .solve_final_state(), right after the solve). + That way we can reuse the IndexHelper and SolverOutputState instances we have + around, which contains the channel and env information we need, before losing them. + """ + if index is None and final_state is None: + # The parent class 'Solver.solve_for_diff()' method will call this method again + # with only 'link_precs' as the argument, because that's the original method signature. + # We have added two optional kwargs (index and final_state) so we can call this method + # earlier, in .solve_final_state(), while we still have access to the index helper + # (which allows us to query the available packages in the channels quickly, without + # reloading the channels with conda) and the final_state (which gives the list of + # packages to be installed). So, if both index and final_state are None, we return + # because that means that the method is being called from .solve_for_diff() and at + # that point we will have already called it from .solve_for_state(). + return + if not context.notify_outdated_conda or context.quiet: + # This check can be silenced with a specific option in the context or in quiet mode + return + + # manually check base prefix since `PrefixData(...).get("conda", None) is expensive + # once prefix data is lazy this might be a different situation + current_conda_prefix_rec = None + conda_self_installed = False + conda_frozen_file_found = os.path.exists( + os.path.join(context.root_prefix, PREFIX_FROZEN_FILE) + ) + conda_meta_prefix_directory = os.path.join(context.root_prefix, "conda-meta") + with suppress(OSError, ValueError): + if os.path.lexists(conda_meta_prefix_directory): + for entry in os.scandir(conda_meta_prefix_directory): + if entry.is_file() and entry.name.endswith(".json"): + package_name = entry.name.rsplit("-", 2)[0] + if package_name == "conda": + with open(entry.path) as f: + current_conda_prefix_rec = PrefixRecord(**json.loads(f.read())) + elif package_name == "conda-self": + conda_self_installed = True + if conda_self_installed and current_conda_prefix_rec is not None: + # conda-self is installed and current conda has been found, no more information needed + break + + if not current_conda_prefix_rec: + # We are checking whether conda can be found in the environment conda is + # running from. Unless something is really wrong, this should never happen. + return + + channel_name = current_conda_prefix_rec.channel.canonical_name + if channel_name in (UNKNOWN_CHANNEL, "@", "", "pypi"): + channel_name = "defaults" + + # only check the loaded index if it contains the channel conda should come from + # otherwise ignore + index_channels = {getattr(chn, "canonical_name", chn) for chn in index.channels} + if channel_name not in index_channels: + return + + # we only want to check if a newer conda is available in the channel we installed it from + conda_newer_str = f"{channel_name}::conda>{_conda_version}" + conda_newer_spec = MatchSpec(conda_newer_str) + + # if target prefix is the same conda is running from + # maybe the solution we are proposing already contains + # an updated conda! in that case, we don't need to check further + if paths_equal(self.prefix, context.conda_prefix): + if any(conda_newer_spec.match(record) for record in final_state): + return + + # check if the loaded index contains records that match a more recent conda version + conda_newer_records = index.search(conda_newer_str) + + # print instructions to stderr if we found a newer conda + if conda_newer_records: + newest = max(conda_newer_records, key=lambda x: VersionOrder(x.version)) + conda_update_message = f"conda update -n base -c {channel_name} conda" + if conda_frozen_file_found: + if conda_self_installed: + conda_update_message = "conda self update" + else: + conda_update_message += " --override-frozen" + + print( + dedent( + f""" + + ==> WARNING: A newer version of conda exists. <== + current version: {_conda_version} + latest version: {newest.version} + + Please update conda by running + + $ {conda_update_message} + + """ + ), + file=sys.stderr, + ) + + # endregion diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/state.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/state.py new file mode 100644 index 0000000000000000000000000000000000000000..3214fa76f8ef2b8bd958f22666c119c8b9aecdf3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/state.py @@ -0,0 +1,782 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Solver-agnostic logic to compose the requests passed to the solver +and accumulate its results. + +The state exposed to the solver is handled by two objects whose primary +function is to serve read-only information to the solver and its other helpers. + +- ``SolverInputState``: fully solver agnostic. It handles: + - The local state on disk, namely the prefix state. This includes the + already installed packages in the prefix (if any), the explicit requests + made in that prefix in the past (history), its pinned specs, packages + configured as aggressive updates and others. + - The runtime context, determined by the configuration file(s), + `CONDA_*` environment variables, command line flags and the requested + specs (if any). +- ``IndexHelper``: can be subclassed to add solver-specific logic + (e.g. custom index building). It should, provide, at least, a method to + query the index for the _explicit pool_ of packages for a given spec (e.g. + its potential dependency tree). Note that the IndexHelper might need + pieces of ``SolverInputState`` to build the index (e.g. installed packages, + configured channels and subdirs...) + +.. todo:: + + Embed IndexHelper in SolverInputState? + +Since ``conda`` follows an iterative approach to solve a request, +in addition the _input_ state, the Solver itself can store additional state +in a separate helper: the ``SolverOutputState`` object. This is meant to help +accumulate the following pieces of data: + +- ``specs``: a mapping of package names to its corresponding ``MatchSpec`` + objects. These objects are passed to the actual Solver, hoping it will return + a solution. +- ``records``: a mapping of package names to ``PackageRecord`` objects. It will + end up containing the list of package records that will compose the final state + of the prefix (the _solution_). Its default value is set to the currently installed + packages in the prefix. The solver will alter this list as needed to accommodate + the final solution. + +If the algorithm was not iterative, the sole purpose of the solver would be to turn +the ``specs`` into ``records``. However, ``conda``'s logic will try to constrain the +solution to mimic the initial state as much as possible to reduce the amount of +changes in the prefix. Sometimes, the initial request is too constrained, which results +in a number of conflicts. These conflicts are then stored in the ``conflicts`` mapping, +which will determine which ``specs`` are relaxed in the next attempt. Additionally, +``conda`` stores other solve artifacts: + +- ``for_history``: The explicitly requested specs in the command-line should end up + in the history. Some modifier flags can affect how this mapping is populated (e.g. + ``--update-deps``.) +- ``neutered``: Pieces of history that were found to be conflicting in the future and + were annotated as such to avoid falling in the same conflict again. + +The mappings stored in ``SolverOutputState`` are backed by ``TrackedMap`` objects, +which allow to keep the reasons _why_ those specs or records were added to the mappings, +as well as richer logging for each action. +""" +# TODO: This module could be part of conda-core once if we refactor the classic logic + +from __future__ import annotations + +import logging +from types import MappingProxyType +from typing import TYPE_CHECKING + +from boltons.setutils import IndexedSet +from conda.auxlib import NULL +from conda.base.constants import DepsModifier, UpdateModifier +from conda.base.context import context +from conda.common.path import paths_equal +from conda.core.index import Index +from conda.core.prefix_data import PrefixData +from conda.core.solve import get_pinned_specs +from conda.exceptions import PackagesNotFoundError, SpecsConfigurationConflictError +from conda.history import History +from conda.models.channel import Channel +from conda.models.match_spec import MatchSpec +from conda.models.prefix_graph import PrefixGraph + +if TYPE_CHECKING: + from collections.abc import Iterable + from os import PathLike + from typing import Any + + from conda.core.solve import Solver + from conda.models.records import PackageRecord + + from .index import LibMambaIndexHelper + +from .utils import EnumAsBools, compatible_specs + +log = logging.getLogger(f"conda.{__name__}") + + +class SolverInputState: + """ + Helper object to provide the input data needed to compute the state that will be + exposed to the solver. + + Parameters + ---------- + prefix + Path to the prefix we are operating on. This will be used to expose + ``PrefixData``, ``History``, pinned specs, among others. + requested + The MatchSpec objects required by the user (either in the command line or + through the Python API). + update_modifier + A value of ``UpdateModifier``, which has an effect on which specs are added + to the final list. The default value here must match the default value in the + ``context`` object. + deps_modifier + A value of ``DepsModifier``, which has an effect on which specs are added + to the final list. The default value here must match the default value in the + ``context`` object. + ignore_pinned + Whether pinned specs can be ignored or not. The default value here must match + the default value in the ``context`` object. + force_remove + Remove the specs without solving the environment (which would also remove their) + dependencies. The default value here must match the default value in the + ``context`` object. + force_reinstall + Uninstall and install the computed records even if they were already satisfied + in the given prefix. The default value here must match the default value in the + ``context`` object. + prune + Remove dangling dependencies that ended up orphan. The default value here must + match the default value in the ``context`` object. + command + The subcommand used to invoke this operation (e.g. ``create``, ``install``, ``remove``...). + It can have an effect on the computed list of records. + _pip_interop_enabled + Internal only. Whether ``PrefixData`` will also expose packages not installed by + ``conda`` (e.g. ``pip`` and others can put Python packages in the prefix). + """ + + _ENUM_STR_MAP = { + "NOT_SET": DepsModifier.NOT_SET, + "NO_DEPS": DepsModifier.NO_DEPS, + "ONLY_DEPS": DepsModifier.ONLY_DEPS, + "SPECS_SATISFIED_SKIP_SOLVE": UpdateModifier.SPECS_SATISFIED_SKIP_SOLVE, + "FREEZE_INSTALLED": UpdateModifier.FREEZE_INSTALLED, + "UPDATE_DEPS": UpdateModifier.UPDATE_DEPS, + "UPDATE_SPECS": UpdateModifier.UPDATE_SPECS, + "UPDATE_ALL": UpdateModifier.UPDATE_ALL, + } + _DO_NOT_REMOVE_NAMES = ( + "anaconda", + "conda", + "conda-build", + "python.app", + "console_shortcut", + "powershell_shortcut", + ) + + def __init__( + self, + prefix: str | bytes | PathLike, + requested: Iterable[str | MatchSpec] | None = (), + update_modifier: UpdateModifier | None = UpdateModifier.UPDATE_SPECS, + deps_modifier: DepsModifier | None = DepsModifier.NOT_SET, + ignore_pinned: bool | None = None, + force_remove: bool | None = False, + force_reinstall: bool | None = False, + prune: bool | None = False, + command: str | None = None, + _pip_interop_enabled: bool | None = None, + ): + self.prefix = prefix + self._prefix_data = PrefixData(prefix, interoperability=_pip_interop_enabled) + self._pip_interop_enabled = _pip_interop_enabled + self._history = History(prefix).get_requested_specs_map() + self._pinned = {spec.name: spec for spec in get_pinned_specs(prefix)} + self._aggressive_updates = {spec.name: spec for spec in context.aggressive_update_packages} + + virtual = Index().system_packages + self._virtual = {record.name: record for record in virtual} + + self._requested = {} + for spec in requested: + spec = MatchSpec(spec) + self._requested[spec.name] = spec + + self._update_modifier = self._default_to_context_if_null( + "update_modifier", update_modifier + ) + if prune and self._update_modifier == UpdateModifier.FREEZE_INSTALLED: + self._update_modifier = UpdateModifier.UPDATE_SPECS # revert to default + self._deps_modifier = self._default_to_context_if_null("deps_modifier", deps_modifier) + self._ignore_pinned = self._default_to_context_if_null("ignore_pinned", ignore_pinned) + self._force_remove = self._default_to_context_if_null("force_remove", force_remove) + self._force_reinstall = self._default_to_context_if_null( + "force_reinstall", force_reinstall + ) + self._prune = prune + self._command = command + + # special cases + self._do_not_remove = {p: MatchSpec(p) for p in self._DO_NOT_REMOVE_NAMES} + + def _default_to_context_if_null(self, name, value, context=context) -> Any: + "Obtain default value from the context if value is set to NULL; otherwise leave as is" + return getattr(context, name) if value is NULL else self._ENUM_STR_MAP.get(value, value) + + @property + def prefix_data(self) -> PrefixData: + """ + A direct reference to the ``PrefixData`` object for the given ``prefix``. + You will usually use this object through the ``installed`` property. + """ + return self._prefix_data + + # Prefix state pools + + @property + def installed(self) -> dict[str, PackageRecord]: + """ + This exposes the installed packages in the prefix. Note that a ``PackageRecord`` + can generate an equivalent ``MatchSpec`` object with ``.to_match_spec()``. + Records are toposorted. + """ + return MappingProxyType(dict(sorted(self.prefix_data._prefix_records.items()))) + + @property + def history(self) -> dict[str, MatchSpec]: + """ + These are the specs that the user explicitly asked for in previous operations + on the prefix. See :class:`History` for more details. + """ + return MappingProxyType(self._history) + + @property + def pinned(self) -> dict[str, MatchSpec]: + """ + These specs represent hard constrains on what package versions can be installed + on the environment. The packages here returned don't need to be already installed. + + If ``ignore_pinned`` is True, this returns an empty dictionary. + """ + if self.ignore_pinned: + return MappingProxyType({}) + return MappingProxyType(self._pinned) + + @property + def virtual(self) -> dict[str, MatchSpec]: + """ + System properties exposed as virtual packages (e.g. ``__glibc=2.17``). These packages + cannot be (un)installed, they only represent constrains for other packages. By convention, + their names start with a double underscore. + """ + return MappingProxyType(dict(sorted(self._virtual.items()))) + + @property + def aggressive_updates(self) -> dict[str, MatchSpec]: + """ + Packages that the solver will always try to update. As such, they will never have an + associated version or build constrain. Note that the packages here returned do not need to + be installed. + """ + return MappingProxyType(self._aggressive_updates) + + @property + def always_update(self) -> dict[str, MatchSpec]: + """ + Merged lists of packages that should always be updated, depending on the flags, including: + - aggressive_updates + - conda if auto_update_conda is true and we are on the base env + - almost all packages if update_all is true + - etc + """ + installed = self.installed + pinned = self.pinned + pkgs = {pkg: MatchSpec(pkg) for pkg in self.aggressive_updates if pkg in installed} + if context.auto_update_conda and paths_equal(self.prefix, context.root_prefix): + pkgs.setdefault("conda", MatchSpec("conda")) + if self.update_modifier.UPDATE_ALL: + for pkg in installed: + if pkg != "python" and pkg not in pinned: + pkgs.setdefault(pkg, MatchSpec(pkg)) + return MappingProxyType(pkgs) + + @property + def do_not_remove(self) -> dict[str, MatchSpec]: + """ + Packages that are protected by the solver so they are not accidentally removed. This list + is not configurable, but hardcoded for legacy reasons. + """ + return MappingProxyType(self._do_not_remove) + + @property + def requested(self) -> dict[str, MatchSpec]: + """ + Packages that the user has explicitly asked for in this operation. + """ + return MappingProxyType(self._requested) + + # Types of commands + + @property + def is_installing(self) -> bool: + """ + True if the used subcommand was ``install``. + """ + return self._command == "install" + + @property + def is_updating(self) -> bool: + """ + True if the used subcommand was ``update``. + """ + return self._command == "update" + + @property + def is_creating(self) -> bool: + """ + True if the used subcommand was ``create``. + """ + return self._command == "create" + + @property + def is_removing(self) -> bool: + """ + True if the used subcommand was ``remove``. + """ + return self._command == "remove" + + # modifiers + + @property + def update_modifier(self) -> EnumAsBools: + """ + Use attribute access to test whether the modifier is set to that value + + >>> update_modifier = EnumAsBools(context.update_modifier) + >>> update_modifier.UPDATE_SPECS + True + >>> update_modifier.UPDATE_DEPS + False + """ + return EnumAsBools(self._update_modifier) + + @property + def deps_modifier(self) -> EnumAsBools: + """ + Use attribute access to test whether the modifier is set to that value + + >>> deps_modifier = EnumAsBools(context.deps_modifier) + >>> deps_modifier.NOT_SET + True + >>> deps_modifier.DEPS_ONLY + False + """ + return EnumAsBools(self._deps_modifier) + + # Other flags + + @property + def ignore_pinned(self) -> bool: + return self._ignore_pinned + + @property + def force_remove(self) -> bool: + return self._force_remove + + @property + def force_reinstall(self) -> bool: + return self._force_reinstall + + @property + def prune(self) -> bool: + return self._prune + + #  Utility methods + + def channels_from_specs(self) -> Iterable[Channel]: + """ + Collect all channels added with the `channel::package=*` syntax. For now, + we only collect those specifically requested by the user in the current command + (same as conda), but we should investigate whether history keeps channels around + too. + """ + for spec in self.requested.values(): + channel = spec.get_exact_value("channel") + if channel: + if spec.original_spec_str and spec.original_spec_str.startswith("file://"): + # Handle MatchSpec roundtrip issue with local channels + channel = Channel(spec.original_spec_str.split("::")[0]) + yield channel + + def maybe_free_channel(self) -> Iterable[Channel]: + # FUTURE: conda 25.9+ remove restore_free_channel + if channel := getattr(context, "_restore_free_channel", None): + context.custom_multichannels # force deprecation warning + elif channel is None: + channel = getattr(context, "restore_free_channel", None) + + if channel: + yield Channel.from_url("https://repo.anaconda.com/pkgs/free") + + +class SolverOutputState: + """ + This is the main mutable object we will massage before passing the result of the computation + (the ``specs`` mapping) to the solver. It will also store the result of the solve (in + ``records``). + + Parameters + ---------- + solver_input_state + This instance provides the initial state for the output. + records + Dict of package names to ``PackageRecord`` objects. If not provided, it will be + initialized from the ``installed`` records in ``solver_input_state``. + for_history + Dict of package names to ``MatchSpec`` objects. These specs will be written to + the prefix history once the solve is complete. Its default initial value is taken from the + explicitly requested packages in the ``solver_input_state`` instance. + neutered + Dict of package names to ``MatchSpec`` objects. These specs are also written to + the prefix history, as part of the neutered specs. If not provided, their default value is + a blank mapping. + conflicts + If a solve attempt is not successful, conflicting specs are kept here for further + relaxation of the version and build constrains. If not provided, their default value is a + blank mapping. + pins + Packages that ended up being pinned. Mostly used for reporting and debugging. Deprecated. + + Notes + ----- + Almost all the attributes in this object map package names (``str``) to ``MatchSpec`` + (_specs_ in short) objects. The only mapping with different values is ``records``, which + stores ``PackageRecord`` objects. A quick note on these objects: + + * ``MatchSpec`` objects are a query language for packages, based on the ``PackageRecord`` + schema. ``PackageRecord`` objects is how packages that are already installed are + represented. This is what you get from ``PrefixData.iter_records()``. Since they are + related, ``MatchSpec`` objects can be created from a ``PackageRecord`` with + ``.to_match_spec()``. + * ``MatchSpec`` objects also feature fields like ``target`` and ``optional``. These are, + essentially, used by the low-level classic solver (:class:`conda.resolve.Resolve`) to + mark specs as items it can optionally play with to satisfy the solver constrains. A + ``target`` marked spec is _soft-pinned_ in the sense that the solver will try to satisfy + that but it will stop trying if it gets in the way, so you might end up a different + version or build. ``optional`` seems to be in the same lines, but maybe the entire spec + can be dropped from the request? The key idea here is that these two fields might not be + directly usable by the solver, but it might need some custom adaptation. For example, for + ``libmamba`` we might need a separate pool that can be configured as a flexible task. See + more details in the first comment of ``conda.core.solve.classic.Solver._add_specs`` + """ + + def __init__( + self, + *, + solver_input_state: SolverInputState, + records: dict[str, PackageRecord] | None = None, + for_history: dict[str, MatchSpec] | None = None, + neutered: dict[str, MatchSpec] | None = None, + conflicts: dict[str, MatchSpec] | None = None, + pins: dict[str, MatchSpec] | None = None, + ): + self.solver_input_state: SolverInputState = solver_input_state + self.records: dict[str, PackageRecord] = records or dict(solver_input_state.installed) + self.for_history: dict[str, MatchSpec] = for_history or dict(solver_input_state.requested) + self.neutered: dict[str, MatchSpec] = neutered or {} + self.conflicts: dict[str, MatchSpec] = conflicts or {} + self.pins: dict[str, MatchSpec] = pins or {} + + @property + def current_solution(self) -> IndexedSet[PackageRecord]: + """ + Massage currently stored records so they can be returned as the type expected by the + solver API. This is what you should return in ``Solver.solve_final_state()``. + """ + return IndexedSet(PrefixGraph(self.records.values()).graph) + + @property + def specs(self) -> dict[str, MatchSpec]: + """ + Merge all possible sources of input package specs, sorted by their input category and + strictness. It's just meant to be an enumeration of all possible inputs, not a ready-to-use + list of specs for a solver. + """ + sis = self.solver_input_state + specs_by_strictness = {} + for group in ( + "requested", + "pinned", + "history", + "aggressive_updates", + ): + for name, spec in sorted( + getattr(sis, group).items(), + key=sort_by_spec_strictness, + reverse=True, + ): + specs_by_strictness.setdefault(name, spec) + for record_group in ("installed", "virtual"): + for name, record in getattr(sis, record_group).items(): + specs_by_strictness.setdefault(name, record.to_match_spec()) + return specs_by_strictness + + @property + def real_specs(self) -> dict[str, MatchSpec]: + """ + Specs that are _not_ virtual. + """ + return {name: spec for name, spec in self.specs.items() if not name.startswith("__")} + + @property + def virtual_specs(self) -> dict[str, MatchSpec]: + """ + Specs that are virtual. + """ + return {name: spec for name, spec in self.specs.items() if name.startswith("__")} + + def early_exit(self) -> IndexedSet[PackageRecord] | None: + """ + Operations that do not need a solver and might result in returning + early are collected here. + """ + sis = self.solver_input_state + if sis.is_removing: + # Make sure that requested packages to be removed match + # an installed record. Otherwise, raise an error. + # When 'remove --force' is set, remove the package without solving. + if sis.force_remove: + force_remove_solution = self.current_solution + not_installed: list[MatchSpec] = [] + for name, spec in sis.requested.items(): + for record in sis.installed.values(): + if spec.match(record): + if sis.force_remove: + force_remove_solution.remove(record) + break + else: + not_installed.append(spec) + + if not_installed: + exc = PackagesNotFoundError(not_installed) + exc.allow_retry = False + raise exc + + if sis.force_remove: + return force_remove_solution + elif sis.update_modifier.SPECS_SATISFIED_SKIP_SOLVE: + for name, spec in sis.requested.items(): + if name not in sis.installed: + break + if not any(spec.match(record) for record in sis.installed.values()): + break + else: + # All specs match a package in the current environment. + # Return early, with the current solution (at this point, .records is set + # to the map of installed packages) + return self.current_solution + + def check_for_pin_conflicts(self, index: LibMambaIndexHelper) -> None: + """ + Last part of the logic, common to addition and removal of packages. Originally, + the legacy logic will also minimize the conflicts here by doing a pre-solve + analysis, but so far we have opted for a different approach in libmamba: let the + solver try, fail with conflicts, and annotate those as such so they are unconstrained. + + Now, this method only ensures that the pins do not cause conflicts. + """ + # ## Inconsistency analysis ### + # here we would call conda.core.solve.classic.Solver._find_inconsistent_packages() + + # ## Check pin and requested are compatible + sis = self.solver_input_state + requested_and_pinned = set(sis.requested).intersection(sis.pinned) + for name in requested_and_pinned: + requested = sis.requested[name] + pin = sis.pinned[name] + installed = sis.installed.get(name) + if ( + # name-only pins lock to installed; requested spec must match it + (pin.is_name_only_spec and installed and not requested.match(installed)) + # otherwise, the pin needs to be compatible with the requested spec + or not compatible_specs(index, (requested, pin)) + ): + pinned_specs = [ + (sis.installed.get(name, pin) if pin.is_name_only_spec else pin) + for name, pin in sorted(sis.pinned.items()) + ] + exc = SpecsConfigurationConflictError( + requested_specs=sorted(sis.requested.values(), key=lambda x: x.name), + pinned_specs=pinned_specs, + prefix=sis.prefix, + ) + exc.allow_retry = False + raise exc + + def post_solve(self, solver: Solver) -> None: + """ + These tasks are performed _after_ the solver has done its work. It essentially + post-processes the ``records`` mapping. + + Parameters + ---------- + solver_cls + The class used to instantiate the Solver. If not provided, defaults to the one + specified in the context configuration. + + Notes + ----- + This method could be solver-agnostic but unfortunately ``--update-deps`` requires a + second solve; that's why this method needs a solver class to be passed as an argument. + """ + # After a solve, we still need to do some refinement + sis = self.solver_input_state + + # ## Record history ### + # user requested specs need to be annotated in history + # we control that in .for_history + self.for_history.update(sis.requested) + + # ## Neutered ### + # annotate overridden history specs so they are written to disk + for name, spec in sis.history.items(): + record = self.records.get(name) + if record and not spec.match(record): + self.neutered[name] = MatchSpec(name, version=record.version) + + # ## Add inconsistent packages back ### + # direct result of the inconsistency analysis above + + # ## Deps modifier ### + # handle the different modifiers (NO_DEPS, ONLY_DEPS, UPDATE_DEPS) + # this might mean removing different records by hand or even calling + # the solver a 2nd time + + if sis.deps_modifier.NO_DEPS: + # In the NO_DEPS case, we need to start with the original list of packages in the + # environment, and then only modify packages that match the requested specs + # + # Help information notes that use of NO_DEPS is expected to lead to broken + # environments. + original_state = dict(sis.installed) + only_change_these = {} + for name, spec in sis.requested.items(): + for record in self.records.values(): + if spec.match(record): + only_change_these[name] = record + + if sis.is_removing: + # TODO: This could be a pre-solve task to save time in forced removes? + for name in only_change_these: + del original_state[name] + else: + for name, record in only_change_these.items(): + original_state[name] = record + + self.records.clear() + self.records.update(original_state) + + elif sis.deps_modifier.ONLY_DEPS and not sis.update_modifier.UPDATE_DEPS: + # Using a special instance of PrefixGraph to remove youngest child nodes that match + # the original requested specs. It's important to remove only the *youngest* child + # nodes, because a typical use might be `conda install --only-deps python=2 flask`, + # and in that case we'd want to keep python. + # + # What are we supposed to do if flask was already in the environment? + # We can't be removing stuff here that's already in the environment. + # + # What should be recorded for the user-requested specs in this case? Probably all + # direct dependencies of flask. + + graph = PrefixGraph(self.records.values(), sis.requested.values()) + # this method below modifies the graph inplace _and_ returns the removed nodes + # (like dict.pop()) + would_remove = graph.remove_youngest_descendant_nodes_with_specs() + + # We need to distinguish the behavior between `conda remove` and the rest + to_remove = [] + if sis.is_removing: + for record in would_remove: + # do not remove records that were not requested but were installed + if record.name not in sis.requested and record.name in sis.installed: + continue + to_remove.append(record.name) + else: + for record in would_remove: + for dependency in record.depends: + spec = MatchSpec(dependency) + if spec.name not in self.specs: + # following https://github.com/conda/conda/pull/8766 + self.for_history[spec.name] = spec + to_remove.append(record.name) + + for name in to_remove: + installed = sis.installed.get(name) + if installed: + self.records[name] = installed + else: + self.records.pop(name, None) + + elif sis.update_modifier.UPDATE_DEPS: + # Here we have to SAT solve again :( It's only now that we know the dependency + # chain of specs_to_add. + # + # UPDATE_DEPS is effectively making each spec in the dependency chain a + # user-requested spec. For all other specs, we drop all information but name, drop + # target, and add them to `requested` so it gets recorded in the history file. + # + # It's like UPDATE_ALL, but only for certain dependency chains. + new_specs = {} + + graph = PrefixGraph(self.records.values()) + for name, spec in sis.requested.items(): + record = graph.get_node_by_name(name) + for ancestor in graph.all_ancestors(record): + new_specs[ancestor.name] = MatchSpec(ancestor.name) + + # Remove pinned_specs + for name, spec in sis.pinned.items(): + new_specs.pop(name, None) + # Follow major-minor pinning business rule for python + if "python" in new_specs: + record = sis.installed["python"] + version = ".".join(record.version.split(".")[:2]) + ".*" + new_specs["python"] = MatchSpec(name="python", version=version) + # Add in the original `requested` on top. + new_specs.update(sis.requested) + + if sis.is_removing: + specs_to_add = () + specs_to_remove = list(new_specs.keys()) + else: + specs_to_add = list(new_specs.values()) + specs_to_remove = () + + with context._override("quiet", False): + # Create a new solver instance to perform a 2nd solve with deps added We do it + # like this to avoid overwriting state accidentally. Instead, we will import + # the needed state bits manually. + records = solver.__class__( + prefix=solver.prefix, + channels=solver.channels, + subdirs=solver.subdirs, + specs_to_add=specs_to_add, + specs_to_remove=specs_to_remove, + command="recursive_call_for_update_deps", + ).solve_final_state( + update_modifier=UpdateModifier.UPDATE_SPECS, # avoid recursion! + deps_modifier=sis._deps_modifier, + ignore_pinned=sis.ignore_pinned, + force_remove=sis.force_remove, + prune=sis.prune, + ) + records = {record.name: record for record in records} + + self.records.clear() + self.records.update(records) + self.for_history.clear() + self.for_history.update(new_specs) + + # Disable pruning regardless the original value + # TODO: Why? Dive in https://github.com/conda/conda/pull/7719 + sis._prune = False + + # ## Prune ### + # remove orphan leaves in the graph + if sis.prune: + graph = PrefixGraph(list(self.records.values()), list(sis.requested.values())) + graph.prune() + self.records.clear() + self.records.update({record.name: record for record in graph.graph}) + + +def sort_by_spec_strictness(key_value_tuple: tuple[str, MatchSpec]) -> tuple[int, str]: + """ + Helper function to sort a list of (key, value) tuples by spec strictness + """ + name, spec = key_value_tuple + return getattr(spec, "strictness", 0), name diff --git a/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/utils.py b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa5c4038c39b2cad1daaacee7ebf2c69875a520 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_libmamba_solver/utils.py @@ -0,0 +1,118 @@ +# Copyright (C) 2022 Anaconda, Inc +# Copyright (C) 2023 conda +# SPDX-License-Identifier: BSD-3-Clause +""" +Miscellaneous utilities +""" + +from __future__ import annotations + +from logging import getLogger +from typing import TYPE_CHECKING +from urllib.parse import quote + +from conda.common.compat import on_win +from conda.common.url import urlparse +from conda.exceptions import PackagesNotFoundError + +if TYPE_CHECKING: + from collections.abc import Iterable + from enum import Enum + + from conda.models.match_spec import MatchSpec + + from .index import LibMambaIndexHelper + +log = getLogger(f"conda.{__name__}") + + +def escape_channel_url(channel: str) -> str: + if channel.startswith("file:"): + if "%" in channel: # it's escaped already + return channel + if on_win: + channel = channel.replace("\\", "/") + parts = urlparse(channel) + if parts.scheme: + components = parts.path.split("/") + if on_win: + if parts.netloc and len(parts.netloc) == 2 and parts.netloc[1] == ":": + # with absolute paths (e.g. C:/something), C:, D:, etc might get parsed as netloc + path = "/".join([parts.netloc] + [quote(p) for p in components]) + parts = parts.replace(netloc="") + else: + path = "/".join(components[:2] + [quote(p) for p in components[2:]]) + else: + path = "/".join([quote(p) for p in components]) + parts = parts.replace(path=path) + return str(parts) + return channel + + +def compatible_specs( + index: LibMambaIndexHelper, specs: Iterable[MatchSpec], raise_not_found: bool = True +) -> bool: + """ + Assess whether the given specs are compatible with each other. + This is done by querying the index for each spec and taking the + intersection of the results. If the intersection is empty, the + specs are incompatible. + + If raise_not_found is True, a PackagesNotFoundError will be raised + when one of the specs is not found. Otherwise, False will be returned + because the intersection will be empty. + """ + if not len(specs) >= 2: + raise ValueError("Must specify at least two specs") + + matched = None + for spec in specs: + results = set(index.search(spec)) + if not results: + if raise_not_found: + exc = PackagesNotFoundError([spec], index.channels) + exc.allow_retry = False + raise exc + return False + if matched is None: + # First spec, just set matched to the results + matched = results + continue + # Take the intersection of the results + matched &= results + if not matched: + return False + + return bool(matched) + + +class EnumAsBools: + """ + Allows an Enum to be bool-evaluated with attribute access. + + >>> update_modifier = UpdateModifier("update_deps") + >>> update_modifier_as_bools = EnumAsBools(update_modifier) + >>> update_modifier == UpdateModifier.UPDATE_DEPS # from this + True + >>> update_modidier_as_bools.UPDATE_DEPS # to this + True + >>> update_modifier_as_bools.UPDATE_ALL + False + """ + + def __init__(self, enum: Enum): + self._enum = enum + self._names = {v.name for v in self._enum.__class__.__members__.values()} + + def __getattr__(self, name: str) -> bool: + if name in ("name", "value"): + return getattr(self._enum, name) + if name in self._names: + return self._enum.name == name + raise AttributeError(f"'{name}' is not a valid name for {self._enum.__class__.__name__}") + + def __eq__(self, obj: object) -> bool: + return self._enum.__eq__(obj) + + def _dict(self) -> dict[str, bool]: + return {name: self._enum.name == name for name in self._names} diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/INSTALLER b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/METADATA b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..18b827d5ef2f8bd7b277c636e866dbc45ab6d16f --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/METADATA @@ -0,0 +1,55 @@ +Metadata-Version: 2.4 +Name: conda-package-handling +Version: 2.4.0 +Summary: Create and extract conda packages of various formats. +Home-page: https://github.com/conda/conda-package-handling +Author: Anaconda, Inc. +Author-email: conda@anaconda.com +Keywords: conda-package-handling +Classifier: Programming Language :: Python :: 3 +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-File: LICENSE +License-File: AUTHORS.md +Requires-Dist: conda-package-streaming>=0.9.0 +Provides-Extra: docs +Requires-Dist: furo; extra == "docs" +Requires-Dist: sphinx; extra == "docs" +Requires-Dist: sphinx-argparse; extra == "docs" +Requires-Dist: myst-parser; extra == "docs" +Requires-Dist: mdit-py-plugins>=0.3.0; extra == "docs" +Provides-Extra: test +Requires-Dist: mock; extra == "test" +Requires-Dist: pytest; extra == "test" +Requires-Dist: pytest-cov; extra == "test" +Requires-Dist: pytest-mock; extra == "test" +Requires-Dist: bottle; extra == "test" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# conda-package-handling + +[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/conda/conda-package-handling/main.svg)](https://results.pre-commit.ci/latest/github/conda/conda-package-handling/main) + +Create and extract conda packages of various formats. + +`conda` and `conda-build` use `conda_package_handling.api` to create and extract +conda packages. This package also provides the `cph` command line tool to +extract, create, and convert between formats. + +See also +[conda-package-streaming](https://conda.github.io/conda-package-streaming), an +efficient library to read from new and old format .conda and .tar.bz2 conda +packages. + +Full documentation at [https://conda.github.io/conda-package-handling/](https://conda.github.io/conda-package-handling/) diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/RECORD b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f040e97f09e41d982fe2d136ddab14fc496964c2 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/RECORD @@ -0,0 +1,33 @@ +../../../bin/cph,sha256=8l-Rp9U9E5wfHY3n_BLjFjyH8PFAmQcUH9ZDEFXjjYs,481 +conda_package_handling-2.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +conda_package_handling-2.4.0.dist-info/METADATA,sha256=_YzNZyk3KcgMXBlUgL-rvAq2Giou8V0f4PNa31IjGhQ,1977 +conda_package_handling-2.4.0.dist-info/RECORD,, +conda_package_handling-2.4.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +conda_package_handling-2.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +conda_package_handling-2.4.0.dist-info/direct_url.json,sha256=NfSTIqxtaVOSqkrkI2oHYgOzw9ipzp_3AAw7czuTCxI,112 +conda_package_handling-2.4.0.dist-info/entry_points.txt,sha256=4gBd7ZOv9v6P3VIiI6veVwgXzKCu_fUiOqwqVb0VTno,56 +conda_package_handling-2.4.0.dist-info/licenses/AUTHORS.md,sha256=IH_Um8vGtX2W3zDeomwXBWG-0MWj5LYtCGmdOfOhoSo,494 +conda_package_handling-2.4.0.dist-info/licenses/LICENSE,sha256=t_7OW5ytYcamhC7Wd2bBOAaL6tOaKVupR0m8szIrXnU,1505 +conda_package_handling-2.4.0.dist-info/top_level.txt,sha256=3290W3g8MbIyhMS6inC3oTzSzIweY5A2UKk__AZrnSY,23 +conda_package_handling/__init__.py,sha256=yLaFvd-K80rs_ClRVYULStijkok4RfYSaanIt_E-aKM,22 +conda_package_handling/__main__.py,sha256=a8OMmLES3Fl3A097Gn8VgCl6qR0b0zL6PON76sjnik8,60 +conda_package_handling/__pycache__/__init__.cpython-313.pyc,, +conda_package_handling/__pycache__/__main__.cpython-313.pyc,, +conda_package_handling/__pycache__/api.cpython-313.pyc,, +conda_package_handling/__pycache__/cli.cpython-313.pyc,, +conda_package_handling/__pycache__/conda_fmt.cpython-313.pyc,, +conda_package_handling/__pycache__/exceptions.cpython-313.pyc,, +conda_package_handling/__pycache__/interface.cpython-313.pyc,, +conda_package_handling/__pycache__/streaming.cpython-313.pyc,, +conda_package_handling/__pycache__/tarball.cpython-313.pyc,, +conda_package_handling/__pycache__/utils.cpython-313.pyc,, +conda_package_handling/__pycache__/validate.cpython-313.pyc,, +conda_package_handling/api.py,sha256=1myslsbrLIlu_oUh__XqyoV_6i441TVby8RZr8TRvvI,8085 +conda_package_handling/cli.py,sha256=eihYohoPzq8zINR1u-rbvRjIurW4eAts3mk28h8Lfx4,6047 +conda_package_handling/conda_fmt.py,sha256=wg9qNphvoD-vbHUNpZIiYJdaPMltmcIKOzfZ0EfjG9Q,7786 +conda_package_handling/exceptions.py,sha256=Eg2_GsE2oJqpeHvg98YYO6tfHP8Wv0MrV7CS55xRau0,1893 +conda_package_handling/interface.py,sha256=YkNDXXv12uCJtjCXz5uhWHGkR_rzOLVNiRZ-Eawv3Yg,796 +conda_package_handling/streaming.py,sha256=rTvjVY1zrQvu0Iueqh_HF6Fc4-x1LWQ3hfNsPwXBwjY,3071 +conda_package_handling/tarball.py,sha256=xibzzljnkBFoRHT_BG7ceNonX6iuC-bqhr4FySFX6Iw,3271 +conda_package_handling/utils.py,sha256=xhJfogHyWO7Mxx1y4OmHcHXEuVEQIR99bMVZP-Y0Zqk,16707 +conda_package_handling/validate.py,sha256=48gkidkuUm1JbCxLTh2jbJ4TgMu9tAasltb-UO2R62k,3652 diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/REQUESTED b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/WHEEL b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/direct_url.json b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..88857d546616e736d35febe1d6572f9a750e7054 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/task_176236637997838/conda-bld/conda-package-handling_1762366405159/work"} \ No newline at end of file diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/entry_points.txt b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..9fdb1861f943c5c8c0b96afb0e2ea40f88f30649 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +cph = conda_package_handling.cli:main diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/licenses/AUTHORS.md b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/licenses/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..1e1f7b4dd7a8e1ff3b3ecf67cfb28f12ce49d5d8 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/licenses/AUTHORS.md @@ -0,0 +1,26 @@ +All of the people who have made at least one contribution to conda-package-handling. +Authors are sorted alphabetically. + +* Alan Du +* Cheng H. Lee +* Chris Burr +* Christopher Barber +* Conda Bot +* Daniel Bast +* Daniel Holth +* Eli Uriegas +* Jannis Leidel +* John Lee +* Jonathan J. Helmus +* Justin Wood (Callek) +* Ken Odegard +* Marius van Niekerk +* Matthew R. Becker +* Michael Sarahan +* Nehal J Wani +* Pure Software +* Ray Donnelly +* Tobias "Tobi" Koch +* Vadim Zayakin +* jaimergp +* pre-commit-ci[bot] diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/licenses/LICENSE b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eb2f3f5caf1ffbd7a91b22c6a757ab1f31616621 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2019, Conda +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* 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. + +* 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 NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/top_level.txt b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b18d594baf030474c9e1b3a2f0cc4b86c453686b --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling-2.4.0.dist-info/top_level.txt @@ -0,0 +1 @@ +conda_package_handling diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/__init__.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d67cd6bb497cf0c862b60ff30e8b273aae5d851 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/__init__.py @@ -0,0 +1 @@ +__version__ = "2.4.0" diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/__main__.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..dde91ff0efe062c13395035b31d275e499d967de --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/__main__.py @@ -0,0 +1,3 @@ +from conda_package_handling import cli + +cli.main(args=None) diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/api.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/api.py new file mode 100644 index 0000000000000000000000000000000000000000..47881ce4a1330e1011fc7c241114a77985094034 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/api.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import functools as _functools +import os as _os +import warnings as _warnings +from glob import glob as _glob + +# expose these two exceptions as part of the API. Everything else should feed into these. +from .exceptions import ConversionError, InvalidArchiveError # NOQA +from .interface import AbstractBaseFormat +from .tarball import CondaTarBZ2 as _CondaTarBZ2 +from .utils import ensure_list, filter_info_files +from .utils import get_executor as _get_executor +from .utils import rm_rf as _rm_rf + +SUPPORTED_EXTENSIONS: dict[str, type[AbstractBaseFormat]] = {".tar.bz2": _CondaTarBZ2} + +libarchive_enabled = False #: Old API meaning "can extract .conda" (now without libarchive) + +try: + from .conda_fmt import ZSTD_COMPRESS_LEVEL, ZSTD_COMPRESS_THREADS + from .conda_fmt import CondaFormat_v2 as _CondaFormat_v2 + + SUPPORTED_EXTENSIONS[".conda"] = _CondaFormat_v2 + + libarchive_enabled = True + +except ImportError: + _warnings.warn("Install zstandard Python bindings for .conda support") + +THREADSAFE_EXTRACT = True #: Not present in conda-package-handling<2.0. + + +def _collect_paths(prefix): + dir_paths, file_paths = [], [] + for dp, dn, filenames in _os.walk(prefix): + for f in filenames: + file_paths.append(_os.path.relpath(_os.path.join(dp, f), prefix)) + dir_paths.extend(_os.path.relpath(_os.path.join(dp, _), prefix) for _ in dn) + file_list = file_paths + [ + dp for dp in dir_paths if not any(f.startswith(dp + _os.sep) for f in file_paths) + ] + return file_list + + +def get_default_extracted_folder(in_file, abspath=True): + dirname = None + for ext in SUPPORTED_EXTENSIONS: + if in_file.endswith(ext): + dirname = in_file[: -len(ext)] + if dirname and not abspath: + dirname = _os.path.basename(dirname) + return dirname + + +def extract(fn, dest_dir=None, components=None, prefix=None): + if dest_dir: + if _os.path.isabs(dest_dir) and prefix: + raise ValueError( + "dest_dir and prefix both provided as abs paths. If providing both, " + "prefix can be abspath, but dest dir must be relative (relative to " + "prefix)" + ) + if not _os.path.isabs(dest_dir): + dest_dir = _os.path.normpath(_os.path.join(prefix or _os.getcwd(), dest_dir)) + else: + dest_dir = _os.path.join( + prefix or _os.path.dirname(fn), + get_default_extracted_folder(fn, abspath=False), + ) + + if not _os.path.isdir(dest_dir): + _os.makedirs(dest_dir) + + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(fn): + format.extract(fn, dest_dir, components=components) + break + else: + raise ValueError( + "Didn't recognize extension for file '{}'. Supported extensions are: {}".format( + fn, list(SUPPORTED_EXTENSIONS.keys()) + ) + ) + + +def create(prefix, file_list, out_fn, out_folder=None, **kw): + if not out_folder: + out_folder = _os.getcwd() + + # simplify arguments to format.create() + if _os.path.isabs(out_fn): + out_folder = _os.path.dirname(out_fn) + out_fn = _os.path.basename(out_fn) + + if file_list is None: + file_list = _collect_paths(prefix) + elif isinstance(file_list, str): + try: + with open(file_list) as f: + data = f.readlines() + file_list = [_.strip() for _ in data] + except: + raise + + out = None + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(out_fn): + try: + out = format.create(prefix, file_list, out_fn, out_folder, **kw) + break + except BaseException as err: + # don't leave broken files around + abs_out_fn = _os.path.join(out_folder, out_fn) + if _os.path.isfile(abs_out_fn): + _rm_rf(abs_out_fn) + raise err + else: + raise ValueError( + "Didn't recognize extension for file '{}'. Supported extensions are: {}".format( + out_fn, list(SUPPORTED_EXTENSIONS.keys()) + ) + ) + + return out + + +def _convert( + fn, + out_ext, + out_folder, + force=False, + zstd_compress_level=None, + zstd_compress_threads=None, + **kw, +): + # allow package to work in degraded mode when zstandard is not available + import conda_package_streaming.transmute + import zstandard + + basename = get_default_extracted_folder(fn, abspath=False) + from .validate import validate_converted_files_match_streaming + + if not basename: + return ( + fn, + "", + "Input file %s doesn't have a supported extension (%s), skipping it" + % (fn, SUPPORTED_EXTENSIONS), + ) + out_fn = str(_os.path.join(out_folder, basename + out_ext)) + errors = "" + if not _os.path.lexists(out_fn) or force: + if force and _os.path.lexists(out_fn): + _os.unlink(out_fn) + + if out_ext == ".conda": + # ZSTD_COMPRESS_* constants are only defined if we have zstandard + if zstd_compress_level is None: + zstd_compress_level = ZSTD_COMPRESS_LEVEL + if zstd_compress_threads is None: + zstd_compress_threads = ZSTD_COMPRESS_THREADS + + def compressor(): + return zstandard.ZstdCompressor( + level=zstd_compress_level, threads=zstd_compress_threads + ) + + def is_info(filename): + return filter_info_files([filename], prefix=".") == [] + + transmute = _functools.partial( + conda_package_streaming.transmute.transmute, + fn, + out_folder, + compressor=compressor, + is_info=is_info, + ) + + else: + transmute = _functools.partial( + conda_package_streaming.transmute.transmute_tar_bz2, fn, out_folder + ) + + try: + transmute() + result = validate_converted_files_match_streaming(out_fn, fn) + _, missing_files, mismatching_sizes = result + if missing_files or mismatching_sizes: + errors = str(ConversionError(missing_files, mismatching_sizes)) + except BaseException as e: + # don't leave partial package around + if _os.path.isfile(out_fn): + _rm_rf(out_fn) + if not isinstance(e, Exception): + raise + errors = str(e) + + return fn, out_fn, errors + + +def transmute(in_file, out_ext, out_folder=None, processes=1, **kw): + if not out_folder: + out_folder = _os.path.dirname(in_file) or _os.getcwd() + + flist = set(_glob(in_file)) + for in_ext in SUPPORTED_EXTENSIONS: + if in_file.endswith(in_ext): + replacement = in_file[: -len(in_ext)] + out_ext + flist = flist - set(_glob(replacement)) + break + + failed_files = {} + with _get_executor(processes) as executor: + convert_f = _functools.partial(_convert, out_ext=out_ext, out_folder=out_folder, **kw) + for fn, out_fn, errors in executor.map(convert_f, flist): + if errors: + failed_files[fn] = errors + _rm_rf(out_fn) + return failed_files + + +def get_pkg_details(in_file): + """For the new pkg format, we return the size and hashes of the inner pkg part of the file""" + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(in_file): + return format.get_pkg_details(in_file) + raise ValueError(f"Don't know what to do with file {in_file}") + + +def list_contents(in_file, verbose=False, components=None): + components = ensure_list(components or ("info", "pkg")) + for format in SUPPORTED_EXTENSIONS.values(): + if format.supported(in_file): + return format.list_contents(in_file, verbose=verbose, components=components) + raise ValueError(f"Don't know what to do with file {in_file}") diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/cli.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ed3733c53fb2b2ab9d163378a4bdc7b0d1d4f5 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/cli.py @@ -0,0 +1,165 @@ +import argparse +import os +import sys +from pprint import pprint + +from . import __version__, api + + +def parse_args(parse_this=None): + parser = build_parser() + return parser.parse_args(parse_this) + + +def build_parser(): + parser = argparse.ArgumentParser() + parser.add_argument( + "-V", + "--version", + action="version", + help="Show the conda-package-handling version number and exit.", + version=f"conda-package-handling {__version__}", + ) + sp = parser.add_subparsers(title="subcommands", dest="subcommand", required=True) + + extract_parser = sp.add_parser("extract", help="extract package contents", aliases=["x"]) + extract_parser.add_argument("archive_path", help="path to archive to extract") + extract_parser.add_argument( + "--dest", + help="destination folder to extract to. If not set, defaults to" + " package filename minus extension in the same folder as the input archive." + " May be relative path used in tandem with the --prefix flag.", + ) + extract_parser.add_argument( + "--prefix", + help="base directory to extract to. Use this to set the base" + " directory, while allowing the folder name to be automatically determined " + "by the input filename. An abspath --prefix with an unset --dest will " + "achieve this.", + ) + extract_parser.add_argument( + "--info", + help="If the archive supports separate metadata, this" + " flag extracts only the metadata in the info folder from the " + "package. If the archive does not support separate metadata, this " + "flag has no effect and all files are extracted.", + action="store_true", + ) + + create_parser = sp.add_parser("create", help="bundle files into a package", aliases=["c"]) + create_parser.add_argument( + "prefix", + help="folder of files to bundle. Not strictly required to" + " have conda package metadata, but if conda package metadata isn't " + "present, you'll see a warning and your file will not work as a " + "conda package", + ) + create_parser.add_argument( + "out_fn", + help="Filename of archive to be created. Extension determines package type.", + ) + create_parser.add_argument( + "--file-list", + help="Path to file containing one relative path per" + " line that should be included in the archive. If not provided, " + "lists all files in the prefix.", + ) + create_parser.add_argument("--out-folder", help="Folder to dump final archive to") + + convert_parser = sp.add_parser( + "transmute", help="convert from one package type to another", aliases=["t"] + ) + convert_parser.add_argument( + "in_file", help="existing file to convert from. Glob patterns accepted." + ) + convert_parser.add_argument( + "out_ext", + help="extension of file to convert to. Examples: .tar.bz2, .conda", + ) + convert_parser.add_argument("--out-folder", help="Folder to dump final archive to") + convert_parser.add_argument( + "--force", action="store_true", help="Force overwrite existing package" + ) + convert_parser.add_argument( + "--processes", + type=int, + help="Max number of processes to use. If not set, defaults to 1.", + ) + convert_parser.add_argument( + "--zstd-compression-level", + help=( + "When building v2 packages, set the compression level used by " + "conda-package-handling. Defaults to 19." + ), + type=int, + choices=range(1, 23), + default=19, + ) + convert_parser.add_argument( + "--zstd-compression-threads", + help=( + "When building v2 packages, set the compression threads used by " + "conda-package-handling. Defaults to 1. -1=automatic." + ), + type=int, + default=1, + ) + list_parser = sp.add_parser( + "list", + aliases=["l"], + help="List package contents like `python -m tarfile --list ...` would do.", + ) + list_parser.add_argument("archive_path", help="path or URL to archive to inspect") + list_parser.add_argument( + "-v", + "--verbose", + action="store_true", + help="Report more details, similar to 'ls -l'. Otherwise, only the filenames are printed.", + ) + list_parser.add_argument( + "--components", + dest="components", + default="info,pkg", + help="Comma-separated list of components to read (.conda artifacts only; " + "ignored for .tar.bz2). Allowed values: info, pkg.", + ) + + return parser + + +def main(args=None): + args = parse_args(args) + if hasattr(args, "out_folder") and args.out_folder: + args.out_folder = ( + os.path.abspath(os.path.normpath(os.path.expanduser(args.out_folder))) + os.sep + ) + if args.subcommand in ("extract", "x"): + if args.info: + api.extract(args.archive_path, args.dest, components="info", prefix=args.prefix) + else: + api.extract(args.archive_path, args.dest, prefix=args.prefix) + elif args.subcommand in ("create", "c"): + api.create(args.prefix, args.file_list, args.out_fn, args.out_folder) + elif args.subcommand in ("transmute", "t"): + failed_files = api.transmute( + args.in_file, + args.out_ext, + args.out_folder, + args.processes or 1, + force=args.force, + zstd_compress_level=args.zstd_compression_level, + zstd_compress_threads=args.zstd_compression_threads, + ) + if failed_files: + print("failed files:") + pprint(failed_files) + sys.exit(1) + elif args.subcommand in ("list", "l"): + components = [ + component.strip() for component in (args.components or "info,pkg").split(",") + ] + api.list_contents(args.archive_path, verbose=args.verbose, components=components) + + +if __name__ == "__main__": # pragma: no cover + main(args=None) diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/conda_fmt.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/conda_fmt.py new file mode 100644 index 0000000000000000000000000000000000000000..c6c45cd37234c682db53e511ecd94bc8c909b089 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/conda_fmt.py @@ -0,0 +1,198 @@ +""" +The 'new' conda format, introduced in late 2018/early 2019. + +https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/packages.html +""" + +from __future__ import annotations + +import json +import os +import stat +import tarfile +import time +from contextlib import closing +from typing import Callable +from zipfile import ZIP_STORED, ZipFile + +import zstandard +from conda_package_streaming.package_streaming import stream_conda_component +from conda_package_streaming.url import conda_reader_for_url + +from . import utils +from .interface import AbstractBaseFormat +from .streaming import _extract, _list + +CONDA_PACKAGE_FORMAT_VERSION = 2 +DEFAULT_COMPRESSION_TUPLE = (".tar.zst", "zstd", "zstd:compression-level=19") + +# increase to reduce speed and increase compression (22 = conda's default) +ZSTD_COMPRESS_LEVEL = 19 +# increase to reduce compression (slightly) and increase speed +ZSTD_COMPRESS_THREADS = 1 + + +class CondaFormat_v2(AbstractBaseFormat): + """If there's another conda format or breaking changes, please create a new class and keep this + one, so that handling of v2 stays working.""" + + @staticmethod + def supported(fn): + return fn.endswith(".conda") + + @staticmethod + def extract(fn, dest_dir, **kw): + components = utils.ensure_list(kw.get("components")) or ("info", "pkg") + if not os.path.isabs(fn): + fn = os.path.normpath(os.path.join(os.getcwd(), fn)) + if not os.path.isdir(dest_dir): + os.makedirs(dest_dir) + + _extract(str(fn), str(dest_dir), components=components) + + @staticmethod + def extract_info(fn, dest_dir=None): + return CondaFormat_v2.extract(fn, dest_dir, components=["info"]) + + @staticmethod + def create( + prefix, + file_list, + out_fn, + out_folder=None, + compressor: Callable[[], zstandard.ZstdCompressor] | None = None, + compression_tuple=(None, None, None), + ): + if out_folder is None: + out_folder = os.getcwd() + if os.path.isabs(out_fn): + out_folder = os.path.dirname(out_fn) + out_fn = os.path.basename(out_fn) + conda_pkg_fn = os.path.join(out_folder, out_fn) + file_id = out_fn[: -len(".conda")] + pkg_files = utils.filter_info_files(file_list, prefix) + # preserve order + pkg_files_set = set(pkg_files) + info_files = list(f for f in file_list if f not in pkg_files_set) + + if compressor and (compression_tuple != (None, None, None)): + raise ValueError("Supply one of compressor= or (deprecated) compression_tuple=") + + if compressor is None: + compressor = lambda: zstandard.ZstdCompressor( + level=ZSTD_COMPRESS_LEVEL, + threads=ZSTD_COMPRESS_THREADS, + ) + + # legacy libarchive-ish compatibility + ext, comp_filter, filter_opts = compression_tuple + if filter_opts and filter_opts.startswith("zstd:compression-level="): + compressor = lambda: zstandard.ZstdCompressor( + level=int(filter_opts.split("=", 1)[-1]), + threads=ZSTD_COMPRESS_THREADS, + ) + + class NullWriter: + """ + zstd uses less memory on extract if size is known. + """ + + def __init__(self): + self.size = 0 + + def write(self, bytes): + self.size += len(bytes) + return len(bytes) + + def tell(self): + return self.size + + with ZipFile(conda_pkg_fn, "w", compression=ZIP_STORED) as conda_file, utils.tmp_chdir( + prefix + ): + pkg_metadata = {"conda_pkg_format_version": CONDA_PACKAGE_FORMAT_VERSION} + conda_file.writestr("metadata.json", json.dumps(pkg_metadata)) + + components_files = ( + (f"pkg-{file_id}.tar.zst", pkg_files), + ( + f"info-{file_id}.tar.zst", + info_files, + ), + ) + + # put the info last, for parity with updated transmute. + compress = compressor() + for component, files in components_files: + # If size is known, the decompressor may be able to allocate less memory. + # The compressor will error if size is not correct. + with tarfile.TarFile(fileobj=NullWriter(), mode="w") as sizer: # type: ignore + for file in files: + sizer.add(file, filter=utils.anonymize_tarinfo) + size = sizer.fileobj.size # type: ignore + + with conda_file.open(component, "w", force_zip64=True) as component_file: + # only one stream_writer() per compressor() must be in use at a time + component_stream = compress.stream_writer( + component_file, size=size, closefd=False + ) + component_tar = tarfile.TarFile(fileobj=component_stream, mode="w") + + for file in files: + component_tar.add(file, filter=utils.anonymize_tarinfo) + + component_tar.close() + component_stream.close() + + return conda_pkg_fn + + @staticmethod + def get_pkg_details(in_file): + stat_result = os.stat(in_file) + size = stat_result.st_size + md5, sha256 = utils.checksums(in_file, ("md5", "sha256")) + return {"size": size, "md5": md5, "sha256": sha256} + + @classmethod + def list_contents(cls, fn, verbose=False, **kw): + components = utils.ensure_list(kw.get("components")) or ("info", "pkg") + if "://" in fn: + return cls._list_remote_contents(fn, components=components, verbose=verbose) + # local resource + if not os.path.isabs(fn): + fn = os.path.abspath(fn) + _list(fn, components=components, verbose=verbose) + + @staticmethod + def _list_remote_contents(url, verbose=False, components=("info", "pkg")): + """ + List contents of a remote .conda artifact (by URL). It only fetches the 'info' component + and uses the metadata to infer details of the 'pkg' component. Some fields like + modification time or permissions will be missing in verbose mode. + """ + components = utils.ensure_list(components or ("info", "pkg")) + lines = {} + filename, conda = conda_reader_for_url(url) + with closing(conda): + for tar, member in stream_conda_component(filename, conda, component="info"): + path = member.name + ("/" if member.isdir() else "") + if "info" in components: + line = "" + if verbose: + line = ( + f"{stat.filemode(member.mode)} " + f"{member.uname or member.uid}/{member.gname or member.gid} " + f"{member.size:10d} " + ) + line += "%d-%02d-%02d %02d:%02d:%02d " % time.localtime(member.mtime)[:6] + lines[path] = line + path + if "pkg" in components and member.name == "info/paths.json": + data = json.loads(tar.extractfile(member).read().decode()) + assert data.get("paths_version", 1) == 1, data + for path in data.get("paths", ()): + line = "" + if verbose: + size = path["size_in_bytes"] + line = f"?????????? ?/? {size:10d} ????-??-?? ??:??:?? " + lines[path["_path"]] = line + path["_path"] + print(*[line for _, line in sorted(lines.items())], sep="\n") diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/exceptions.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..00e820c63b072448b432e258a34a1d8f73c80126 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/exceptions.py @@ -0,0 +1,53 @@ +from errno import ENOENT + + +class InvalidArchiveError(Exception): + """Raised when libarchive can't open a file""" + + def __init__(self, fn, msg, *args, **kw): + msg = ( + "Error with archive %s. You probably need to delete and re-download " + "or re-create this file. Message was:\n\n%s" % (fn, msg) + ) + self.errno = ENOENT + super().__init__(msg) + + +class ArchiveCreationError(Exception): + """Raised when an archive fails during creation""" + + pass + + +class CaseInsensitiveFileSystemError(InvalidArchiveError): + def __init__(self, package_location, extract_location, **kwargs): + message = """ + Cannot extract package to a case-insensitive file system. Your install + destination does not differentiate between upper and lowercase + characters, and this breaks things. Try installing to a location that + is case-sensitive. Windows drives are usually the culprit here - can + you install to a native Unix drive, or turn on case sensitivity for + this (Windows) location? + + package location: %(package_location)s + extract location: %(extract_location)s + """ + self.package_location = package_location + self.extract_location = extract_location + super().__init__(package_location, message, **kwargs) + + +class ConversionError(Exception): + def __init__(self, missing_files, mismatching_sizes, *args, **kw): + self.missing_files = missing_files + self.mismatching_sizes = mismatching_sizes + errors = "" + if self.missing_files: + errors = "Missing files in converted package: %s\n" % self.missing_files + errors = ( + errors + + "Mismatching sizes (corruption) in converted package: %s" # noqa + % self.mismatching_sizes + ) + + super().__init__(errors, *args, **kw) diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/interface.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..390cffdc77ed4fc668f0ebd070f641855f4f1447 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/interface.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import abc + + +class AbstractBaseFormat(metaclass=abc.ABCMeta): + @staticmethod + @abc.abstractmethod + def supported(fn): # pragma: no cover + return False + + @staticmethod + @abc.abstractmethod + def extract(fn, dest_dir, **kw): # pragma: no cover + raise NotImplementedError + + @staticmethod + @abc.abstractmethod + def create(prefix, file_list, out_fn, out_folder: str | None = None, **kw): # pragma: no cover + raise NotImplementedError + + @staticmethod + @abc.abstractmethod + def get_pkg_details(in_file): # pragma: no cover + raise NotImplementedError + + @staticmethod + @abc.abstractmethod + def list_contents(in_file, verbose=False, **kw): # pragma: no cover + raise NotImplementedError diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/streaming.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..f05f981ae70e215ea89fdba9c1366b575284756c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/streaming.py @@ -0,0 +1,82 @@ +""" +Exception-compatible adapter from conda_package_streaming. +""" + +from __future__ import annotations + +import io +import tarfile +from contextlib import redirect_stdout +from tarfile import TarError +from typing import Generator +from zipfile import BadZipFile + +from conda_package_streaming.extract import exceptions as cps_exceptions +from conda_package_streaming.extract import extract_stream, package_streaming + +from . import exceptions + + +def _stream_components( + filename: str, + components: list[str], + dest_dir: str = "", +) -> Generator[Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]]: + if str(filename).endswith(".tar.bz2"): + assert components == ["pkg"] + + try: + with open(filename, "rb") as fileobj: + for component in components: + # will parse zipfile twice + yield package_streaming.stream_conda_component( + filename, fileobj, component=component + ) + except cps_exceptions.CaseInsensitiveFileSystemError as e: + raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e + except (OSError, TarError, BadZipFile) as e: + raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e + + +def _extract(filename: str, dest_dir: str, components: list[str]): + """ + Extract .conda or .tar.bz2 package to dest_dir. + + If it's a conda package, components may be ["pkg", "info"] + + If it's a .tar.bz2 package, components must equal ["pkg"] + + Internal. Skip directly to conda-package-streaming if you don't need + exception compatibility. + """ + for stream in _stream_components(filename, components, dest_dir=dest_dir): + try: + extract_stream(stream, dest_dir) + except cps_exceptions.CaseInsensitiveFileSystemError as e: + raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e + except (OSError, TarError, BadZipFile) as e: + raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e + + +def _list(filename: str, components: list[str], verbose=True): + memfile = io.StringIO() + for component in _stream_components(filename, components): + for tar, _ in component: + with redirect_stdout(memfile): + tar.list(verbose=verbose) + # next iteraton of for loop raises GeneratorExit in stream + # see comments in conda_package_streaming.extract:extract_stream + # and docstring in conda_package_streaming.package_streaming:stream_conda_info + component.close() + memfile.seek(0) + if verbose: + lines = sorted( + memfile.readlines(), + # verbose Tarfile.list() produces lines like: + # ?rw-r--r-- 502/20 2342 2018-10-04 14:02:00 info/about.json + # We only want the last part but we need to be mindful of paths containing spaces + key=lambda line: line.split(None, 5)[-1], + ) + else: + lines = sorted(memfile.readlines()) + print("".join(lines), end="") diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/tarball.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/tarball.py new file mode 100644 index 0000000000000000000000000000000000000000..506a3e0ba5c0f8ea99b1210d11b5dd6e255bc222 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/tarball.py @@ -0,0 +1,101 @@ +import logging +import os +import re +import tarfile + +from . import streaming, utils +from .interface import AbstractBaseFormat + +LOG = logging.getLogger(__name__) + + +def _sort_file_order(prefix, files): + """Sort by filesize, to optimize compression?""" + info_slash = "info" + os.path.sep + + def order(f): + # we don't care about empty files so send them back via 100000 + fsize = os.lstat(os.path.join(prefix, f)).st_size or 100000 + # info/* records will be False == 0, others will be 1. + info_order = int(not f.startswith(info_slash)) + if info_order: + _, ext = os.path.splitext(f) + # Strip any .dylib.* and .so.* and rename .dylib to .so + ext = re.sub(r"(\.dylib|\.so).*$", r".so", ext) + if not ext: + # Files without extensions should be sorted by dirname + info_order = 1 + hash(os.path.dirname(f)) % (10**8) + else: + info_order = 1 + abs(hash(ext)) % (10**8) + return info_order, fsize + + files_list = list(sorted(files, key=order)) + + return files_list + + +def _create_no_libarchive(fullpath, files): + with tarfile.open(fullpath, "w:bz2") as t: + for f in files: + t.add(f, filter=utils.anonymize_tarinfo) + + +def create_compressed_tarball( + prefix, files, tmpdir, basename, ext, compression_filter, filter_opts="" +): + tmp_path = os.path.join(tmpdir, basename) + files = _sort_file_order(prefix, files) + + # add files in order of a) in info directory, b) increasing size so + # we can access small manifest or json files without decompressing + # possible large binary or data files + fullpath = tmp_path + ext + with utils.tmp_chdir(prefix): + _create_no_libarchive(fullpath, files) + return fullpath + + +class CondaTarBZ2(AbstractBaseFormat): + @staticmethod + def supported(fn): + return fn.endswith(".tar.bz2") + + @staticmethod + def extract(fn, dest_dir, **kw): + if not os.path.isdir(dest_dir): + os.makedirs(dest_dir) + if not os.path.isabs(fn): + fn = os.path.normpath(os.path.join(os.getcwd(), fn)) + + streaming._extract(str(fn), str(dest_dir), components=["pkg"]) + + @staticmethod + def create(prefix, file_list, out_fn, out_folder=None, **kw): + if out_folder is None: + out_folder = os.getcwd() + if os.path.isabs(out_fn): + out_folder = os.path.dirname(out_fn) + out_file = create_compressed_tarball( + prefix, + file_list, + out_folder, + os.path.basename(out_fn).replace(".tar.bz2", ""), + ".tar.bz2", + "bzip2", + ) + return out_file + + @staticmethod + def get_pkg_details(in_file): + stat_result = os.stat(in_file) + size = stat_result.st_size + md5, sha256 = utils.checksums(in_file, ("md5", "sha256")) + return {"size": size, "md5": md5, "sha256": sha256} + + @staticmethod + def list_contents(fn, verbose=False, **kw): + if "://" in fn: + raise ValueError("Remote .tar.bz2 artifact listing is not supported.") + if not os.path.isabs(fn): + fn = os.path.abspath(fn) + streaming._list(str(fn), components=["pkg"], verbose=verbose) diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/utils.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..699a2dbe4d31c495a04205c200376a22714be26c --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/utils.py @@ -0,0 +1,493 @@ +import contextlib +import fnmatch +import hashlib +import logging +import os +import re +import shutil +import sys +import warnings as _warnings +from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor +from errno import EACCES, ENOENT, EPERM, EROFS +from itertools import chain +from os.path import ( + abspath, + basename, + dirname, + isdir, + isfile, + islink, + join, + lexists, + normpath, + split, +) +from stat import S_IEXEC, S_IMODE, S_ISDIR, S_ISREG, S_IWRITE +from subprocess import STDOUT, CalledProcessError, check_output, list2cmdline +from tempfile import NamedTemporaryFile, mkdtemp + +on_win = sys.platform == "win32" +log = logging.getLogger(__name__) +CONDA_TEMP_EXTENSION = ".c~" + + +def which(executable): + from distutils.spawn import find_executable + + return find_executable(executable) + + +def make_writable(path): + try: + mode = os.lstat(path).st_mode + if S_ISDIR(mode): + os.chmod(path, S_IMODE(mode) | S_IWRITE | S_IEXEC) + elif S_ISREG(mode) or islink(path): + os.chmod(path, S_IMODE(mode) | S_IWRITE) + else: + log.debug("path cannot be made writable: %s", path) + return True + except Exception as e: + eno = getattr(e, "errno", None) + if eno in (ENOENT,): + log.debug("tried to make writable, but didn't exist: %s", path) + raise + elif eno in (EACCES, EPERM, EROFS): + log.debug("tried make writable but failed: %s\n%r", path, e) + return False + else: + log.warn("Error making path writable: %s\n%r", path, e) + raise + + +class DummyExecutor(Executor): + def map(self, func, *iterables): + for iterable in iterables: + for thing in iterable: + yield func(thing) + + +def get_executor(processes): + return DummyExecutor() if processes == 1 else ProcessPoolExecutor(max_workers=processes) + + +def recursive_make_writable(path): + # The need for this function was pointed out at + # https://github.com/conda/conda/issues/3266#issuecomment-239241915 + # Especially on windows, file removal will often fail because it is marked read-only + if isdir(path): + for root, dirs, files in os.walk(path): + for path in chain.from_iterable((files, dirs)): + try: + make_writable(join(root, path)) + except: + pass + else: + try: + make_writable(path) + except: + pass + + +def quote_for_shell(arguments, shell=None): + if not shell: + shell = "cmd.exe" if on_win else "bash" + if shell == "cmd.exe": + return list2cmdline(arguments) + else: + # If any multiline argument gets mixed with any other argument (which is true if we've + # arrived in this function) then we just quote it. This assumes something like: + # ['python', '-c', 'a\nmultiline\nprogram\n'] + # It may make sense to allow specifying a replacement character for '\n' too? e.g. ';' + quoted = [] + # This could all be replaced with some regex wizardry but that is less readable and + # for code like this, readability is very important. + for arg in arguments: + if '"' in arg: + quote = "'" + elif "'" in arg: + quote = '"' + elif not any(_ in arg for _ in (" ", "\n")): + quote = "" + else: + quote = '"' + quoted.append(quote + arg + quote) + return " ".join(quoted) + + +def rmtree(path, *args, **kwargs): + # subprocessing to delete large folders can be quite a bit faster + path = normpath(path) + if on_win: + try: + # the fastest way seems to be using DEL to recursively delete files + # https://www.ghacks.net/2017/07/18/how-to-delete-large-folders-in-windows-super-fast/ + # However, this is not entirely safe, as it can end up following symlinks to folders + # https://superuser.com/a/306618/184799 + # so, we stick with the slower, but hopefully safer way. Maybe if we figured out how + # to scan for any possible symlinks, we could do the faster way. + # out = check_output('DEL /F/Q/S *.* > NUL 2> NUL'.format(path), shell=True, + # stderr=STDOUT, cwd=path) + + out = check_output(f'RD /S /Q "{path}" > NUL 2> NUL', shell=True, stderr=STDOUT) + except: + try: + # Try to delete in Unicode + name = None + + with NamedTemporaryFile(suffix=".bat", delete=False) as batch_file: + batch_file.write(f"RD /S {quote_for_shell([path])}\n") + batch_file.write("chcp 65001\n") + batch_file.write(f"RD /S {quote_for_shell([path])}\n") + batch_file.write("EXIT 0\n") + name = batch_file.name + # If the above is bugged we can end up deleting hard-drives, so we check + # that 'path' appears in it. This is not bulletproof but it could save you (me). + with open(name) as contents: + content = contents.read() + assert path in content + comspec = os.environ["COMSPEC"] + CREATE_NO_WINDOW = 0x08000000 + # It is essential that we `pass stdout=None, stderr=None, stdin=None` here because + # if we do not, then the standard console handles get attached and chcp affects the + # parent process (and any which share those console handles!) + out = check_output( + [comspec, "/d", "/c", name], + shell=False, + stdout=None, + stderr=None, + stdin=None, + creationflags=CREATE_NO_WINDOW, + ) + + except CalledProcessError as e: + if e.returncode != 5: + log.error(f"Removing folder {path} the fast way failed. Output was: {out}") + raise + else: + log.debug(f"removing dir contents the fast way failed. Output was: {out}") + else: + try: + os.makedirs(".empty") + except: + pass + # yes, this looks strange. See + # https://unix.stackexchange.com/a/79656/34459 + # https://web.archive.org/web/20130929001850/http://linuxnote.net/jianingy/en/linux/a-fast-way-to-remove-huge-number-of-files.html # NOQA + rsync = which("rsync") + if rsync and isdir(".empty"): + try: + out = check_output( + [ + rsync, + "-a", + "--force", + "--delete", + join(os.getcwd(), ".empty") + "/", + path + "/", + ], + stderr=STDOUT, + ) + except CalledProcessError: + log.debug(f"removing dir contents the fast way failed. Output was: {out}") + shutil.rmtree(".empty") + shutil.rmtree(path) + + +def unlink_or_rename_to_trash(path): + """If files are in use, especially on windows, we can't remove them. + The fallback path is to rename them (but keep their folder the same), + which maintains the file handle validity. See comments at: + https://serverfault.com/a/503769 + """ + try: + make_writable(path) + os.unlink(path) + except OSError: + try: + os.rename(path, path + ".conda_trash") + except OSError: + if on_win: + # on windows, it is important to use the rename program, as just using python's + # rename leads to permission errors when files are in use. + with NamedTemporaryFile(suffix=".bat") as trash_script: + with open(trash_script, "w") as f: + f.write('@pushd "%1"\n') + f.write("@REM Rename src to dest") + f.write('@ren "%2" "%3" > NUL 2> NUL")') + + _dirname, _fn = split(path) + dest_fn = path + ".conda_trash" + counter = 1 + while isfile(dest_fn): + dest_fn = dest_fn.splitext[0] + f".conda_trash_{counter}" + counter += 1 + out = "< empty >" + try: + out = check_output( + [ + "cmd.exe", + "/C", + trash_script, + _dirname, + _fn, + basename(dest_fn), + ], + stderr=STDOUT, + ) + except CalledProcessError: + log.warn( + "renaming file path {} to trash failed. Output was: {}".format( + path, out + ) + ) + + log.warn( + "Could not remove or rename {}. Please remove this file manually (you " + "may need to reboot to free file handles)".format(path) + ) + + +def remove_empty_parent_paths(path): + # recurse to clean up empty folders that were created to have a nested hierarchy + parent_path = dirname(path) + while isdir(parent_path) and not os.listdir(parent_path): + rmdir(parent_path) + parent_path = dirname(parent_path) + + +def rm_rf(path, clean_empty_parents=False, *args, **kw): + """ + Completely delete path + max_retries is the number of times to retry on failure. The default is 5. This only applies + to deleting a directory. + If removing path fails and trash is True, files will be moved to the trash directory. + """ + recursive_make_writable(path) + try: + path = abspath(path) + if isdir(path) and not islink(path): + rmdir(path) + elif lexists(path): + unlink_or_rename_to_trash(path) + else: + log.debug("rm_rf failed. Not a link, file, or directory: %s", path) + finally: + if lexists(path): + log.info("rm_rf failed for %s", path) + return False + if isdir(path): + delete_trash(path) + if clean_empty_parents: + remove_empty_parent_paths(path) + return True + + +# aliases that all do the same thing (legacy compat) +try_rmdir_all_empty = move_to_trash = move_path_to_trash = rm_rf + + +def delete_trash(prefix): + if not prefix: + prefix = sys.prefix + exclude = {"envs"} + for root, dirs, files in os.walk(prefix, topdown=True): + dirs[:] = [d for d in dirs if d not in exclude] + for fn in files: + if fnmatch.fnmatch(fn, "*.conda_trash*") or fnmatch.fnmatch( + fn, "*" + CONDA_TEMP_EXTENSION + ): + filename = join(root, fn) + try: + os.unlink(filename) + remove_empty_parent_paths(filename) + except OSError as e: + log.debug("%r errno %d\nCannot unlink %s.", e, e.errno, filename) + + +def rmdir(dirpath): + if not isdir(dirpath): + return + try: + rmtree(dirpath) + # we don't really care about errors that much. We'll catch remaining files + # with slower python logic. + except: + pass + + for root, dirs, files in os.walk(dirpath, topdown=False): + for f in files: + unlink_or_rename_to_trash(join(root, f)) + + +# we have our own TemporaryDirectory class because it's faster and handles disk issues better. +class TemporaryDirectory: + """Create and return a temporary directory. This has the same + behavior as mkdtemp but can be used as a context manager. For + example: + + with TemporaryDirectory() as tmpdir: + ... + + Upon exiting the context, the directory and everything contained + in it are removed. + """ + + # Handle mkdtemp raising an exception + name = None + _closed = False + + def __init__(self, suffix="", prefix=".cph_tmp", dir=os.getcwd()): + self.name = mkdtemp(suffix, prefix, dir) + + def __repr__(self): + return f"<{self.__class__.__name__} {self.name!r}>" + + def __enter__(self): + return self.name + + def cleanup(self, _warn=False, _warnings=_warnings): + if self.name and not self._closed: + try: + rm_rf(self.name) + except: + _warnings.warn( + 'Conda-package-handling says: "I tried to clean up, ' + "but I could not. There is a mess in %s that you might " + 'want to clean up yourself. Sorry..."' % self.name + ) + self._closed = True + if _warn and _warnings.warn: + _warnings.warn( + f"Implicitly cleaning up {self!r}", + _warnings.ResourceWarning, + ) + + def __exit__(self, exc, value, tb): + self.cleanup() + + def __del__(self): + # Issue a ResourceWarning if implicit cleanup needed + self.cleanup(_warn=True) + + +@contextlib.contextmanager +def tmp_chdir(dest): + curdir = os.getcwd() + try: + os.chdir(dest) + yield + finally: + os.chdir(curdir) + + +def ensure_list(arg): + if isinstance(arg, str) or not hasattr(arg, "__iter__"): + if arg is not None: + arg = [arg] + else: + arg = [] + return arg + + +def filter_files( + files_list, + prefix, + filter_patterns=( + r"(.*[\\\\/])?\.git[\\\\/].*", + r"(.*[\\\\/])?\.git$", + r"(.*)?\.DS_Store.*", + r".*\.la$", + r"conda-meta.*", + ), +): + """Remove things like the .git directory from the list of files to be copied""" + for pattern in filter_patterns: + r = re.compile(pattern) + files_list = set(files_list) - set(filter(r.match, files_list)) + return [ + f + for f in files_list + if + # `islink` prevents symlinks to directories from being removed + os.path.islink(os.path.join(prefix, f)) or not os.path.isdir(os.path.join(prefix, f)) + ] + + +def filter_info_files(files_list, prefix): + return filter_files( + files_list, + prefix, + filter_patterns=( + "info[\\\\/]index\\.json", + "info[\\\\/]files", + "info[\\\\/]paths\\.json", + "info[\\\\/]about\\.json", + "info[\\\\/]has_prefix", + "info[\\\\/]hash_input_files", # legacy, not used anymore + "info[\\\\/]hash_input\\.json", + "info[\\\\/]run_exports\\.yaml", # legacy + "info[\\\\/]run_exports\\.json", # current + "info[\\\\/]git", + "info[\\\\/]recipe[\\\\/].*", + "info[\\\\/]recipe_log.json", + "info[\\\\/]recipe.tar", + "info[\\\\/]test[\\\\/].*", + "info[\\\\/]LICENSE.*", + "info[\\\\/]requires", + "info[\\\\/]meta", + "info[\\\\/]platform", + "info[\\\\/]no_link", + "info[\\\\/]link\\.json", + "info[\\\\/]icon\\.png", + ), + ) + + +def _checksum(fd, algorithm, buffersize=65536): + hash_impl = getattr(hashlib, algorithm) + if not hash_impl: + raise ValueError(f"Unrecognized hash algorithm: {algorithm}") + else: + hash_impl = hash_impl() + for block in iter(lambda: fd.read(buffersize), b""): + hash_impl.update(block) + return hash_impl.hexdigest() + + +def sha256_checksum(fd): + return _checksum(fd, "sha256") + + +def md5_checksum(fd): + return _checksum(fd, "md5") + + +def checksum(fn, algorithm, buffersize=1 << 18): + """ + Calculate a checksum for a filename (not an open file). + """ + with open(fn, "rb") as fd: + return _checksum(fd, algorithm, buffersize) + + +def checksums(fn, algorithms, buffersize=1 << 18): + """ + Calculate multiple checksums for a filename in parallel. + """ + with ThreadPoolExecutor(max_workers=len(algorithms)) as e: + # take care not to share hash_impl between threads + results = [e.submit(checksum, fn, algorithm, buffersize) for algorithm in algorithms] + return [result.result() for result in results] + + +def anonymize_tarinfo(tarinfo): + """ + Remove user id, name from tarinfo. + """ + # also remove timestamps? + tarinfo.uid = 0 + tarinfo.uname = "" + tarinfo.gid = 0 + tarinfo.gname = "" + return tarinfo diff --git a/miniconda3/lib/python3.13/site-packages/conda_package_handling/validate.py b/miniconda3/lib/python3.13/site-packages/conda_package_handling/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..024d71af293153b500a273fe2f45ba641eb48945 --- /dev/null +++ b/miniconda3/lib/python3.13/site-packages/conda_package_handling/validate.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import hashlib +import os +from itertools import chain +from pathlib import Path + +from conda_package_streaming import package_streaming + +from .utils import TemporaryDirectory + + +def validate_converted_files_match( + src_file_or_folder, subject, reference_ext="" +): # pragma: nocover + # No longer used by conda-package-handling + from .api import extract + + with TemporaryDirectory() as tmpdir: + assert tmpdir is not None + if os.path.isdir(src_file_or_folder): + src_folder = src_file_or_folder + else: + extract(src_file_or_folder + reference_ext, dest_dir=os.path.join(tmpdir, "src")) + src_folder = os.path.join(tmpdir, "src") + + converted_folder = os.path.join(tmpdir, "converted") + extract(subject, dest_dir=converted_folder) + + missing_files = set() + mismatch_size = set() + for root, dirs, files in os.walk(src_folder): + for f in files: + absfile = os.path.join(root, f) + rp = os.path.relpath(absfile, src_folder) + destpath = os.path.join(converted_folder, rp) + if not os.path.islink(destpath): + if not os.path.isfile(destpath): + missing_files.add(rp) + elif os.stat(absfile).st_size != os.stat(destpath).st_size: + mismatch_size.add(rp) + return src_file_or_folder, missing_files, mismatch_size + + +def hash_fn(): + return hashlib.blake2b() + + +IGNORE_FIELDS = { + "uid", + "gid", + "mtime", + "uname", + "gname", + "chksum", +} #: ignore if not strict + + +def validate_converted_files_match_streaming( + src: str | Path, reference: str | Path, *, strict=True +): + """ + Check that two .tar.bz2 or .conda files (either of src_file and + reference_file can be either format) match exactly, down to the timestamps + etc. + + Does not check outside of the info- and pkg- components of a .conda. + (conda's metadata.json, which gives the version "2" of the format) + + If strict = True, also check for matching uid, gid, mtime, uname, gname. + """ + source_set = {} + reference_set = {} + ignore_fields = {"chksum"} if strict else IGNORE_FIELDS + + def get_fileset(filename: str | Path): + fileset = {} + components = ["info", "pkg"] if os.fspath(filename).endswith(".conda") else ["pkg"] + with open(filename, "rb") as conda_file: + for component in components: + for tar, member in package_streaming.stream_conda_component( + filename, conda_file, component + ): + info = {k: v for k, v in member.get_info().items() if k not in ignore_fields} + + if member.isfile(): + hasher = hash_fn() + fd = tar.extractfile(member) + assert fd is not None + for block in iter(lambda: fd.read(1 << 18), b""): # type: ignore + hasher.update(block) + + info["digest"] = hasher.hexdigest() + + fileset[info["name"]] = info + + return fileset + + source_set = get_fileset(src) + reference_set = get_fileset(reference) + + missing = [] + mismatched = [] + + if source_set != reference_set: + for file in chain(source_set, reference_set): + if not (file in source_set and file in reference_set): + missing.append(file) + elif source_set[file] != reference_set[file]: + mismatched.append(file) + + return src, missing, mismatched