diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/about.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/about.json new file mode 100644 index 0000000000000000000000000000000000000000..bdd5348efab52ae389a02ff2b311a105e4defd1e --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/about.json @@ -0,0 +1,163 @@ +{ + "channels": [ + "https://repo.anaconda.com/pkgs/main", + "https://repo.anaconda.com/pkgs/r", + "https://repo.anaconda.com/pkgs/main" + ], + "conda_build_version": "25.1.2", + "conda_version": "25.1.1", + "description": "A library to query system architecture", + "dev_url": "https://github.com/archspec/archspec/", + "doc_url": "https://archspec.readthedocs.io/", + "env_vars": { + "CIO_TEST": "" + }, + "extra": { + "copy_test_source_files": true, + "final": true, + "recipe-maintainers": [ + "anthchirp", + "isuruf" + ] + }, + "home": "https://pypi.org/project/archspec/", + "identifiers": [], + "keywords": [], + "license": "MIT OR Apache-2.0", + "license_file": [ + "LICENSE-MIT", + "LICENSE-APACHE" + ], + "root_pkgs": [ + "_libgcc_mutex 0.1 main", + "ca-certificates 2025.9.9 h06a4308_0", + "ld_impl_linux-64 2.40 h12ee557_0", + "libstdcxx-ng 11.2.0 h1234567_1", + "nlohmann_json 3.11.2 h6a678d5_0", + "pybind11-abi 5 hd3eb1b0_0", + "tzdata 2025a h04d1e81_0", + "libgomp 11.2.0 h1234567_1", + "_openmp_mutex 5.1 1_gnu", + "libgcc-ng 11.2.0 h1234567_1", + "bzip2 1.0.8 h5eee18b_6", + "c-ares 1.19.1 h5eee18b_0", + "cpp-expected 1.1.0 hdb19cb5_0", + "expat 2.6.4 h6a678d5_0", + "fmt 9.1.0 hdb19cb5_1", + "icu 73.1 h6a678d5_0", + "libev 4.33 h7f8727e_1", + "libffi 3.4.4 h6a678d5_1", + "libuuid 1.41.5 h5eee18b_0", + "lz4-c 1.9.4 h6a678d5_1", + "ncurses 6.4 h6a678d5_0", + "liblief 0.12.3 h6a678d5_0", + "reproc 14.2.4 h6a678d5_2", + "simdjson 3.10.1 hdb19cb5_0", + "xz 5.4.6 h5eee18b_1", + "yaml-cpp 0.8.0 h6a678d5_1", + "zlib 1.2.13 h5eee18b_1", + "libedit 3.1.20230828 h5eee18b_0", + "libnghttp2 1.57.0 h2d74bed_0", + "libssh2 1.11.1 h251f7ec_0", + "libxml2 2.13.5 hfdd30dd_0", + "pcre2 10.42 hebb0a14_1", + "readline 8.2 h5eee18b_0", + "reproc-cpp 14.2.4 h6a678d5_2", + "spdlog 1.11.0 hdb19cb5_0", + "tk 8.6.14 h39e8969_0", + "zstd 1.5.6 hc292b87_0", + "krb5 1.20.1 h143b758_1", + "libarchive 3.7.7 hfab0078_0", + "libsolv 0.7.30 he621ea3_1", + "sqlite 3.45.3 h5eee18b_0", + "libcurl 8.11.1 hc9e6f67_0", + "python 3.12.9 h5148396_0", + "libmamba 2.0.5 haf1ee3a_1", + "menuinst 2.2.0 py312h06a4308_1", + "anaconda-anon-usage 0.5.0 py312hfc0e8ea_100", + "annotated-types 0.6.0 py312h06a4308_0", + "archspec 0.2.3 pyhd3eb1b0_0", + "boltons 24.1.0 py312h06a4308_0", + "brotli-python 1.0.9 py312h6a678d5_9", + "charset-normalizer 3.3.2 pyhd3eb1b0_0", + "distro 1.9.0 py312h06a4308_0", + "frozendict 2.4.2 py312h06a4308_0", + "idna 3.7 py312h06a4308_0", + "jsonpointer 2.1 pyhd3eb1b0_0", + "libmambapy 2.0.5 py312hdb19cb5_1", + "mdurl 0.1.0 py312h06a4308_0", + "packaging 24.2 py312h06a4308_0", + "platformdirs 3.10.0 py312h06a4308_0", + "pluggy 1.5.0 py312h06a4308_0", + "pycosat 0.6.6 py312h5eee18b_2", + "pycparser 2.21 pyhd3eb1b0_0", + "pygments 2.15.1 py312h06a4308_1", + "pysocks 1.7.1 py312h06a4308_0", + "ruamel.yaml.clib 0.2.8 py312h5eee18b_0", + "setuptools 75.8.0 py312h06a4308_0", + "tqdm 4.67.1 py312he106c6f_0", + "truststore 0.10.0 py312h06a4308_0", + "typing_extensions 4.12.2 py312h06a4308_0", + "wheel 0.45.1 py312h06a4308_0", + "cffi 1.17.1 py312h1fdaa30_1", + "jsonpatch 1.33 py312h06a4308_1", + "markdown-it-py 2.2.0 py312h06a4308_1", + "pip 25.0 py312h06a4308_0", + "ruamel.yaml 0.18.6 py312h5eee18b_0", + "typing-extensions 4.12.2 py312h06a4308_0", + "urllib3 2.3.0 py312h06a4308_0", + "cryptography 43.0.3 py312h7825ff9_1", + "pydantic-core 2.27.1 py312h4aa5aa6_0", + "requests 2.32.3 py312h06a4308_1", + "rich 13.9.4 py312h06a4308_0", + "zstandard 0.23.0 py312h2c38b39_1", + "conda-content-trust 0.2.0 py312h06a4308_1", + "conda-package-streaming 0.11.0 py312h06a4308_0", + "pydantic 2.10.3 py312h06a4308_0", + "conda-package-handling 2.4.0 py312h06a4308_0", + "conda 25.1.1 py312h06a4308_0", + "conda-anaconda-tos 0.1.2 py312h06a4308_0", + "conda-libmamba-solver 25.1.1 pyhd3eb1b0_0", + "libsodium 1.0.18 h7b6447c_0", + "openssl 3.0.17 h5eee18b_0", + "patch 2.8 hb25bd0a_0", + "patchelf 0.17.2 h6a678d5_0", + "yaml 0.2.5 h7b6447c_0", + "argcomplete 3.6.2 py312h06a4308_0", + "attrs 24.3.0 py312h06a4308_0", + "certifi 2025.8.3 py312h06a4308_0", + "chardet 5.2.0 py312h06a4308_0", + "click 8.2.1 py312h06a4308_0", + "filelock 3.17.0 py312h06a4308_0", + "jmespath 1.0.1 py312h06a4308_0", + "markupsafe 3.0.2 py312h5eee18b_0", + "more-itertools 10.3.0 py312h06a4308_0", + "pkginfo 1.12.0 py312h06a4308_0", + "psutil 7.0.0 py312hee96239_0", + "py-lief 0.12.3 py312h6a678d5_0", + "python-libarchive-c 5.1 pyhd3eb1b0_0", + "pytz 2025.2 py312h06a4308_0", + "pyyaml 6.0.2 py312h5eee18b_0", + "rpds-py 0.22.3 py312h4aa5aa6_0", + "six 1.17.0 py312h06a4308_0", + "soupsieve 2.5 py312h06a4308_0", + "tomlkit 0.13.2 py312h06a4308_0", + "xmltodict 0.14.2 py312h06a4308_0", + "jinja2 3.1.6 py312h06a4308_0", + "python-dateutil 2.9.0post0 py312h06a4308_2", + "referencing 0.30.2 py312h06a4308_0", + "yq 3.4.3 py312h06a4308_0", + "beautifulsoup4 4.13.5 py312h06a4308_0", + "botocore 1.37.10 py312h06a4308_0", + "jsonschema-specifications 2023.7.1 py312h06a4308_0", + "pynacl 1.5.0 py312h5eee18b_1", + "jsonschema 4.25.0 py312h06a4308_0", + "s3transfer 0.11.2 py312h06a4308_0", + "boto3 1.37.10 py312h06a4308_0", + "conda-anaconda-telemetry 0.3.0 pyhd3eb1b0_1", + "conda-index 0.5.0 py312h06a4308_0", + "conda-build 25.1.2 py312h06a4308_0" + ], + "summary": "A library to query system architecture", + "tags": [] +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/files b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/files new file mode 100644 index 0000000000000000000000000000000000000000..7ba45b5d395770c207cbdbebd6234fdc52cc3c8c --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/files @@ -0,0 +1,76 @@ +site-packages/archspec-0.2.5.dist-info/INSTALLER +site-packages/archspec-0.2.5.dist-info/METADATA +site-packages/archspec-0.2.5.dist-info/RECORD +site-packages/archspec-0.2.5.dist-info/REQUESTED +site-packages/archspec-0.2.5.dist-info/WHEEL +site-packages/archspec-0.2.5.dist-info/direct_url.json +site-packages/archspec-0.2.5.dist-info/entry_points.txt +site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-APACHE +site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-MIT +site-packages/archspec-0.2.5.dist-info/licenses/NOTICE +site-packages/archspec/__init__.py +site-packages/archspec/__main__.py +site-packages/archspec/cli.py +site-packages/archspec/cpu/__init__.py +site-packages/archspec/cpu/alias.py +site-packages/archspec/cpu/detect.py +site-packages/archspec/cpu/microarchitecture.py +site-packages/archspec/cpu/schema.py +site-packages/archspec/json/COPYRIGHT +site-packages/archspec/json/LICENSE-APACHE +site-packages/archspec/json/LICENSE-MIT +site-packages/archspec/json/NOTICE +site-packages/archspec/json/README.md +site-packages/archspec/json/cpu/cpuid.json +site-packages/archspec/json/cpu/cpuid_schema.json +site-packages/archspec/json/cpu/microarchitectures.json +site-packages/archspec/json/cpu/microarchitectures_schema.json +site-packages/archspec/json/tests/targets/bgq-rhel6-power7 +site-packages/archspec/json/tests/targets/darwin-bigsur-m1 +site-packages/archspec/json/tests/targets/darwin-mojave-haswell +site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge +site-packages/archspec/json/tests/targets/darwin-mojave-skylake +site-packages/archspec/json/tests/targets/darwin-monterey-m1 +site-packages/archspec/json/tests/targets/darwin-monterey-m2 +site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72 +site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1 +site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1 +site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids +site-packages/archspec/json/tests/targets/linux-asahi-m1 +site-packages/archspec/json/tests/targets/linux-asahi-m2 +site-packages/archspec/json/tests/targets/linux-centos7-cascadelake +site-packages/archspec/json/tests/targets/linux-centos7-power8le +site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 +site-packages/archspec/json/tests/targets/linux-rhel6-piledriver +site-packages/archspec/json/tests/targets/linux-rhel7-broadwell +site-packages/archspec/json/tests/targets/linux-rhel7-haswell +site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge +site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512 +site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 +site-packages/archspec/json/tests/targets/linux-rhel7-zen +site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 +site-packages/archspec/json/tests/targets/linux-rhel8-power9 +site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2 +site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2 +site-packages/archspec/json/tests/targets/linux-rocky8-a64fx +site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4 +site-packages/archspec/json/tests/targets/linux-rocky9-zen5 +site-packages/archspec/json/tests/targets/linux-scientific7-k10 +site-packages/archspec/json/tests/targets/linux-scientific7-piledriver +site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer +site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver +site-packages/archspec/json/tests/targets/linux-sifive-u74mc +site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell +site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3 +site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2 +site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2 +site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 +site-packages/archspec/json/tests/targets/linux-unknown-power10 +site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids +site-packages/archspec/json/tests/targets/windows-cpuid-broadwell +site-packages/archspec/json/tests/targets/windows-cpuid-icelake +site-packages/archspec/vendor/cpuid/.gitignore +site-packages/archspec/vendor/cpuid/LICENSE +site-packages/archspec/vendor/cpuid/README.md +site-packages/archspec/vendor/cpuid/cpuid.py +site-packages/archspec/vendor/cpuid/example.py diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/git b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/git new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/hash_input.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/hash_input.json new file mode 100644 index 0000000000000000000000000000000000000000..03c137a2d34204d05990e03d3dfb47a87a927cbc --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/hash_input.json @@ -0,0 +1,3 @@ +{ + "channel_targets": "defaults" +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/index.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/index.json new file mode 100644 index 0000000000000000000000000000000000000000..90484ab966c1e9a27bb61782a6901e31ce209438 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/index.json @@ -0,0 +1,15 @@ +{ + "arch": null, + "build": "pyhd3eb1b0_0", + "build_number": 0, + "depends": [ + "python >=3.7" + ], + "license": "MIT OR Apache-2.0", + "name": "archspec", + "noarch": "python", + "platform": null, + "subdir": "noarch", + "timestamp": 1758125010311, + "version": "0.2.5" +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/link.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/link.json new file mode 100644 index 0000000000000000000000000000000000000000..89cc4ffea79d2d7f53763ce37ee73c6e8b716412 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/link.json @@ -0,0 +1,9 @@ +{ + "noarch": { + "entry_points": [ + "archspec = archspec.cli:main" + ], + "type": "python" + }, + "package_metadata_version": 1 +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/paths.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/paths.json new file mode 100644 index 0000000000000000000000000000000000000000..d8d4d3a9ffa74173cda1b7ad5e1cfc7ee197da86 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/paths.json @@ -0,0 +1,461 @@ +{ + "paths": [ + { + "_path": "site-packages/archspec-0.2.5.dist-info/INSTALLER", + "path_type": "hardlink", + "sha256": "d0edee15f91b406f3f99726e44eb990be6e34fd0345b52b910c568e0eef6a2a8", + "size_in_bytes": 5 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/METADATA", + "path_type": "hardlink", + "sha256": "46c6be9472a57abf0c5ff8e11f0c9a7f042ef79bbcb40d20a81067788a1c289e", + "size_in_bytes": 4565 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/RECORD", + "path_type": "hardlink", + "sha256": "6637105b748aa7c845d167cf461a32a8f38c60db5a220680888505e8050204a2", + "size_in_bytes": 8188 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/REQUESTED", + "path_type": "hardlink", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size_in_bytes": 0 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/WHEEL", + "path_type": "hardlink", + "sha256": "3396ac9a20252fa1c470eab9d988b99a693d2a64d58d8d910cfb4ee29f4332b7", + "size_in_bytes": 88 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/direct_url.json", + "path_type": "hardlink", + "sha256": "b446a7927eb5d640640b58f9af3f75ac020c9b3cf899c52255e09b0e28870e6c", + "size_in_bytes": 98 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/entry_points.txt", + "path_type": "hardlink", + "sha256": "bfaba68aee5e4120fad3cf158b2be48e573559548728ad0b00331aeeb329366e", + "size_in_bytes": 46 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-APACHE", + "path_type": "hardlink", + "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "size_in_bytes": 11358 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/licenses/LICENSE-MIT", + "path_type": "hardlink", + "sha256": "9001ad99a662075a0e5a6a9a539fc75040d8063c3f7251d6839ca40b5234054e", + "size_in_bytes": 1171 + }, + { + "_path": "site-packages/archspec-0.2.5.dist-info/licenses/NOTICE", + "path_type": "hardlink", + "sha256": "f4247dde07952a5ff866b24e45b5cdd1fce410cdb2e038255a1635867f59c10c", + "size_in_bytes": 1167 + }, + { + "_path": "site-packages/archspec/__init__.py", + "path_type": "hardlink", + "sha256": "97fbc61f8c0a5c1e5b9a0ed9a8d87ec40f04554929269012e65ed5d3b89cd241", + "size_in_bytes": 67 + }, + { + "_path": "site-packages/archspec/__main__.py", + "path_type": "hardlink", + "sha256": "959bb70b63fd15b3a51391817a8493aa074fc9cbdc41c2fb37c8a1b1d6465d83", + "size_in_bytes": 97 + }, + { + "_path": "site-packages/archspec/cli.py", + "path_type": "hardlink", + "sha256": "aa0a971fef5bd5b6ecb26d342ce4267a26644ee649220ca65f001bb420d593d6", + "size_in_bytes": 1691 + }, + { + "_path": "site-packages/archspec/cpu/__init__.py", + "path_type": "hardlink", + "sha256": "3849055313ded2f79124bd9b778918c3313c7c9f3f57d500b4c0766c4c8056c3", + "size_in_bytes": 727 + }, + { + "_path": "site-packages/archspec/cpu/alias.py", + "path_type": "hardlink", + "sha256": "1ab24f6965faf85b687a9177cf61bc4708a4681fbfb251d54f9e32150b4e2d4d", + "size_in_bytes": 2506 + }, + { + "_path": "site-packages/archspec/cpu/detect.py", + "path_type": "hardlink", + "sha256": "cc87754662ad124dfae7c3374950f5ff1103ffd52c291216313b0e4b9122e61c", + "size_in_bytes": 16302 + }, + { + "_path": "site-packages/archspec/cpu/microarchitecture.py", + "path_type": "hardlink", + "sha256": "23f5eaa08ba637896731beb5c7f3d012c2151089ddb2f113e26779b08ee31091", + "size_in_bytes": 15210 + }, + { + "_path": "site-packages/archspec/cpu/schema.py", + "path_type": "hardlink", + "sha256": "f029d45031b35da686a9b852390093613df07e814b8f8a85bc579e741b44e5b3", + "size_in_bytes": 3687 + }, + { + "_path": "site-packages/archspec/json/COPYRIGHT", + "path_type": "hardlink", + "sha256": "9d70c5a837efa62df7ee37df1c70ddffc0bb38e38df29ddfdcfa01462407cdfb", + "size_in_bytes": 805 + }, + { + "_path": "site-packages/archspec/json/LICENSE-APACHE", + "path_type": "hardlink", + "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "size_in_bytes": 11358 + }, + { + "_path": "site-packages/archspec/json/LICENSE-MIT", + "path_type": "hardlink", + "sha256": "9001ad99a662075a0e5a6a9a539fc75040d8063c3f7251d6839ca40b5234054e", + "size_in_bytes": 1171 + }, + { + "_path": "site-packages/archspec/json/NOTICE", + "path_type": "hardlink", + "sha256": "f4247dde07952a5ff866b24e45b5cdd1fce410cdb2e038255a1635867f59c10c", + "size_in_bytes": 1167 + }, + { + "_path": "site-packages/archspec/json/README.md", + "path_type": "hardlink", + "sha256": "8b31bb4ce98f6fbeb47019956b09cfb33c54b41972caf1e62a8c45adfddf2be8", + "size_in_bytes": 1531 + }, + { + "_path": "site-packages/archspec/json/cpu/cpuid.json", + "path_type": "hardlink", + "sha256": "800591e7b1a881a9c7ba97595f9eefd82c172d5a214a4c768719052ffaf4f8ed", + "size_in_bytes": 20572 + }, + { + "_path": "site-packages/archspec/json/cpu/cpuid_schema.json", + "path_type": "hardlink", + "sha256": "c081db214332c2d8de0676471b02f683adac6da829eb0ace363db1f72dfaa738", + "size_in_bytes": 3129 + }, + { + "_path": "site-packages/archspec/json/cpu/microarchitectures.json", + "path_type": "hardlink", + "sha256": "ba9598c4b6ec4e157f60943918f5d700be9dd150facad3d6f9656a048294d983", + "size_in_bytes": 85601 + }, + { + "_path": "site-packages/archspec/json/cpu/microarchitectures_schema.json", + "path_type": "hardlink", + "sha256": "1241d86d67c7b3693beb941853682ca04c68715fe4f71b7eff72ea02c1aa8695", + "size_in_bytes": 3025 + }, + { + "_path": "site-packages/archspec/json/tests/targets/bgq-rhel6-power7", + "path_type": "hardlink", + "sha256": "efc8296d50ed99a7a1c66f88e77fc90fdfed62bf2690325f503f5d03de5a9058", + "size_in_bytes": 116 + }, + { + "_path": "site-packages/archspec/json/tests/targets/darwin-bigsur-m1", + "path_type": "hardlink", + "sha256": "71c5c33f8a0635b3ad4c0d7a665f67b6e87947926a9c196f6504fa9b7538e13c", + "size_in_bytes": 534 + }, + { + "_path": "site-packages/archspec/json/tests/targets/darwin-mojave-haswell", + "path_type": "hardlink", + "sha256": "c7676a2a8e0f6324230383b6f659864ae26ebdb3f0b13e0b1d8b7ad0fb74fec3", + "size_in_bytes": 553 + }, + { + "_path": "site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge", + "path_type": "hardlink", + "sha256": "6045156b145266635ad8da790e98c059d170146fa8f369e354a9b040329595dc", + "size_in_bytes": 2356 + }, + { + "_path": "site-packages/archspec/json/tests/targets/darwin-mojave-skylake", + "path_type": "hardlink", + "sha256": "1de9a687a33406f1ecd389eed8d10bcb6d0238c2fff781b5cc7e1b02e994fdd8", + "size_in_bytes": 598 + }, + { + "_path": "site-packages/archspec/json/tests/targets/darwin-monterey-m1", + "path_type": "hardlink", + "sha256": "5921bd3b8e3a43f4920fdbc7b988f549a236cc0e83846b45dd4536d316e767db", + "size_in_bytes": 3307 + }, + { + "_path": "site-packages/archspec/json/tests/targets/darwin-monterey-m2", + "path_type": "hardlink", + "sha256": "1310acde662c01bdcbb7a6570cb235a5a9bd5ab11f0cd561a1da617d503b2bac", + "size_in_bytes": 3307 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72", + "path_type": "hardlink", + "sha256": "3fb6008a9bee765a365353ef51ad357434761ca41444f781d8f1cdbbb90745eb", + "size_in_bytes": 221 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1", + "path_type": "hardlink", + "sha256": "cef1c93aa2f31dfe1c4ec7259689815f689264d2b8e4c899d33da327d01e0ea9", + "size_in_bytes": 276 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1", + "path_type": "hardlink", + "sha256": "d91b16bca108c87c5542e9c1460fd7ef5addbead9d84f29184a72c61d59bf36e", + "size_in_bytes": 361 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids", + "path_type": "hardlink", + "sha256": "69181ab4ebd026a24a9c8eb6602e850ae1f188c5ad9f099b6b6d3f2a8d1723e9", + "size_in_bytes": 1519 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-asahi-m1", + "path_type": "hardlink", + "sha256": "84a10e95ba66915e35ff5f03f9732283c4d95761626492e706363066da4dac84", + "size_in_bytes": 363 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-asahi-m2", + "path_type": "hardlink", + "sha256": "48a12dbf702133e673cf2afde06162aeb1795092894ce399a8adf72ae95a0622", + "size_in_bytes": 381 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-centos7-cascadelake", + "path_type": "hardlink", + "sha256": "618768f06d1b3fce5b9f874675678f343b6112d0218632954525ecdcced88e0f", + "size_in_bytes": 1408 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-centos7-power8le", + "path_type": "hardlink", + "sha256": "2a09064a41cba64daf3f88f45b79bb8877b9e7d7fea716b6ae25ad02420c471a", + "size_in_bytes": 111 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-centos7-thunderx2", + "path_type": "hardlink", + "sha256": "2bcc6c9eadd6ec40be3d7bf98f732c1ab6aea3038044638a8f7ffbfa83ac3492", + "size_in_bytes": 238 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel6-piledriver", + "path_type": "hardlink", + "sha256": "dd89d0a53060062ec566d482ac98c0831f438c57bddbeb18a15240a6b3012bfa", + "size_in_bytes": 1411 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel7-broadwell", + "path_type": "hardlink", + "sha256": "1c15848b2136b8a0d8452dc2d2b2aca486ffe50ca96397ecf7834710349a3cbd", + "size_in_bytes": 1187 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel7-haswell", + "path_type": "hardlink", + "sha256": "92adaa92ee78a8f89cfeaf829cec3e4548f59d74c6eac6470540cc84cc99cfd8", + "size_in_bytes": 1095 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge", + "path_type": "hardlink", + "sha256": "3c2d4d2f0f404c1ac237bcc742ccf16ef1d5bcc1cbd71505a55d689fde1433a4", + "size_in_bytes": 1009 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512", + "path_type": "hardlink", + "sha256": "dc523c693fba3b0056135e452a8443cd38b3e415ea5d84799c5353060ed8f50c", + "size_in_bytes": 1286 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3", + "path_type": "hardlink", + "sha256": "0fa88a864f4a4256fda987ad3dd50198354d015afe846576f7bbc31cbc1ed853", + "size_in_bytes": 1172 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel7-zen", + "path_type": "hardlink", + "sha256": "89cc9b64203e6d7b9ab272474bfaa7534b41a50823cbafa30d18ad482db42751", + "size_in_bytes": 1319 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1", + "path_type": "hardlink", + "sha256": "82d0bee8c360a4f4e15ff1d86181c48af86ab62ac1df62253ec71523b917dc3d", + "size_in_bytes": 351 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel8-power9", + "path_type": "hardlink", + "sha256": "2f2d25d3092ef3408c762cefd5408a131d928a9f52ff405dd0f4c27d03d81cb7", + "size_in_bytes": 135 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2", + "path_type": "hardlink", + "sha256": "b6943d786ef68827a6c1accc316fdf19e982813692be7dc92147c95bbe30c89c", + "size_in_bytes": 429 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2", + "path_type": "hardlink", + "sha256": "5c357df05bc0a3b45d988f91a52fda87ca5d31601c98efec9e22798f58952070", + "size_in_bytes": 444 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rocky8-a64fx", + "path_type": "hardlink", + "sha256": "ad5a3ebaa6042679603d70216edf8b6b55b6e4247fc5f6f4deb874b79db4ff53", + "size_in_bytes": 256 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4", + "path_type": "hardlink", + "sha256": "cb850341d3b1b20d07978eb55e5043fed3dbfd35fc11c5d5edbc221d09facc53", + "size_in_bytes": 1750 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-rocky9-zen5", + "path_type": "hardlink", + "sha256": "fc770d91f4f942360e976ff9e71240fa07760c5be68421ce6712b7abadeb179a", + "size_in_bytes": 1882 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-scientific7-k10", + "path_type": "hardlink", + "sha256": "c4485009ce4222a0563a87b6f2bbeb5be0678d94a438406fd205cb40ce720271", + "size_in_bytes": 1111 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-scientific7-piledriver", + "path_type": "hardlink", + "sha256": "90a0aca60ea06a65a031ef61f4cc7984fe4ed435e05ce23a887d81d817f08c38", + "size_in_bytes": 1149 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer", + "path_type": "hardlink", + "sha256": "6666e836acd912c596c0ec0157fbe6acd222eb1d44dc4efa533e048f5e45bb6b", + "size_in_bytes": 1201 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver", + "path_type": "hardlink", + "sha256": "e69559a553d7b4a9aa28ad4fb362e661a8025a15936e3239728ff54236236712", + "size_in_bytes": 1099 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-sifive-u74mc", + "path_type": "hardlink", + "sha256": "3469efadc2b754fe2a99693b7993480203440facafc9f70405ab0c4e6b0781c9", + "size_in_bytes": 124 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell", + "path_type": "hardlink", + "sha256": "0336f7c5cf56be0c41bd044d0b99bcdd2269aabef788bac6489549e6ce3fccd2", + "size_in_bytes": 1190 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3", + "path_type": "hardlink", + "sha256": "63b0b0b38930cc194dba94211a5ff6c2803fd7f496c51ab08339fd35a4f7fe48", + "size_in_bytes": 1531 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2", + "path_type": "hardlink", + "sha256": "4d1e82e075f6411722500c3368949f4f12fb2b8dbb3670bf4a57e7513ab115ee", + "size_in_bytes": 396 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2", + "path_type": "hardlink", + "sha256": "16b9041b19dffa29dd0f3521bb2c6830b894440b82fb659d939f8561fd293928", + "size_in_bytes": 458 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2", + "path_type": "hardlink", + "sha256": "8507c39b6b5cc917f7fa4c21313528c36699ba3c6a6d5967cd412335ac500b78", + "size_in_bytes": 447 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-unknown-power10", + "path_type": "hardlink", + "sha256": "ee7b425a65c60932647d930c074988024edf7b627b3653b5d63d248ca91a4943", + "size_in_bytes": 83 + }, + { + "_path": "site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids", + "path_type": "hardlink", + "sha256": "f000242685da2e436199c32a529ef6e53fcc2167b2c646ab538a688bf65bd181", + "size_in_bytes": 2187 + }, + { + "_path": "site-packages/archspec/json/tests/targets/windows-cpuid-broadwell", + "path_type": "hardlink", + "sha256": "a61d13450a2bd6cdf78fd2158ed6c4e990f8fb0abb8a296dcb6be755be141c39", + "size_in_bytes": 395 + }, + { + "_path": "site-packages/archspec/json/tests/targets/windows-cpuid-icelake", + "path_type": "hardlink", + "sha256": "6f62659a73e2505e49065de31c29a444fbe89fdbc213bfece4d8cfa61e441ab2", + "size_in_bytes": 432 + }, + { + "_path": "site-packages/archspec/vendor/cpuid/.gitignore", + "path_type": "hardlink", + "sha256": "251a4549455fb87bf9785820de268cbedab484ef8c36b60aab5a55c25ad7a7d3", + "size_in_bytes": 12 + }, + { + "_path": "site-packages/archspec/vendor/cpuid/LICENSE", + "path_type": "hardlink", + "sha256": "0df811360326d9f455ddf102055348fda0c0318c5cd3abcaafe2aad2bb6db2ee", + "size_in_bytes": 1079 + }, + { + "_path": "site-packages/archspec/vendor/cpuid/README.md", + "path_type": "hardlink", + "sha256": "50f2aa1a7563b25b22191d8681726ffadc2761d9c59e6085dffb7908b5e66344", + "size_in_bytes": 2400 + }, + { + "_path": "site-packages/archspec/vendor/cpuid/cpuid.py", + "path_type": "hardlink", + "sha256": "872c252864cab4f5f24b2272ebb77838ba5a40b7f07ec3e052f48f75ac5a9d14", + "size_in_bytes": 6037 + }, + { + "_path": "site-packages/archspec/vendor/cpuid/example.py", + "path_type": "hardlink", + "sha256": "83711400d1aece1bbad65e99fb988b79d3c47bfbdf39b2b1cacf91e6a9c8e8c6", + "size_in_bytes": 1855 + } + ], + "paths_version": 1 +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/repodata_record.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/repodata_record.json new file mode 100644 index 0000000000000000000000000000000000000000..ef5a024c0679625b48de0df9286b2fdaa890c0e9 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/info/repodata_record.json @@ -0,0 +1,21 @@ +{ + "build": "pyhd3eb1b0_0", + "build_number": 0, + "channel": "https://repo.anaconda.com/pkgs/main/noarch/", + "constrains": [], + "depends": [ + "python >=3.7" + ], + "fn": "archspec-0.2.5-pyhd3eb1b0_0.conda", + "license": "MIT OR Apache-2.0", + "md5": "c0ad195970a65c174b997011ac13f2f8", + "name": "archspec", + "noarch": "python", + "package_type": "noarch_python", + "sha256": "d7c38d818d5f88e636de5d9fba2365be56f3230ee2656ab3b552c1e4bbd07668", + "size": 49261, + "subdir": "noarch", + "timestamp": 1758125010000, + "url": "https://repo.anaconda.com/pkgs/main/noarch/archspec-0.2.5-pyhd3eb1b0_0.conda", + "version": "0.2.5" +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/INSTALLER b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/METADATA b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..499927d778be66a399ff512b866409c4ba7a7c8c --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/RECORD b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f75096c401fa947de902b18930f9f2b5ca819262 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/REQUESTED b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/WHEEL b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9f0d68ff7fc3c1ff6da960ed2ffd70dd8ea16896 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/direct_url.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..a6165286c803f9d8801a84db325aa9a341ebc9d5 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/entry_points.txt b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f3dc153b53f4ca570f5707b5e12f0401d98ec7d --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec-0.2.5.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +archspec=archspec.cli:main + diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/__init__.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2425354e623ab3e58c65ab9aa67e4c7d884053b4 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/__init__.py @@ -0,0 +1,3 @@ +"""Init file to avoid namespace packages""" + +__version__ = "0.2.5" diff --git a/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/__main__.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..45fbe12704517a629bf56fa10fbb6e32672c9d74 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cli.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..eaddaf5d77bef895fc6a6104c0f4b6b16ff83735 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/__init__.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbb43b785db83b1639f8cb9c0b228ab10741eeb --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/alias.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/alias.py new file mode 100644 index 0000000000000000000000000000000000000000..783a67d3ea9563f05f23ab6cba45ffc7b261aff1 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/detect.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/detect.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f095f78a6c05fb42dbe21b0e2515e76fdcd5a7 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/microarchitecture.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/microarchitecture.py new file mode 100644 index 0000000000000000000000000000000000000000..bb85b9f37c0966b3a7eb30b0a811d4db83a74eed --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/schema.py b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/cpu/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffc2231650b6952d3b9ad2fe6674632100d6607 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/COPYRIGHT b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/COPYRIGHT new file mode 100644 index 0000000000000000000000000000000000000000..4164e98de77169c98f258c4ac8eff4daf9f78f4e --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/LICENSE-APACHE b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/LICENSE-APACHE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/LICENSE-MIT b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/LICENSE-MIT new file mode 100644 index 0000000000000000000000000000000000000000..03be635ad5df4567a85180c7a03a54ee96e1ee98 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/NOTICE b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..3737d5a86ddc20bfd04ce225fff2d34407df06f9 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/README.md b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78c424a86fa348b1b48001b649df8530fa3da2ac --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/cpuid.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/cpuid.json new file mode 100644 index 0000000000000000000000000000000000000000..594e435383ad50c0cd6f71f965b27b54343f502a --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/cpuid_schema.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/cpuid_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8dc5b982eac66a8230a107962882a11d4982240a --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/microarchitectures.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/microarchitectures.json new file mode 100644 index 0000000000000000000000000000000000000000..9275422ef4da53a21daf0b774f9d6ecb622c1d3e --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/microarchitectures_schema.json b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/cpu/microarchitectures_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..085e5b95772e6a71e72afb21678cb1efe731b4d1 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 new file mode 100644 index 0000000000000000000000000000000000000000..39da8a49fe06920f0a9ac714612ccc625551523b --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 new file mode 100644 index 0000000000000000000000000000000000000000..b033bcb90d939d207f6c1bec351843c4ef488634 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-mojave-haswell b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-mojave-haswell new file mode 100644 index 0000000000000000000000000000000000000000..45054c567634d236bacc45274d328e42998b6ff0 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge new file mode 100644 index 0000000000000000000000000000000000000000..6a52d6c19dbe4ef8023f102d795f3f5db996ecfd --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-mojave-skylake b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-mojave-skylake new file mode 100644 index 0000000000000000000000000000000000000000..67dc28a966fc4a8f83fc1d652c78217ed7f773ee --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-monterey-m1 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/darwin-monterey-m1 new file mode 100644 index 0000000000000000000000000000000000000000..de801d480b7694b52927e1a5e0c25bd436f5e2d9 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-asahi-m1 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-asahi-m1 new file mode 100644 index 0000000000000000000000000000000000000000..11f48d1832a52a49b47aa575a2d94a4d00b787f2 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake new file mode 100644 index 0000000000000000000000000000000000000000..e409c3d07a18c826fd9c7742b3e199cccae30d8b --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-centos7-power8le b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-centos7-power8le new file mode 100644 index 0000000000000000000000000000000000000000..f21ca85323dd6f47f1bc2b2ab2a1dc9ee5529e91 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 new file mode 100644 index 0000000000000000000000000000000000000000..2447306bac15024241fd123c23cf013dad31b659 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge new file mode 100644 index 0000000000000000000000000000000000000000..7d6cfe4daaed77956694e9c14bd43a3bd739d86f --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 new file mode 100644 index 0000000000000000000000000000000000000000..d6feeccceb82f45bb868e864d0fd7aada6c61548 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel7-zen b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel7-zen new file mode 100644 index 0000000000000000000000000000000000000000..014dec3359e30216065e7aabde5f5671bbf5a1b9 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 new file mode 100644 index 0000000000000000000000000000000000000000..57853e97eafcaba26d569cc96f81213e083893a3 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 new file mode 100644 index 0000000000000000000000000000000000000000..31379fde97b062bf34dd0c0ad71969fbe45a6729 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-scientific7-k10 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-scientific7-k10 new file mode 100644 index 0000000000000000000000000000000000000000..1522b17480e1137f86d1819f17ea8aba0d9bd006 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver new file mode 100644 index 0000000000000000000000000000000000000000..4c823f6e46baab2ee6f204340e76505b3957e0b4 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer new file mode 100644 index 0000000000000000000000000000000000000000..c240cfc6ce94618217d588b98a983d6da438e671 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-sifive-u74mc b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-sifive-u74mc new file mode 100644 index 0000000000000000000000000000000000000000..8c1d29002e6952044d026945e1ab81e11a01dee4 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..bbe287ebf14956e40272be4e06f20d26f5a00cab --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 new file mode 100644 index 0000000000000000000000000000000000000000..09087ac4e8decaf91b3d38151a2b4f13cb342c63 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-unknown-power10 b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-unknown-power10 new file mode 100644 index 0000000000000000000000000000000000000000..ad8b15f9b9039f3bbd1af29e1b392e06b5f429aa --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids new file mode 100644 index 0000000000000000000000000000000000000000..c317b6b6b515c100ddebb14f31d2c3ce5aacc563 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..f19f1d4a475a08736c60a6b5ff40f2a98ca420c2 --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/windows-cpuid-icelake b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/site-packages/archspec/json/tests/targets/windows-cpuid-icelake new file mode 100644 index 0000000000000000000000000000000000000000..dcc0453e4f3418e4e5c965dddd8f2fa7edf5569c --- /dev/null +++ b/data/miniconda3/pkgs/archspec-0.2.5-pyhd3eb1b0_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/fish/conf.d/conda.fish b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/fish/conf.d/conda.fish new file mode 100644 index 0000000000000000000000000000000000000000..4ce5b15f113cfcedabffeea1354f8270ac1db447 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/fish/conf.d/conda.fish @@ -0,0 +1,140 @@ +set -gx CONDA_EXE "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/conda"; +set -gx _CONDA_EXE "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/conda"; +set -e _CE_M || true; +set -e _CE_CONDA || true; +set -gx CONDA_PYTHON_EXE "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python"; +set -gx _CONDA_ROOT "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p"; + +# 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/profile.d/conda.csh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/profile.d/conda.csh new file mode 100644 index 0000000000000000000000000000000000000000..5467a7772a415c4bdfcd8be30d279790964b376e --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/profile.d/conda.csh @@ -0,0 +1,8 @@ +setenv CONDA_EXE "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/conda"; +setenv _CONDA_EXE "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/conda"; +unsetenv _CE_M; +unsetenv _CE_CONDA; +setenv CONDA_PYTHON_EXE "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python"; +setenv _CONDA_ROOT "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p"; + +source "/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh" \ No newline at end of file diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/profile.d/conda.sh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/profile.d/conda.sh new file mode 100644 index 0000000000000000000000000000000000000000..89122f59e6f0829b5b8d72576be0badb22384aec --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/etc/profile.d/conda.sh @@ -0,0 +1,81 @@ +export CONDA_EXE='/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/conda' +export _CONDA_EXE='/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/conda' +export _CE_M='' +export _CE_CONDA='' +export CONDA_PYTHON_EXE='/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python' +export _CONDA_ROOT='/home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p' + +# 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/licenses/conda-src/LICENSE b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/licenses/conda-src/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a2fbff055a4a2c501a54936ad1ec343ea049bce2 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/licenses/conda-src/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/conda_build_config.yaml b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/conda_build_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b5f99003c4661db5470df6895df7ec9692c124c --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/conda_build_config.yaml @@ -0,0 +1,28 @@ +c_compiler: gcc +channel_targets: defaults +cpu_optimization_target: nocona +cran_mirror: https://cran.r-project.org +cxx_compiler: gxx +extend_keys: +- pin_run_as_build +- ignore_version +- ignore_build_only_deps +- extend_keys +fortran_compiler: gfortran +ignore_build_only_deps: +- numpy +- python +lua: '5' +numpy: '1.26' +perl: 5.26.2 +pin_run_as_build: + python: + max_pin: x.x + min_pin: x.x + r-base: + max_pin: x.x + min_pin: x.x +platform: linux-64 +python: '3.13' +r_base: '3.5' +target_platform: linux-64 diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/meta.yaml b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/meta.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3df1c96cf23b640de7c65ed89409501a3fceeb80 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/meta.yaml @@ -0,0 +1,180 @@ +# This file created by conda-build 25.1.2 +# meta.yaml template originally from: +# /home/task_176556791054345/conda-feedstock/recipe, last modified Fri Dec 12 19:32:08 2025 +# ------------------------------------------------ + +package: + name: conda + version: 25.11.1 +source: + folder: conda-src + sha256: 280bee40bfa3dc64a294a3501ae3150fe112e0f51cf94f7a346e5cfb4b370efb + url: https://github.com/conda/conda/releases/download/25.11.1/conda-25.11.1.tar.gz +build: + always_include_files: + - bin/activate + - bin/conda + - bin/deactivate + number: '0' + script: /home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python + -m pip install conda-src/ --no-deps --no-build-isolation -vv && /home/task_176556791054345/conda-bld/conda_1765567979493/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python + -m conda init --install + string: py313h06a4308_0 +requirements: + build: + - _libgcc_mutex 0.1 main + - _openmp_mutex 5.1 1_gnu + - bzip2 1.0.8 h5eee18b_6 + - c-ares 1.34.5 hef5626c_0 + - ca-certificates 2025.12.2 h06a4308_0 + - expat 2.7.3 h7354ed3_4 + - gettext 0.21.0 hedfda30_2 + - git 2.51.0 pl5382h9046301_1 + - icu 73.1 h6a678d5_0 + - jansson 2.14 h5eee18b_1 + - libcurl 8.16.0 heebcbe5_0 + - libev 4.33 h7f8727e_1 + - libexpat 2.7.3 h7354ed3_4 + - libgcc 15.2.0 h69a1729_7 + - libgcc-ng 15.2.0 h166f726_7 + - libgomp 15.2.0 h4751f2c_7 + - libiconv 1.16 h5eee18b_3 + - libidn2 2.3.8 hf80d704_0 + - libnghttp2 1.67.1 h697f920_0 + - libssh2 1.11.1 h251f7ec_0 + - libstdcxx 15.2.0 h39759b7_7 + - libstdcxx-ng 15.2.0 hc03a8fd_7 + - libunistring 1.3 hb25bd0a_0 + - libxcb 1.17.0 h9b100fa_0 + - libxml2 2.13.9 h2c43086_0 + - libzlib 1.3.1 hb25bd0a_0 + - lz4-c 1.9.4 h6a678d5_1 + - ncurses 6.5 h7934f7d_0 + - openssl 3.0.18 hd6dcaed_0 + - pcre2 10.46 hf426167_0 + - perl 5.40.2 0_h5eee18b_perl5 + - pthread-stubs 0.3 h0ce48e5_1 + - tk 8.6.15 h54e0aa7_0 + - xorg-libx11 1.8.12 h9b100fa_1 + - xorg-libxau 1.0.12 h9b100fa_0 + - xorg-libxdmcp 1.1.5 h9b100fa_0 + - xorg-xorgproto 2024.1 h5eee18b_1 + - xz 5.6.4 h5eee18b_1 + - zlib 1.3.1 hb25bd0a_0 + - zstd 1.5.7 h11fc155_0 + host: + - _libgcc_mutex 0.1 main + - _openmp_mutex 5.1 1_gnu + - boltons 25.0.0 py313h06a4308_0 + - brotlicffi 1.2.0.0 py313h7354ed3_0 + - bzip2 1.0.8 h5eee18b_6 + - ca-certificates 2025.12.2 h06a4308_0 + - certifi 2025.11.12 py313h06a4308_0 + - cffi 2.0.0 py313h4eded50_1 + - charset-normalizer 3.4.4 py313h06a4308_0 + - frozendict 2.4.6 py313hee96239_0 + - hatch-vcs 0.5.0 py313h06a4308_0 + - hatchling 1.27.0 py313h06a4308_1 + - idna 3.11 py313h06a4308_0 + - ld_impl_linux-64 2.44 h153f514_2 + - libexpat 2.7.3 h7354ed3_4 + - libffi 3.4.4 h6a678d5_1 + - libgcc 15.2.0 h69a1729_7 + - libgcc-ng 15.2.0 h166f726_7 + - libgomp 15.2.0 h4751f2c_7 + - libmpdec 4.0.0 h5eee18b_0 + - libstdcxx 15.2.0 h39759b7_7 + - libstdcxx-ng 15.2.0 hc03a8fd_7 + - libuuid 1.41.5 h5eee18b_0 + - libxcb 1.17.0 h9b100fa_0 + - libzlib 1.3.1 hb25bd0a_0 + - menuinst 2.4.2 py313h06a4308_1 + - ncurses 6.5 h7934f7d_0 + - openssl 3.0.18 hd6dcaed_0 + - packaging 25.0 py313h06a4308_1 + - pathspec 0.12.1 py313h06a4308_1 + - pip 25.3 pyhc872135_0 + - platformdirs 4.5.0 py313h06a4308_0 + - pluggy 1.5.0 py313h06a4308_0 + - pthread-stubs 0.3 h0ce48e5_1 + - pycparser 2.23 py313h06a4308_0 + - pysocks 1.7.1 py313h06a4308_1 + - python 3.13.11 hcf712cf_100_cp313 + - python_abi 3.13 3_cp313 + - readline 8.3 hc2a1206_0 + - requests 2.32.5 py313h06a4308_1 + - ruamel.yaml 0.18.16 py313h4aee224_0 + - ruamel.yaml.clib 0.2.14 py313h4aee224_0 + - setuptools 80.9.0 py313h06a4308_0 + - setuptools-scm 9.2.2 py313h06a4308_0 + - sqlite 3.51.0 h2a70700_0 + - tk 8.6.15 h54e0aa7_0 + - tqdm 4.67.1 py313h7040dfc_1 + - trove-classifiers 2025.5.9.12 py313h06a4308_0 + - tzdata 2025b h04d1e81_0 + - urllib3 2.6.1 py313h06a4308_0 + - wheel 0.45.1 py313h06a4308_0 + - xorg-libx11 1.8.12 h9b100fa_1 + - xorg-libxau 1.0.12 h9b100fa_0 + - xorg-libxdmcp 1.1.5 h9b100fa_0 + - xorg-xorgproto 2024.1 h5eee18b_1 + - xz 5.6.4 h5eee18b_1 + - zlib 1.3.1 hb25bd0a_0 + run: + - archspec >=0.2.3 + - boltons >=23.0.0 + - charset-normalizer + - conda-libmamba-solver >=25.4.0 + - conda-package-handling >=2.2.0 + - distro >=1.5.0 + - frozendict >=2.4.2 + - jsonpatch >=1.32 + - menuinst >=2 + - packaging >=23.0 + - platformdirs >=3.10.0 + - pluggy >=1.0.0 + - pycosat >=0.6.3 + - python >=3.13,<3.14.0a0 + - python_abi 3.13.* *_cp313 + - requests >=2.28.0,<3 + - ruamel.yaml >=0.11.14,<0.19 + - setuptools >=60.0.0 + - tqdm >=4 + - truststore >=0.8.0 + - zstandard >=0.19.0 + run_constrained: + - conda-build >=25.9 + - conda-content-trust >=0.1.1 + - conda-env >=2.6 +test: + downstreams: + - conda-smithy + imports: + - conda + - conda_env + requires: null +about: + description: 'Conda is an open source package management system and environment + + management system for installing multiple versions of software packages + + and their dependencies and switching easily between them. It works on + + Linux, OS X and Windows, and was created for Python programs but can + + package and distribute any software. + + ' + dev_url: https://github.com/conda/conda + doc_url: https://docs.conda.io/projects/conda/en/stable/ + home: https://docs.conda.io/ + license: BSD-3-Clause + license_family: BSD + license_file: conda-src/LICENSE + summary: OS-agnostic, system-level binary package and environment manager. +extra: + copy_test_source_files: true + final: true + skip-lints: + - missing_pip_check + - python_build_tool_in_run diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/meta.yaml.template b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/meta.yaml.template new file mode 100644 index 0000000000000000000000000000000000000000..a5635cb1b9e8f5982cbfa2a8cb8d20ae8e3accd4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/meta.yaml.template @@ -0,0 +1,120 @@ +{% set name = "conda" %} +{% set version = "25.11.1" %} +{% set build_number = "0" %} +{% set sha256 = "280bee40bfa3dc64a294a3501ae3150fe112e0f51cf94f7a346e5cfb4b370efb" %} +# Running the upstream test suite requires the inclusion of test files, which +# balloons the size of the package and occasionally triggers false-positive +# security warnings; values can be "yes" or "no". +{% set run_upstream_tests = "no" %} + +package: + name: {{ name }} + version: {{ version }} + +source: + url: https://github.com/conda/{{ name }}/releases/download/{{ version }}/{{ name }}-{{ version }}.tar.gz + sha256: {{ sha256 }} + folder: conda-src + +build: + skip: True # [py<310] + number: {{ build_number }} + script: {{ PYTHON }} -m pip install conda-src/ --no-deps --no-build-isolation -vv && {{ PYTHON }} -m conda init --install + # These are present when the new environment is created + # so we have to exempt them from the list of initial files + # for conda-build to realize they should be included. + always_include_files: + - bin/conda # [unix] + - bin/activate # [unix] + - bin/deactivate # [unix] + - Scripts/activate.bat # [win] + - Scripts/activate # [win] + - Scripts/deactivate # [win] + +requirements: + build: + - git # [not win] + - msys2-filesystem # [win] + - msys2-bash # [win] + - msys2-base # [win] + host: + - python + - pip + - hatchling >=1.12.2 + - hatch-vcs >=0.2.0 + # for `conda init` in build/script above + - boltons >=23.0.0 + - frozendict >=2.4.2 + - menuinst >=2 + - platformdirs >=3.10.0 + - requests >=2.28.0,<3 + - ruamel.yaml >=0.11.14,<0.19 + - tqdm >=4 + run: + - archspec >=0.2.3 + - boltons >=23.0.0 + - charset-normalizer + - conda-libmamba-solver >=25.4.0 + - conda-package-handling >=2.2.0 + - distro >=1.5.0 + - frozendict >=2.4.2 + - jsonpatch >=1.32 + - menuinst >=2 + - packaging >=23.0 + - platformdirs >=3.10.0 + - pluggy >=1.0.0 + - pycosat >=0.6.3 + - python + - requests >=2.28.0,<3 + - ruamel.yaml >=0.11.14,<0.19 + - setuptools >=60.0.0 + - tqdm >=4 + - truststore >=0.8.0 # [py>=310] + - zstandard >=0.19.0 + run_constrained: + - conda-build >=25.9 + - conda-content-trust >=0.1.1 + - conda-env >=2.6 + +test: +{% if run_upstream_tests == 'yes' %} + source_files: + - conda-src/tests + - conda-src/setup.cfg +{% endif %} + requires: +{% if run_upstream_tests == 'yes' %} + - mock + - pytest + - pexpect + - responses + # - conda-build # needed to run the test suite, but we're not doing that right now. +{% endif %} + - msys2-filesystem # [win] + - msys2-bash # [win] + - msys2-base # [win] + imports: + - conda + - conda_env + downstreams: + - conda-smithy # [py3k] + +about: + home: https://docs.conda.io/ + license: BSD-3-Clause + license_family: BSD + license_file: conda-src/LICENSE + summary: OS-agnostic, system-level binary package and environment manager. + description: | + Conda is an open source package management system and environment + management system for installing multiple versions of software packages + and their dependencies and switching easily between them. It works on + Linux, OS X and Windows, and was created for Python programs but can + package and distribute any software. + doc_url: https://docs.conda.io/projects/conda/en/stable/ + dev_url: https://github.com/conda/conda + +extra: + skip-lints: + - python_build_tool_in_run + - missing_pip_check diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/run_test.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/run_test.bat new file mode 100644 index 0000000000000000000000000000000000000000..207c16ce95b557d1443bdea822726082e95006ed --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/run_test.bat @@ -0,0 +1,27 @@ +:: clear conda stuff from parent process +SET CONDA_SHLVL= +SET _CE_CONDA= +SET _CE_M= +SET _CONDA_EXE= + +:: load shell interface +:: CALL is necessary because conda is a bat script, +:: running bat files within other bat files requires CALL or else +:: the outer script (our test script) exits when the inner completes +CALL %PREFIX%\condabin\conda_hook.bat + +:: display conda details +CALL conda info --all + +:: create, activate, and deactivate a conda environment +CALL conda create --yes --prefix ".\built-conda-test-env" "m2-patch" +IF NOT %ERRORLEVEL% == 0 EXIT /B 1 + +CALL conda activate ".\built-conda-test-env" +ECHO "CONDA_PREFIX=%CONDA_PREFIX%" + +IF NOT "%CONDA_PREFIX%" == "%CD%\built-conda-test-env" EXIT /B 1 +%CONDA_PREFIX%\Library\usr\bin\patch.exe --version +IF NOT %ERRORLEVEL% == 0 EXIT /B 1 + +CALL conda deactivate diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/run_test.sh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/run_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a12d4f3261bd0897b59dce952fcc5efbe4079180 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/recipe/run_test.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +# clear conda stuff from parent process +unset CONDA_SHLVL +unset _CE_CONDA +unset _CE_M +unset CONDA_EXE + +# load shell interface +eval "$(python -m conda shell.bash hook)" + +# display conda details +conda info --all + +# create, activate, and deactivate a conda environment +conda create --yes --prefix "./built-conda-test-env" "patch" || exit 1 + +conda activate "./built-conda-test-env" +echo "CONDA_PREFIX=${CONDA_PREFIX}" + +[[ "${CONDA_PREFIX}" == "${PWD}/built-conda-test-env" ]] || exit 1 +${CONDA_PREFIX}/bin/patch --version || exit 1 + +conda deactivate diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/test/run_test.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/test/run_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f4631f96e9a9c06363037a41ce080c3780516268 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/test/run_test.py @@ -0,0 +1,6 @@ +print("import: 'conda'") +import conda + +print("import: 'conda_env'") +import conda_env + diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/test/run_test.sh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/test/run_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a12d4f3261bd0897b59dce952fcc5efbe4079180 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/info/test/run_test.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +# clear conda stuff from parent process +unset CONDA_SHLVL +unset _CE_CONDA +unset _CE_M +unset CONDA_EXE + +# load shell interface +eval "$(python -m conda shell.bash hook)" + +# display conda details +conda info --all + +# create, activate, and deactivate a conda environment +conda create --yes --prefix "./built-conda-test-env" "patch" || exit 1 + +conda activate "./built-conda-test-env" +echo "CONDA_PREFIX=${CONDA_PREFIX}" + +[[ "${CONDA_PREFIX}" == "${PWD}/built-conda-test-env" ]] || exit 1 +${CONDA_PREFIX}/bin/patch --version || exit 1 + +conda deactivate diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda-25.11.1.dist-info/licenses/AUTHORS.md b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda-25.11.1.dist-info/licenses/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..9217778ee79c91ad76ab9867b37248bfabe9b464 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda-25.11.1.dist-info/licenses/AUTHORS.md @@ -0,0 +1,479 @@ +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 +* 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 +* 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 +* 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 +* Geir Ove Myhr +* George Hartzell +* 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 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 +* 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 +* 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda-25.11.1.dist-info/licenses/LICENSE b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda-25.11.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a2fbff055a4a2c501a54936ad1ec343ea049bce2 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda-25.11.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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3abf5c0da7241d6267b6dd2609fa7f28d4813be5 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__init__.py @@ -0,0 +1,192 @@ +# 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 + +#: The conda package directory. +CONDA_PACKAGE_ROOT = abspath(dirname(__file__)) +#: 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. +CONDA_SOURCE_ROOT = dirname(CONDA_PACKAGE_ROOT) + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c02c12bc2e60afa011f3b45a6bd1df17f657582 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae50afdf44620209f6f9b277107ca995665ffcd9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/_vendor.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/_vendor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..788af134ec99ae1af64b5772343427e5cb93843d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/_vendor.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/_version.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c29f699365796543f217a80898750d7d6aab5e0b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/_version.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/activate.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/activate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2617162743a8b07004cf4ffe8172c0b37eee644 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/activate.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/api.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/api.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f15479cddfff799c633103b5bc9c02e74f8a823 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/api.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/deprecations.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/deprecations.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b4cf4a72ac7ee11d4143cce6122e040dd604897 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/deprecations.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exception_handler.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exception_handler.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b43044fb9a7a4ea54a9e1d76c16bce000a0e0c5d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exception_handler.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35ab8430b07d343269cea0af3b1af51dda953437 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exports.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exports.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6092b298d6296ac73825e43bf0985f5fd5ff980f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/exports.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/history.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/history.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e83da7216d4a95417a6983d6d8e00039823f8dc3 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/history.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/instructions.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/instructions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1a927125854cf0f62827a193f12e3e1176e2dbd Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/instructions.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/misc.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/misc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72ce49df8d80ce87232e1cc4cef0bc7a56ce07ce Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/misc.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/plan.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/plan.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93ce7f122d5742e86ef0a6211e9aa9608e54552a Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/plan.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/reporters.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/reporters.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3450a756769970d75b0ab5009a2486d279d9f7b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/reporters.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/resolve.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/resolve.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f639fe0bb73949d7fb43c1bd9cf8b604b4c15458 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/resolve.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/utils.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcf7edd02a06c90564dd6f562836a745efd868a4 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/_vendor.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/_vendor.py new file mode 100644 index 0000000000000000000000000000000000000000..7d6e4b982021a48c7dcbcdfc380ee38b208b2fde --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/LICENSE b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a8c7830ae0403396b45fb4fcfd0e6ca72789eaa4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85dd85928ffe4a0a2a1a64bd696df6f3a67de4bb --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9888000c9a816e329ef638d4fb86390601692e65 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/collection.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/collection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..083be7ed932bf87342d1d517406caa2556a85f3d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/collection.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/compat.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/compat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60a248cc0338a5cbb7cc4d6f9edd52fd1c71d279 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/compat.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/decorators.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/decorators.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05ebfba1b984f84b1bb694ee803dd3a8270aaca9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/decorators.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/entity.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/entity.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb4b6e2e44c8b61d4464a4c368a3e70b18587382 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/entity.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4f790aadea436cbe4258ca9c39a37b7ca14895d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/ish.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/ish.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0eaa3b049b921939e514302ec12675646c76237 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/ish.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/logz.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/logz.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833d5bd84222d6422a2eb41fa2eb5f482e3ca8b1 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/logz.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/type_coercion.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/type_coercion.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5115cdc35d1f949c79f60604d54a3d79abaa76c Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/__pycache__/type_coercion.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/collection.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/collection.py new file mode 100644 index 0000000000000000000000000000000000000000..355166377ad697a03e9f85702aa5616df151feda --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/compat.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..66626d21cc51c461d59a6e2c66805197e26255b5 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/decorators.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..c45121fd81d6d7372065417dd0a5b0b48165692f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/entity.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/entity.py new file mode 100644 index 0000000000000000000000000000000000000000..404adc6f8d120e4f811e59332fa21f8ad534e548 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/exceptions.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..71822c8e3c9aac17b3bd81eccb2651b2988187bb --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/ish.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/ish.py new file mode 100644 index 0000000000000000000000000000000000000000..1c2ed900cb40e32618f42d48e5e34802fa08e3db --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/logz.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/logz.py new file mode 100644 index 0000000000000000000000000000000000000000..669d5da05f42480e3450822b5164258baad53a37 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/type_coercion.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/auxlib/type_coercion.py new file mode 100644 index 0000000000000000000000000000000000000000..5a9958890f5f28b753ea74dc28f1dae41bafe435 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff1b814060d62a0c1fb293b8f3dcd664f9320c5 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29d4ec0118212bf6ab3c10b1afaea42328958d34 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/constants.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/constants.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b8a8215368867f2e85f77a57de34a6b2f7a4c64 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/constants.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/context.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/context.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71da854a6e9fd7cbefa108c957e9c9760662a583 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/__pycache__/context.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/constants.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..ce9cf85f3b221acbbf75d030db777674099f3ea5 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/constants.py @@ -0,0 +1,401 @@ +# 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 + +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" +ERROR_UPLOAD_URL: Final = "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" +CONDA_PACKAGE_EXTENSIONS: Final = ( + CONDA_PACKAGE_EXTENSION_V2, + CONDA_PACKAGE_EXTENSION_V1, +) +CONDA_PACKAGE_PARTS: Final = tuple(f"{ext}.part" for ext in CONDA_PACKAGE_EXTENSIONS) +CONDA_TARBALL_EXTENSION: Final = ( + CONDA_PACKAGE_EXTENSION_V1 # legacy support for conda-build +) +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" + +#: Default name of the notices file on the server we look for +NOTICES_FN: Final = "notices.json" + +#: Name of cache file where read notice IDs are stored +NOTICES_CACHE_FN: Final = "notices.cache" + +#: Determines the subdir for notices cache +NOTICES_CACHE_SUBDIR: Final = "notices" + +#: Determines how often notices are displayed while running commands +NOTICES_DECORATOR_DISPLAY_INTERVAL: Final = 86400 # in seconds + +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" + + +#: The name of the default solver, currently "libmamba" +DEFAULT_SOLVER: Final = "libmamba" +CLASSIC_SOLVER: Final = "classic" + +#: The name of the default json reporter backend +DEFAULT_JSON_REPORTER_BACKEND: Final = "json" + +#: The name of the default console reporter backend +DEFAULT_CONSOLE_REPORTER_BACKEND: Final = "classic" + +#: The default `conda list` columns +DEFAULT_CONDA_LIST_FIELDS: Final = ("name", "version", "build", "channel_name") +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" + +# 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/context.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/context.py new file mode 100644 index 0000000000000000000000000000000000000000..d1adb4f100cc87397c7ae2cad5c2db48bc27dab1 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/base/context.py @@ -0,0 +1,2399 @@ +# 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, +) +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, + ERROR_UPLOAD_URL, + KNOWN_SUBDIRS, + NO_PLUGINS, + PREFIX_MAGIC_FILE, + PREFIX_NAME_DISALLOWED_CHARS, + REPODATA_FN, + RESERVED_ENV_NAMES, + ROOT_ENV_NAME, + SEARCH_PATH, + 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(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)) + ) + 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 + 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) + + reserved_multichannel_urls = { + DEFAULTS_CHANNEL_NAME: default_channels, + "local": self.conda_build_local_urls, + } + reserved_multichannels = { + name: tuple( + Channel.make_simple_channel(self.channel_alias, url) for url in urls + ) + for name, urls in reserved_multichannel_urls.items() + } + custom_multichannels = { + name: tuple( + Channel.make_simple_channel(self.channel_alias, url) for url in urls + ) + for name, urls in self._custom_multichannels.items() + } + return { + name: channels + for name, channels in ( + *custom_multichannels.items(), + *reserved_multichannels.items(), # order maters, reserved overrides custom + ) + } + + @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 + from ..common.path import is_package_file + + grouped_packages = groupby_to_dict( + lambda x: "explicit" if is_package_file(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", # should remain undocumented + "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 two reserved + multichannels are 'defaults' and 'local'. The 'defaults' multichannel is + customized using the 'default_channels' parameter. The 'local' + multichannel is a list of file:// channel locations where conda-build stashes + successfully-built packages. Other multichannels can be defined with + custom_multichannels, where the key is the multichannel name and the value is + a list of channel names and/or channel urls. + """ + ), + 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. + """ + ), + # 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() + + 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 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(dict.fromkeys(channels)) + + +@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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ffb1380eaac4e96adba38d5a2fe72eea24bfa3aa --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7669bfca880a03ccbb21edc3955a3f64c38c7b37 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/actions.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/actions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..942c82b3712c2098cb4babad3a0edbec0d84a65f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/actions.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/common.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51d06d68776b36fda0d0b4a89d51b5468c966e78 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/common.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/conda_argparse.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/conda_argparse.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75bf8aba77e417ffa11d8a59b84ef9f7acc20529 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/conda_argparse.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/find_commands.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/find_commands.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50e800e7f6f3439b4ed02f537ed58469cfed0962 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/find_commands.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/helpers.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ed0a7d1ac431f2b9873fe0796981a1baf56d82 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/helpers.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/install.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/install.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89f44aac23e0be48a4f70ac746daf8897c33bb04 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/install.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0613fa59024afc718177976029207adfcbe8928e Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_clean.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_clean.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fc6d5cd560cb58a844e1a4c182f69969f9cac9f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_clean.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_commands.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_commands.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d89ace33d506f4a17e570ad85c4b818fde9ff1a7 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_commands.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_compare.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_compare.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5fbcb4f7ef803333186fcc4697bd0ec11b897b5 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_compare.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_config.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e08b95cff9a046470dcacd2770ca32ca42f21bbc Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_config.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_create.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_create.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..898e4a0453f34bab4dc6595829981531222eeaf7 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_create.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a00c13ad4c911b5d5b052bb87b1ca4fd8aff83d4 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_config.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf3ce75768a7ad8a133a2e64c0830f5b56a144b3 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_config.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_create.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_create.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22aec98f5ed6dfb83ae97649513bc723a240a722 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_create.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_list.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_list.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44e6376d273823189e0c28b780ebaa9d0c8f2aa6 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_list.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_remove.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_remove.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f9da2b2f22f7496a69566d782941dced66f52f9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_remove.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_update.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_update.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b14a06f3b8a9fa364100e2cb2dec65414552cab2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_update.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_vars.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_vars.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a19aeb83a59f14a6929d9811ab9d3a54f6ef230 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_env_vars.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_export.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_export.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a1146ed7b149036f94e025610c5d40b58060249 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_export.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_info.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_info.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ce63c154fc228f01f4255a8abf7e69a1934e31d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_info.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_init.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_init.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45fdf1ddc21fd15b20d6051c32d384d36c62b368 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_init.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_install.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_install.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3c019f78aef9df997c84560b8e916decd17c7da Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_install.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_list.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_list.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9e19ffa37f9a004c5370b865bcc751643869c70 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_list.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_mock_activate.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_mock_activate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80260df14e6744437cbbd414c55964220be30d9c Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_mock_activate.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_mock_deactivate.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_mock_deactivate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7df9ed20c8bcc5e9069cc9a9c80afb57b6da1af3 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_mock_deactivate.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_notices.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_notices.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bac7b933413681b0a6605ae3018ac7ca0ffa3471 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_notices.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_package.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_package.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04db320d993ea4cdc0d95f63efa2bda9859f3c31 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_package.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_pip.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_pip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a7964b2d9c327f2a85d72d686a8b48c01a27aca Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_pip.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_remove.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_remove.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..399ffc60ec167751c424d2001088c56dec733078 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_remove.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_rename.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_rename.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7acb7f155365b3f4db497b74f0fcd8991aee461 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_rename.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_run.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_run.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09dd8afe610b6e694f6982b998e4ffc657af2c35 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_run.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_search.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_search.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1d670f9072c26b225b832af023e1669aa1cf54b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_search.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_update.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_update.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acacceb5af94f74fb6561ad0c5e8a6d019a373a8 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/__pycache__/main_update.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/actions.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/actions.py new file mode 100644 index 0000000000000000000000000000000000000000..ad46ceb9704adeaf16ac45f675da9111a8bf30cd --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/actions.py @@ -0,0 +1,58 @@ +# 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 + + +class NullCountAction(_CountAction): + @staticmethod + 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): + new_count = self._ensure_value(namespace, self.dest, 0) + 1 + setattr(namespace, self.dest, new_count) + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/common.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/common.py new file mode 100644 index 0000000000000000000000000000000000000000..5e94ac3abba2cb2358951cf63fbc6cc882b82eb4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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): # pragma: no cover + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/conda_argparse.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/conda_argparse.py new file mode 100644 index 0000000000000000000000000000000000000000..e88bedfee99a3f6bf78a67eac9c26a0155eab4eb --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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("%", "%%") + +#: List of built-in commands; these cannot be overridden by plugin subcommands +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 +} + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/find_commands.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/find_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..d99923bccaeb26bd0a0aa527017b8c470a8586f3 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/helpers.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..4c4512147518577496e3b129b3bfdacd3d0b0e25 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/helpers.py @@ -0,0 +1,634 @@ +# 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( + "--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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/install.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/install.py new file mode 100644 index 0000000000000000000000000000000000000000..b4da9458e150284ba6f6907ccd4d064934317bb6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/install.py @@ -0,0 +1,568 @@ +# 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") + + +@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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main.py new file mode 100644 index 0000000000000000000000000000000000000000..63d321b24893c49fa8bcf83502635149740093ed --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main.py @@ -0,0 +1,113 @@ +# 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) + pre_args, _ = pre_parser.parse_known_args(args) + + # 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_clean.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_clean.py new file mode 100644 index 0000000000000000000000000000000000000000..bd92db707a772bcf8adab6b71f17294ada6e4b45 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_clean.py @@ -0,0 +1,419 @@ +# 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 CONDA_PACKAGE_EXTENSIONS, CONDA_PACKAGE_PARTS + + warnings: list[str] = [] + pkg_sizes: dict[str, dict[str, int]] = {} + for pkgs_dir in find_pkgs_dirs(): + # tarballs are files in pkgs_dir + _, _, tars = next(os.walk(pkgs_dir)) + for tar in tars: + # tarballs also end in .tar.bz2, .conda, .tar.bz2.part, or .conda.part + if not tar.endswith((*CONDA_PACKAGE_EXTENSIONS, *CONDA_PACKAGE_PARTS)): + continue + + # get size + try: + size = _get_size(pkgs_dir, tar, warnings=warnings) + except NotImplementedError: + pass + else: + pkg_sizes.setdefault(pkgs_dir, {})[tar] = 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_commands.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..67dd8408c9c8b466d85c14b9ef841c8fa594081e --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_compare.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..00910565c9d99affab8356abf8bca9c63aeb1ccb --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_config.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_config.py new file mode 100644 index 0000000000000000000000000000000000000000..becf048bd37a74ecbdd78980986a022114dba7b6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_config.py @@ -0,0 +1,958 @@ +# 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, Sequence +from itertools import chain +from logging import getLogger +from os.path import isfile, join +from pathlib import Path +from textwrap import wrap +from typing import TYPE_CHECKING + +from ..common.configuration import DEFAULT_CONDARC_FILENAME + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace, _SubParsersAction + from typing import Any + + from ..base.context import Context + +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 + from ..exceptions import CouldntParseError + + 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_round_trip_dump + + # 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_round_trip_dump( + {"plugins": {name: json.loads(default_value_str)}} + ) + else: + yaml_content = yaml_round_trip_dump({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 _key_exists(key: str, warnings: list[str], context=None) -> bool: + """ + Logic to determine if the key is a valid setting. + """ + if context is None: + from ..base.context import context + + first, *rest = key.split(".") + if ( + first == "plugins" + and len(rest) > 0 + and rest[0] in context.plugins.list_parameters() + ): + return True + + if first not in context.list_parameters(): + if context.name_for_alias(first): + return True + if context.json: + warnings.append(f"Unknown key: {key!r}") + else: + print(f"Unknown key: {key!r}", file=sys.stderr) + return False + + return True + + +def _get_key( + key: str, + config: dict, + *, + json: dict[str, Any] | None = None, + warnings: list[str] | None = None, +) -> None: + from ..base.context import context + + json = {} if json is None else json + warnings = [] if warnings is None else warnings + key_parts = key.split(".") + + if not _key_exists(key, warnings, context): + return + + if alias := context.name_for_alias(key): + key = alias + key_parts = alias.split(".") + + sub_config = config + try: + for part in key_parts: + sub_config = sub_config[part] + except KeyError: + # KeyError: part not found, nothing to get + pass + else: + if context.json: + json[key] = sub_config + else: + print_config_item(key, sub_config) + + +def _set_key(key: str, item: Any, config: dict) -> None: + from ..base.context import context + + if not _key_exists(key, [], context): + from ..exceptions import CondaKeyError + + raise CondaKeyError(key, "unknown parameter") + + if aliased := 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": + base_context = context.plugins + base_config = config.setdefault("plugins", {}) + parameter_name, *rest = rest + else: + base_context = context + base_config = config + 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: + from ..exceptions import CondaKeyError + + raise CondaKeyError(key, "invalid parameter") + + +def _remove_item(key: str, item: Any, config: dict) -> None: + from ..base.context import context + + first, *rest = key.split(".") + + if first == "plugins": + base_context = context.plugins + base_config = config.setdefault("plugins", {}) + parameter_name = rest[0] + rest = [] + else: + base_context = context + base_config = config + parameter_name = first + + try: + parameter_type = base_context.describe_parameter(parameter_name)[ + "parameter_type" + ] + except KeyError: + # KeyError: key_parts[0] is an unknown parameter + from ..exceptions import CondaKeyError + + raise CondaKeyError(key, "unknown parameter") + + if parameter_type == "sequence" and len(rest) == 0: + if parameter_name not in base_config: + if parameter_name != "channels": + from ..exceptions import CondaKeyError + + raise CondaKeyError(key, "undefined in config") + config[parameter_name] = ["defaults"] + + if item not in base_config[parameter_name]: + from ..exceptions import CondaKeyError + + 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: + from ..exceptions import CondaKeyError + + raise CondaKeyError(key, "invalid parameter") + + +def _remove_key(key: str, config: dict) -> None: + key_parts = key.split(".") + + sub_config = config + 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? + from ..base.context import context + from ..exceptions import CondaKeyError + + if alias := context.name_for_alias(key): + try: + return _remove_key(alias, config) + except CondaKeyError: + pass # raise with originally passed key + raise CondaKeyError(key, "undefined in config") + + +def _read_rc(path: str | os.PathLike | Path) -> dict: + from ..common.serialize import yaml_round_trip_load + + try: + return yaml_round_trip_load(Path(path).read_text()) or {} + except FileNotFoundError: + # FileNotFoundError: path does not exist + return {} + + +def _write_rc(path: str | os.PathLike | Path, config: dict) -> None: + from ruamel.yaml.representer import RoundTripRepresenter + + from .. import CondaError + from ..base.constants import ( + ChannelPriority, + DepsModifier, + PathConflict, + SafetyChecks, + SatSolverChoice, + UpdateModifier, + ) + from ..common.serialize import yaml_round_trip_dump + + # Add representers for enums. + # Because a representer cannot be added for the base Enum class (it must be added for + # each specific Enum subclass - and because of import rules), I don't know of a better + # location to do this. + def enum_representer(dumper, data): + return dumper.represent_str(str(data)) + + RoundTripRepresenter.add_representer(SafetyChecks, enum_representer) + RoundTripRepresenter.add_representer(PathConflict, enum_representer) + RoundTripRepresenter.add_representer(DepsModifier, enum_representer) + RoundTripRepresenter.add_representer(UpdateModifier, enum_representer) + RoundTripRepresenter.add_representer(ChannelPriority, enum_representer) + RoundTripRepresenter.add_representer(SatSolverChoice, enum_representer) + + try: + Path(path).write_text(yaml_round_trip_dump(config)) + except OSError as e: + raise CondaError(f"Cannot write to condarc file at {path}\nCaused by {e!r}") + + +def _validate_provided_parameters( + parameters: Sequence[str], plugin_parameters: Sequence[str], context: Context +) -> None: + """ + Compares the provided parameters with the available parameters. + + :raises: + ArgumentError: If the provided parameters are not valid. + """ + from ..common.io import dashlist + from ..exceptions import ArgumentError + + all_names = context.list_parameters(aliases=True) + all_plugin_names = context.plugins.list_parameters() + + 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)}" + ) + + +def set_keys(*args: tuple[str, Any], path: str | os.PathLike | Path) -> None: + config = _read_rc(path) + for key, value in args: + _set_key(key, value, config) + _write_rc(path, config) + + +def execute_config(args, parser): + from .. import CondaError + from ..base.context import ( + context, + sys_rc_path, + user_rc_path, + ) + from ..common.io import timeout + from ..common.iterators import groupby_to_dict as groupby + from ..common.serialize import json, yaml_round_trip_load + 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 + json_warnings = [] + json_get = {} + + 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 + + # read existing condarc + if os.path.exists(rc_path): + with open(rc_path) as fh: + # round trip load required because... we need to round trip + rc_config = yaml_round_trip_load(fh) or {} + elif os.path.exists(sys_rc_path): + # In case the considered rc file doesn't exist, fall back to the system rc + with open(sys_rc_path) as fh: + rc_config = yaml_round_trip_load(fh) or {} + else: + rc_config = {} + + grouped_parameter = groupby( + lambda p: context.describe_parameter(p)["parameter_type"], + context.list_parameters(), + ) + + plugin_grouped_parameters = groupby( + lambda p: context.plugins.describe_parameter(p)["parameter_type"], + context.plugins.list_parameters(), + ) + sequence_parameters = grouped_parameter["sequence"] + plugin_sequence_parameters = plugin_grouped_parameters.get("sequence", []) + map_parameters = grouped_parameter["map"] + plugin_map_parameters = plugin_grouped_parameters.get("map", []) + + # Get + if args.get is not None: + context.validate_all() + + for key in args.get or sorted(rc_config.keys()): + _get_key(key, rc_config, json=json_get, warnings=json_warnings) + + 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_round_trip_load(content) + rc_config.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: + key, subkey = key.split(".", 1) if "." in key else (key, None) + + if key in sequence_parameters: + arglist = rc_config.setdefault(key, []) + elif key == "plugins" and subkey in plugin_sequence_parameters: + arglist = rc_config.setdefault("plugins", {}).setdefault(subkey, []) + elif key in map_parameters: + arglist = rc_config.setdefault(key, {}).setdefault(subkey, []) + elif key in plugin_map_parameters: + arglist = rc_config.setdefault("plugins", {}).setdefault(subkey, {}) + else: + from ..exceptions import CondaValueError + + raise CondaValueError(f"Key '{key}' is not a known sequence parameter.") + + if not (isinstance(arglist, Sequence) and not isinstance(arglist, str)): + from ..exceptions import CouldntParseError + + bad = rc_config[key].__class__.__name__ + raise CouldntParseError(f"key {key!r} should be a list, not {bad}.") + + if item in arglist: + message_key = key + "." + subkey if subkey is not None else key + # Right now, all list keys should not contain duplicates + location = "top" if prepend else "bottom" + message = f"Warning: '{item}' already in '{message_key}' list, moving to the {location}" + if subkey is None: + arglist = rc_config[key] = [p for p in arglist if p != item] + else: + arglist = rc_config[key][subkey] = [p for p in arglist if p != item] + if not context.json: + stderr_write(message) + else: + json_warnings.append(message) + arglist.insert(0 if prepend else len(arglist), item) + + # Set + for key, item in args.set: + _set_key(key, item, rc_config) + + # Remove + for key, item in args.remove: + _remove_item(key, item, rc_config) + + # Remove Key + for key in args.remove_key: + _remove_key(key, rc_config) + + # config.rc_keys + if not args.get: + _write_rc(rc_path, rc_config) + + if context.json: + from .common import stdout_json_success + + stdout_json_success(rc_path=rc_path, warnings=json_warnings, get=json_get) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_create.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_create.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b8d4b8cbc5e757a1d4e4c4dcff16fcc7d1e053 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_create.py @@ -0,0 +1,175 @@ +# 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. + """ + ) + 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: + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8003c697553e7798bee4bf57b0c773987c92b1 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_config.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_config.py new file mode 100644 index 0000000000000000000000000000000000000000..02a5ddf4cf1c014c20a33343e6ab4249b09b8e74 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_create.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_create.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa9af7bebce16333e87818c8e3e8d6db31ffa71 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_list.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_list.py new file mode 100644 index 0000000000000000000000000000000000000000..c9646354fa37191882a87a790257668e75a966a8 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_list.py @@ -0,0 +1,46 @@ +# 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 + + """ + ) + p = sub_parsers.add_parser( + "list", + help=summary, + description=description, + epilog=epilog, + **kwargs, + ) + + add_parser_json(p) + + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_remove.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_remove.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f70e8f4272e280c2a58b67c6d15b3568f9b345 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_update.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_update.py new file mode 100644 index 0000000000000000000000000000000000000000..d554b6812fee7bfc58dcf9fcb579516b7c56e5dc --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_update.py @@ -0,0 +1,183 @@ +# 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 = {} + + if env.requested_packages: + installers["conda"] = get_installer("conda") + + 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. + """ + ) + ) + + return -1 + + result = {"conda": None, "pip": None} + # install conda packages + installer_type = "conda" + installer = installers[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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_vars.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_env_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..844a4c404711e0b58a0bbd59542316e9f5c89bf6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_export.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_export.py new file mode 100644 index 0000000000000000000000000000000000000000..65cf5d31058eb9c522da5b6b65060ac205a0adc1 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_export.py @@ -0,0 +1,219 @@ +# 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 ..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( + "--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 + + # TODO: Check if platform targets are valid + + # 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_info.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_info.py new file mode 100644 index 0000000000000000000000000000000000000000..13ba33b1e52e3b3d882238353147c355f6e7e8e8 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_info.py @@ -0,0 +1,608 @@ +# 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 textwrap import wrap +from typing import TYPE_CHECKING, Literal + +from ..deprecations import deprecated + +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( + "--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, + ) + 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 ("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()), "") + ) + + +#: Possible components for the info command to render +InfoComponents = Literal["base", "channels", "envs", "system", "detail", "json_all"] + + +class InfoRenderer: + """ + Provides a ``render`` method for rendering ``InfoComponents`` + """ + + def __init__(self, context): + self._context = context + 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]]: + 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, + } + 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: + render(data, style=style) + + 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 + + components = iter_info_components(args, context) + renderer = InfoRenderer(context) + renderer.render(components) + + return 0 diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_init.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_init.py new file mode 100644 index 0000000000000000000000000000000000000000..f85ed0aa8bca0432131644a0e199e9739e767d7e --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_install.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_install.py new file mode 100644 index 0000000000000000000000000000000000000000..d66dcf30ea12760546b82197de4d4b21dbe6fa10 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_list.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_list.py new file mode 100644 index 0000000000000000000000000000000000000000..0deeaddcc74f516d5ce5d8035800f5ab9a73a690 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_list.py @@ -0,0 +1,393 @@ +# 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 + + 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: {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( + "--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, +) -> 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 + from .common import disp_features + + exitcode = 0 + + prefix_data = PrefixData(prefix, interoperability=True) + if reload_records: + prefix_data.load() + installed = sorted(prefix_data.iter_records(), key=lambda x: x.name) + show_channel_urls = show_channel_urls or context.show_channel_urls + fields = fields or context.list_fields + 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 fields == DEFAULT_CONDA_LIST_FIELDS and len(fields) == 4: + widths = [23, 15, 15, 1] + else: + widths = [len(title) for title in titles] + for prec in get_packages(installed, regex) if regex else installed: + if format == "canonical": + packages.append( + prec.dist_fields_dump() if context.json else 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 = "" + 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: + 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}:", + "#", + 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, +) -> 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, + ) + 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 regex and args.full_name: + regex = rf"^{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, + ) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_mock_activate.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_mock_activate.py new file mode 100644 index 0000000000000000000000000000000000000000..86404e5582fc5ae72ce1a950b9f118e98895e33f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_mock_deactivate.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_mock_deactivate.py new file mode 100644 index 0000000000000000000000000000000000000000..4b89bfde8825867ea2f88dae3be65e317f8469a4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_notices.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_notices.py new file mode 100644 index 0000000000000000000000000000000000000000..ab964930cdcfa14614b5fa99f402a24a65b4b8fd --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_package.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_package.py new file mode 100644 index 0000000000000000000000000000000000000000..2309fca0674dc5de7130f13d85500abedc1826d3 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_pip.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_pip.py new file mode 100644 index 0000000000000000000000000000000000000000..7de9f1f9f1861076ecceb93fa2a7e033393f5cf5 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_remove.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_remove.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc67e305fe2e82ec9a83cb9ea68fda444208f57 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_rename.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_rename.py new file mode 100644 index 0000000000000000000000000000000000000000..e38e38520dd80ad1233e66dfc0ddf75ba57c9f96 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_run.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_run.py new file mode 100644 index 0000000000000000000000000000000000000000..dc74646620234e206519c26b1e798f96a11a6bd7 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_run.py @@ -0,0 +1,138 @@ +# 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 + """ + ) + + 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( + "--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.", + ) + + 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 ..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() + # 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, + use_system_tmp_path=True, + ) + + # 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) + if response.stderr: + print(response.stderr, file=sys.stderr) + + # 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_search.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_search.py new file mode 100644 index 0000000000000000000000000000000000000000..df990a32a838d83467e4726c0e8b32ba5d469733 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_update.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/cli/main_update.py new file mode 100644 index 0000000000000000000000000000000000000000..d5dda1f4456bb6cc32181899dc8dae88bd483840 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c55dee5851a0463b8f2cf767899fc9396c4b09b3 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3e5129e59c7b44a0f43bedffd13016336dc0d9f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/_logic.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/_logic.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6cb2b7c05c24b9ae91f44a62bd694e32a3e6326 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/_logic.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/compat.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/compat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34964879b8e2c86844f2d46cfb090b878fbeb3b2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/compat.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/configuration.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/configuration.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ca7500477f62d81ee0baf9e87d09131b1e8f567 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/configuration.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/constants.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/constants.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cd69843b9daff0ab99c97801351fb29609a52b3 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/constants.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/io.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/io.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85b9603cacb0e4db22718ce4eb42dfcb146692fe Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/io.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/iterators.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/iterators.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4fc5351d38918d478ea8e61fc22e1de4817529b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/iterators.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/logic.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/logic.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cc2f60492c36c439e867c7be67612604d1af46f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/logic.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/signals.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/signals.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a46c9c408abe89a1e536b6d5f6fd6a8aab3facb Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/signals.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/toposort.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/toposort.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7a2fa9f9bdd33d5fd701e026db787c433e55ca8 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/toposort.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/url.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/url.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a15dd6eca7603738db117b77873a6fb770cb2e9a Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/__pycache__/url.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_logic.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_logic.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3e0e92b3fa7e8cc0c1076d31b18ede40e51d35 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0c63f283f3859bd4d368a431a62fc2fc45827046 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..135ff3c3df4b748eb3693b07ba526e96b5ff9e66 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/linux.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/linux.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..400769a1211f268323891e0251b12c38c8336399 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/linux.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/osx.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/osx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63d263af46fd502058d9f11640d74abac6749110 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/osx.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/unix.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/unix.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..689b3129ca2e4116208ccc16e3db516c563377ce Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/unix.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/windows.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/windows.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0120820cb4f74a09e166efbaf8a4cf378389c7ab Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/__pycache__/windows.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/linux.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/linux.py new file mode 100644 index 0000000000000000000000000000000000000000..969c90f8b1d029be96944d07d6f6173c2f6f3569 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/osx.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/osx.py new file mode 100644 index 0000000000000000000000000000000000000000..971be9b54f833b0d392de43e1f6e2231868bcc1f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/unix.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/unix.py new file mode 100644 index 0000000000000000000000000000000000000000..33b6a7830dd91556b9bf9d719795fb994532a2ae --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/windows.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/_os/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..38d9f3a747b35edbd7dbd188db507c92413c059d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/compat.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..1f7d85bff1f24e38db35f4f4982310c9003e5d8f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/configuration.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..fe882da5f2e201388c927958bf230ccfa15f0cb0 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/configuration.py @@ -0,0 +1,1771 @@ +# 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 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_round_trip_load + +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 + def make_raw_parameters_from_file(cls, filepath): + with open(filepath) as fh: + try: + yaml_obj = yaml_round_trip_load(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 + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/constants.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..07b72de81e5653703d9818e5689f67d272f77460 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/io.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/io.py new file mode 100644 index 0000000000000000000000000000000000000000..2e7e56da0922941e91ac400525f797676bce2de8 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/iterators.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/iterators.py new file mode 100644 index 0000000000000000000000000000000000000000..a7405113f5cf9bdaf683b1efa21aedd07b9f48c4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/logic.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/logic.py new file mode 100644 index 0000000000000000000000000000000000000000..7f30c1ca53a567e80152d0f47ddf874fc5d3c77d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fbce91ff805f94f60de88b552d7619e1bebaeca6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__init__.py @@ -0,0 +1,208 @@ +# 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 ..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 +) + +# any other extension will be mangled by CondaSession.get() as it tries to find +# channel names from URLs, through strip_pkg_extension() +KNOWN_EXTENSIONS = (".conda", ".tar.bz2", ".json", ".jlap", ".json.zst") + + +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): + """ + 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/_license-1.1-py27_1") + ('/path/_license-1.1-py27_1', None) + """ + # NOTE: not using CONDA_TARBALL_EXTENSION_V1 or CONDA_TARBALL_EXTENSION_V2 to comply with + # import rules and to avoid a global lookup. + for extension in KNOWN_EXTENSIONS: + if path.endswith(extension): + return path[: -len(extension)], extension + return path, None + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e974510266c8d309d5f21858638f62e38135e2ee Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/_cygpath.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/_cygpath.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e76f2f6c808c657bff3910d3af8d6f9126907e12 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/_cygpath.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/directories.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/directories.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08b4962930959a064e5c6d706afe221269b693b3 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/directories.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/python.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/python.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98b621d6ffce30f9bae5d0de1b01983c62c00b2b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/python.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/windows.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/windows.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b4a795d9f71870a0b5903621b305201a3ebc25f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/__pycache__/windows.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/_cygpath.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/_cygpath.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5d371e9612eb37af54e4c5b48dd95d963ad6d4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/directories.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/directories.py new file mode 100644 index 0000000000000000000000000000000000000000..146fa8019fa1ae23cb5f88e29c9e575dcb2321cd --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/python.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/python.py new file mode 100644 index 0000000000000000000000000000000000000000..3d8e1e21b4744006498d247c6b1b231a8275145a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/windows.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/path/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..51942299a8448cc480c6311b01e04faae6439345 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e265393bdbaeb36d2f73fb8556612ad8267de270 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9a4a324cc4073ed5ddf990b0feda762d94fcd3b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__pycache__/python.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__pycache__/python.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5cd7fb3ccd2f60b7f4a6f5fd231918b02b1b7d5 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/__pycache__/python.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/python.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/pkg_formats/python.py new file mode 100644 index 0000000000000000000000000000000000000000..19e616c85c6254f703eb84dd51de5fdee29e2073 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fec3b1ffce0f6db2191a4f77201f941e007d9dc0 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__init__.py @@ -0,0 +1,91 @@ +# 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__) + + +@functools.cache +def _yaml_round_trip(): + from ruamel.yaml import YAML + + parser = YAML(typ="rt") + parser.indent(mapping=2, offset=2, sequence=4) + return parser + + +@functools.cache +def _yaml_safe(): + from ruamel.yaml import YAML + + parser = 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 + + +def yaml_round_trip_load(string): + return _yaml_round_trip().load(string) + + +def yaml_safe_load(string): + """ + Examples: + >>> yaml_safe_load("key: value") + {'key': 'value'} + + """ + return _yaml_safe().load(string) + + +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() + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbbc7d724b3d40c37092e94262766553cfc3e718 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__pycache__/json.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__pycache__/json.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa27b543beb96eb8ac599d178b3245e0d82a1930 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/__pycache__/json.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/json.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/json.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd44bc21725ac0dfdc87223e259b4e46caf85c5 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/serialize/json.py @@ -0,0 +1,49 @@ +# 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 + +# detect the best json library to use +from requests.compat import json + +if TYPE_CHECKING: + from typing import Any + + +class CondaJSONEncoder(json.JSONEncoder): + def default(self, obj: Any) -> Any: + # 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) + + +def dump(*args, **kwargs): + kwargs.setdefault("cls", CondaJSONEncoder) + kwargs.setdefault("indent", 2) + return json.dump(*args, **kwargs) + + +def dumps(*args, **kwargs): + kwargs.setdefault("cls", CondaJSONEncoder) + kwargs.setdefault("indent", 2) + return json.dumps(*args, **kwargs) + + +load = json.load +loads = json.loads +JSONDecodeError = json.JSONDecodeError diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/signals.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/signals.py new file mode 100644 index 0000000000000000000000000000000000000000..696a827853611de7519f86de1382fee909eebc9b --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/toposort.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/toposort.py new file mode 100644 index 0000000000000000000000000000000000000000..20c9994ee0c010140a46127795f1c76be0a1e2c3 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/url.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/common/url.py new file mode 100644 index 0000000000000000000000000000000000000000..7648b996da456c55929bd43feeff0ebf7393c9a3 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed2e43f79ce73ceb0e7e350e4b02496ee3fd4d4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f674271026dcdedd0e92e2670d6764fa6cc809e Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/envs_manager.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/envs_manager.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13db5703230ebe96307e3d361feb64f8fb10299d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/envs_manager.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/index.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/index.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ad18e6ff6369ea59a0a194e61479631f7b1830c Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/index.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/initialize.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/initialize.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52edff4f199e9f241fc2bdc9ade736451c12d30f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/initialize.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/link.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/link.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..576ae5f70e2f803b0594cb7bf418b6230f2b14bd Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/link.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/package_cache_data.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/package_cache_data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..119d4c055b2027078b43643546de5958123585c5 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/package_cache_data.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/path_actions.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/path_actions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb68babe64838b4f2713105d7fd58cd80c39d62b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/path_actions.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/portability.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/portability.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cce1e27f64a10c93ebb87225285ac7c87922f5f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/portability.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/prefix_data.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/prefix_data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72f6ff85e3f304a0c373e74e87ada0730614baf5 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/prefix_data.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/solve.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/solve.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d86f5a8741a83f2ae7f74976caa7c52cb03cb2e Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/solve.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/subdir_data.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/subdir_data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6a052d928fb739d5cfdca089a2d5a07a813d2b6 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/__pycache__/subdir_data.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/envs_manager.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/envs_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c1162e5452894ed7f09f4cc7d2ece2c04ecec4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/index.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/index.py new file mode 100644 index 0000000000000000000000000000000000000000..50dcefe8188a5f8251e78cf8ca06083fa0bab7c2 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/initialize.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/initialize.py new file mode 100644 index 0000000000000000000000000000000000000000..4cfc7c9efd2df5804a460a1afecba6dde6b8ddcc --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/link.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/link.py new file mode 100644 index 0000000000000000000000000000000000000000..e372344274ba5c08ecd2ab75f25a0fbc44f4afb6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/link.py @@ -0,0 +1,1708 @@ +# 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: + composite_ag.extend(record_actions) + # consolidate compile actions into one big'un for better efficiency + 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, + ) + ) + # 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/package_cache_data.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/package_cache_data.py new file mode 100644 index 0000000000000000000000000000000000000000..13421bca7e14531f2ce9e0482c6e6532e956c69a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/package_cache_data.py @@ -0,0 +1,1024 @@ +# 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 codecs +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, + CONDA_PACKAGE_EXTENSIONS, + 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, + extract_tarball, + 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 + + _CONDA_TARBALL_EXTENSIONS = CONDA_PACKAGE_EXTENSIONS + 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 full_path.endswith(_CONDA_TARBALL_EXTENSIONS) + ): + 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: + extract_tarball( + 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 codecs.open(self.urls_txt_path, mode="ab", 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 package_path.endswith(CONDA_PACKAGE_EXTENSIONS): + 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.") + + cache_action = CacheUrlAction( + url=url, + target_pkgs_dir=first_writable_cache.pkgs_dir, + target_package_basename=pref_or_spec.fn, + 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(pref_or_spec.fn)[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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/path_actions.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/path_actions.py new file mode 100644 index 0000000000000000000000000000000000000000..43c836c043f61c3eb2923a7fcd9fb32ebcd7990b --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/path_actions.py @@ -0,0 +1,1510 @@ +# 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, + extract_tarball, + 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, PathType +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 == PathType.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=PathType.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 PathType.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 PathType.softlink, + ) + elif ( + self.link_type == LinkType.copy + and source_path_data.path_type == PathType.softlink + ): + self.prefix_path_data = PathDataV1.from_objects( + self.source_path_data, + path_type=source_path_type or PathType.softlink, + ) + + elif source_path_data.path_type == PathType.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 PathType.hardlink, + ) + elif source_path_data.path_type == PathType.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=PathType.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=PathType.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 + + 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): + 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, + ) + + +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 = PathType.windows_python_entry_point_script + else: + path_type = PathType.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 + ) + 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_tarball( + self.source_full_path, + self.target_full_path, + progress_update_callback=progress_update_callback, + ) + + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/portability.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/portability.py new file mode 100644 index 0000000000000000000000000000000000000000..543dff9c172abb7be3d74a11cc4ee10b805cdec7 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/prefix_data.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/prefix_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2f080f6c847a057e2b22d7b19b90d06ef33ade16 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/prefix_data.py @@ -0,0 +1,843 @@ +# 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 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, + CONDA_PACKAGE_EXTENSIONS, + 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 +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, 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 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 valida 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) + + # endregion + # region Records + + @time_recorder(module_name=__name__) + def load(self) -> None: + self.__prefix_records = {} + _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) -> PrefixData: + 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 + known_ext = False + # .dist-info is for things installed by pip + for ext in CONDA_PACKAGE_EXTENSIONS + (".dist-info",): + if fn.endswith(ext): + fn = fn[: -len(ext)] + known_ext = True + if not known_ext: + raise ValueError( + f"Attempted to make prefix record for unknown package type: {fn}" + ) + return fn + ".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): + 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: + log.debug("loading prefix record %s", prefix_record_json_path) + with open(prefix_record_json_path) as fh: + try: + json_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 + ) + + # TODO: consider, at least in memory, storing prefix_record_json_path as part + # of PrefixRecord + prefix_record = PrefixRecord(**json_data) + + # check that prefix record json filename conforms to name-version-build + # apparently implemented as part of #2638 to resolve #2599 + try: + n, v, b = basename(prefix_record_json_path)[:-5].rsplit("-", 2) + if (n, v, b) != ( + prefix_record.name, + prefix_record.version, + prefix_record.build, + ): + raise ValueError() + except ValueError: + log.warning( + "Ignoring malformed prefix record at: %s", prefix_record_json_path + ) + # TODO: consider just deleting here this record file in the future + return + + self.__prefix_records[prefix_record.name] = prefix_record + + # 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/solve.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..33a9d39c36847b956c6480f57ab77525ca77f6d0 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/solve.py @@ -0,0 +1,1454 @@ +# 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 ( + 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], + 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.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 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/subdir_data.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/core/subdir_data.py new file mode 100644 index 0000000000000000000000000000000000000000..3e95a97dc8911fdfe1c593db122645f6f3437c77 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1e7c5b3ec88373fac58a6a69b351417efe5a573 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/env.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/env.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5abb71452571a95b0a971108f1764972eebeec1f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/env.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/pip_util.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/pip_util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15c98fccfebf8cfb17d00a7000120b1db1cc39b4 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/__pycache__/pip_util.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/env.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/env.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e8d60dc446a15b41f714041e7e4af76d82a369 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/env.py @@ -0,0 +1,485 @@ +# 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_safe_dump, yaml_safe_load +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_safe_load(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() + out = yaml_safe_dump(d, stream) + if stream is None: + return out + + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2548439d141453b1d294a637c2b103d848b646e4 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/base.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f859e7bc60e841c99684cc9b1392e505e96ead7 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/conda.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/conda.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..066a5ffab72bc2267951da7ecb56447f0ba695d9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/conda.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/pip.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/pip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d42f08da8e8fee50057e03fd6bce862af81e32d2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/__pycache__/pip.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/base.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..461e74ffb67bfd7b7d7d6d0e58811bcb01497718 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/conda.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/conda.py new file mode 100644 index 0000000000000000000000000000000000000000..e6fca47d2e750263a43f5b9ec5742baa952a61e6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/pip.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/installers/pip.py new file mode 100644 index 0000000000000000000000000000000000000000..85ff3c35d81fb91cbb52ad3f5c72e1ae4d392ae8 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/pip_util.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/pip_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef5ed2ac03215747daee3c3765c5c658a533753 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef805e178e5cb72b78ed96f02e0321d5d5bd7a0 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76794f1032570d44d50ae3c13fd9bca3d9113d0f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/binstar.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/binstar.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81b3b3f29da37c23474fc19ae2ebe983b76654af Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/binstar.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/cep_24.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/cep_24.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..373980087ba252c7ff0e165a5ccaf57e4cb43bff Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/cep_24.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/explicit.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/explicit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a7c040df4842b179a95201a6e980aa82c3d6314 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/explicit.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/requirements.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/requirements.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51ecfc9a2724d20ec52f9993042c30344e723a57 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/requirements.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/yaml_file.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/yaml_file.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52dba6b8bb0b6d926be7d47ff0aadc1034569a12 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/__pycache__/yaml_file.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/binstar.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/binstar.py new file mode 100644 index 0000000000000000000000000000000000000000..398e00f7df93b20a891f173b0c6b241f12d85399 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/cep_24.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/cep_24.py new file mode 100644 index 0000000000000000000000000000000000000000..7daaf4969aa770eafb00f4a4183821d79dcf55a2 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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_safe_load +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_safe_load(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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/explicit.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/explicit.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5f4925ddb557535b6c8da5100705bccee99a74 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/requirements.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..fd39e94116c226821083605ab6c64e6322ff2ea9 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/yaml_file.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/env/specs/yaml_file.py new file mode 100644 index 0000000000000000000000000000000000000000..2246c35ecfb89d4e86a20f0e7d0b2005ba27dd6a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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_safe_load +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_safe_load(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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f7052773f52043727fe66b1bf54c918f7aaeb1 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ee0c3c648c97be2a0e293617c743d899242fb83 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/anaconda_client.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/anaconda_client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bc16d36f6cf152a41c9c2d06d80ede66d38e402 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/anaconda_client.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/logging.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/logging.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c59ba5028a5f4c3cd95f27223b3a08734ef78ff Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/logging.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/subprocess.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/subprocess.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ac2b6b5149f8edca3a9422c3529531c8192438e Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/__pycache__/subprocess.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/anaconda_client.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/anaconda_client.py new file mode 100644 index 0000000000000000000000000000000000000000..75a16f782a77bf19ed7dd38ce9d631799c78a302 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21beee6400fb947266f0112b7c83fba2b2fb9e01 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ce9ad7fc6c5667c798e15c8b88d2c3addc843e Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/download.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/download.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17fb75b2ddce65ccb013e8d9d6fa4e2f8a8c3123 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/download.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/session.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/session.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a9bbf28e11f7d9def7f6b390524679c65a3bd15 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/__pycache__/session.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbf7f2322f75c92c08b13646a5baa5372ae7c2e2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/ftp.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/ftp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94808677d99121d8c6735bb16ad0dcb4d6b30be5 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/ftp.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/http.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/http.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd23e186b4e8c3c29998521ec6485e951d5d59e2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/http.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/localfs.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/localfs.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..690242600a3ba25d64017d8b91911a74c6037f47 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/localfs.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/s3.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/s3.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2493efe5b24fed8752430db8bdb80f708b75774 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/__pycache__/s3.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/ftp.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/ftp.py new file mode 100644 index 0000000000000000000000000000000000000000..05faa09862f2a700f217f15370ab46df8e82cb14 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/http.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/http.py new file mode 100644 index 0000000000000000000000000000000000000000..524d2b29de288b2cefda22232c1789c5f9ab9a14 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/localfs.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/localfs.py new file mode 100644 index 0000000000000000000000000000000000000000..18496e8fa9a4561bb688536352aa136e20f78954 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/s3.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/adapters/s3.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0caaae8dcd3254b0f08faa9428025eeb3a749e --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/download.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/download.py new file mode 100644 index 0000000000000000000000000000000000000000..e718d663587e957c84084e56f858cd651a975f12 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/download.py @@ -0,0 +1,375 @@ +# 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.context import context +from ...common.io import time_recorder +from ...exceptions import ( + BasicClobberError, + ChecksumMismatchError, + CondaDependencyError, + CondaHTTPError, + CondaSSLError, + CondaValueError, + ProxyError, + maybe_raise, +) +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" + 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: + 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, + getattr(e.response, "status_code", None), + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/session.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/session.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7373d40236e39d81a86084e20e5f36235d3bf6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/connection/session.py @@ -0,0 +1,353 @@ +# 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, 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", + ) +) + + +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 + + +@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"): + request.headers = CaseInsensitiveDict( + { + # hardcoded session headers (self.headers) are injected in super().prepare_request + **context.plugin_manager.get_cached_session_headers( + host=url.netloc + ), + **context.plugin_manager.get_cached_request_headers( + host=url.netloc, path=url.path + ), + **(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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4266b40adef99cc48b7044f395faaf5242ed8d9 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0810340fb322ec4358c4957aa23c234a98c228ec Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/create.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/create.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48b7b3385146e7532e9eb2f900ff54da3f96674e Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/create.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/delete.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/delete.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45149e5fe83961a8b72dc376498bfd7311635829 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/delete.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/link.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/link.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93e58e8af771529e28475a85f0cc7ff7d2bebfe5 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/link.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/lock.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/lock.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69a0fcdb1b9eb7e27a503a468311be363fae3e18 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/lock.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/permissions.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/permissions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a8e663ea98540d95c4ee199a6f361f9b38a7b51 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/permissions.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/read.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/read.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..995565ff692183ef7693af14944a50401931fec2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/read.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/test.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1561929c034da73af6d5ddec895b4a4d88b25258 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/test.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/update.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/update.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82ea16bcf10fe41bee33a1373651dc008a0bfa11 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/__pycache__/update.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/create.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/create.py new file mode 100644 index 0000000000000000000000000000000000000000..e08f5b921967d0db5b117500baa555004818482d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/create.py @@ -0,0 +1,534 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Disk utility functions for creating new files or directories.""" + +import codecs +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 CONDA_PACKAGE_EXTENSION_V1, PACKAGE_CACHE_MAGIC_FILE +from ...base.context import context +from ...common.compat import on_linux, 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 path_is_clean, 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 codecs.open(file_path, mode="wb", 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 codecs.open(target_full_path, mode="wb", 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) + + +def extract_tarball( + tarball_full_path, destination_directory=None, progress_update_callback=None +): + import conda_package_handling.api + + if destination_directory is None: + if tarball_full_path[-8:] == CONDA_PACKAGE_EXTENSION_V1: + destination_directory = tarball_full_path[:-8] + else: + destination_directory = tarball_full_path.splitext()[0] + 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) + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/delete.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/delete.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe2b22ae1770b4164752ca8b2a56a12cec7c178 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/link.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/link.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc3d1dde3714ed6957d01aab0d50129b2ebeee8 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/lock.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/lock.py new file mode 100644 index 0000000000000000000000000000000000000000..8abf8e0dd621da81135a8ae4d13497d5c9ab6686 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/permissions.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..49a3ba38dfb6ca249fcdc1fda854b6fa6eaf3648 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/read.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/read.py new file mode 100644 index 0000000000000000000000000000000000000000..a8476a04424c3ec65ffff4cad545710e297ff083 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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, PathType +from ...models.package_info import PackageInfo, PackageMetadata +from ...models.records import PathData, 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"] = PathType.softlink + else: + path_info["path_type"] = PathType.hardlink + yield PathData(**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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/test.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/test.py new file mode 100644 index 0000000000000000000000000000000000000000..678332194228bc882a7d7831aeada1513f44553c --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/update.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/disk/update.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc403919f54c9a0bf745b6c5cd9d70457337d4a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/logging.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..a47d744782a8aaf8050c0cc0f7730acec5b6c9b9 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f2df4675dffdb51e761a6dcef09a09226cc7522 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__init__.py @@ -0,0 +1,961 @@ +# 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.""" + + #: Channel URL + _url: str + + #: Filename of the repodata file; defaults to value of conda.base.constants.REPODATA_FN + _repodata_fn: str + + 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 in (403, 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 == 401: + channel = Channel(url) + if channel.token: + help_message = """\ +The token '{}' given for the URL is invalid. + +If this token was pulled from anaconda-client, you will need to use +anaconda-client to reauthenticate. + +If you supplied this token to conda directly, 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( + channel.token, + join_url(CONDA_HOMEPAGE_URL, "docs/config.html"), + ) + + elif context.channel_alias.location in url: + # Note, this will not trigger if the binstar configured url does + # not match the conda configured one. + help_message = """\ +The remote server has indicated you are using invalid credentials for this channel. + +If the remote site is anaconda.org or follows the Anaconda Server API, you +will need to + (a) remove the invalid token from your system with `anaconda logout`, optionally + followed by collecting a new token with `anaconda login`, 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac59b074ab0e5b6bef7f534a93489882515da70a Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__pycache__/lock.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__pycache__/lock.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..349f9f9a819d97e0378fcd8c612bd32e33c3a763 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/__pycache__/lock.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f2bd35a5dc213cfb16dade89ef152bae35bf68 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1386188041b6d36ca5baf6b427c1ca8f932f5818 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/core.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..896d5f8b260325c76616e307941e136e90de3778 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/core.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/fetch.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/fetch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0303e293b0d4f0a6353c921e4946bd89e7e7459b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/fetch.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/interface.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/interface.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3e7102ba836ae8d69c150fa65222ed1059e25a7 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/__pycache__/interface.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/core.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/core.py new file mode 100644 index 0000000000000000000000000000000000000000..ddb477e04469e81c75ea736fde2cf4731a778896 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/fetch.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd830d2a6a8f0ebf80d818728b728d0550b7a43 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/interface.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/jlap/interface.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee10eecd685700aba8b5ea6363d6d7a182a5b9f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/lock.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/repodata/lock.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8621a1aacd7fbaa84d1820c325ca31363b938c --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/subprocess.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/gateways/subprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..2daaa70f086c88cb9ef66367b40238656744e8be --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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, 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8865bd1006886c03552ce00b01f0b6d04d6de619 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a97131430cff0a16643759a3572ef894fbd0fa1 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/channel.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/channel.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a2a9618996d950de86255f9bcb7e33d113ea1db Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/channel.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/dist.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/dist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1447f7463421ab11bf5906362c2bf2e47bcdad77 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/dist.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/enums.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/enums.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..122fe1abdaa85c9b2ee13ad53d5981590eb12f31 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/enums.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/environment.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/environment.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bb7f77482e617c25d85e6c73fa82412da53948b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/environment.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/match_spec.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/match_spec.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e187856ed8dd30379cdf6558852e64a1e33190b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/match_spec.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/package_info.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/package_info.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7953cbe04120bf68138eb3352902165c2071aff Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/package_info.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/prefix_graph.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/prefix_graph.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75c3851713aafa0857ed60c44d353889da0a820c Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/prefix_graph.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/records.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/records.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1db01be8da581c4dbcc86207d0b8862d61145eee Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/records.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/version.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55575d924e7706d2136220d32cfd58b141e97b12 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/__pycache__/version.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/channel.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/channel.py new file mode 100644 index 0000000000000000000000000000000000000000..1186bb3acec2f41c7d87e14c9f27c6359b2ae420 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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_package_file, 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 is_package_file(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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/dist.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..67a86775da1da3d9ce2a954784547931126188b9 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/dist.py @@ -0,0 +1,377 @@ +# 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 ( + CONDA_PACKAGE_EXTENSIONS, + 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) + + +def strip_extension(original_dist): + for ext in CONDA_PACKAGE_EXTENSIONS: + if original_dist.endswith(ext): + original_dist = original_dist[: -len(ext)] + return original_dist + + +def split_extension(original_dist): + stripped = strip_extension(original_dist) + return stripped, original_dist[len(stripped) :] + + +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 any(url.endswith(ext) for ext in CONDA_PACKAGE_EXTENSIONS) + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/enums.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/enums.py new file mode 100644 index 0000000000000000000000000000000000000000..2c6aa30b632cec6cb0d395479b48c985545e9483 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/enums.py @@ -0,0 +1,175 @@ +# 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 ..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 PathType(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 (PathType.hardlink, PathType.softlink, PathType.directory) + + def __str__(self): + return self.name + + def __json__(self): + return self.name + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/environment.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..c75a513ca9e3e99947f4f41116af3f825a8e2f74 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/environment.py @@ -0,0 +1,581 @@ +# 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. + """ + + #: The platform this environment may be installed on (required) + platform: str + + #: 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 + config: EnvironmentConfig = field(default_factory=EnvironmentConfig) + + #: Map of other package types that conda can install. For example pypi packages. + external_packages: dict[str, list[str]] = field(default_factory=dict) + + #: The complete list of specs for the environment. + #: eg. after a solve, or from an explicit environment spec + explicit_packages: list[PackageRecord] = field(default_factory=list) + + #: Environment name + name: str | None = None + + #: Prefix the environment is installed into. + prefix: str | None = None + + #: User requested specs for this environment. + requested_packages: list[MatchSpec] = field(default_factory=list) + + #: Environment variables to be applied to the environment. + variables: dict[str, str] = field(default_factory=dict) + + # 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/match_spec.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/match_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4c8f31152817223d1384e84dba07f324297136 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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, is_package_file, 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 is_package_file(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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/package_info.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/package_info.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff2faa23f4235f21d0a54a10a0870ce2ed9e93f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/prefix_graph.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/prefix_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..27d8e263688ff4341c02d926650f1bd288be65c4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/records.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/records.py new file mode 100644 index 0000000000000000000000000000000000000000..1a7aa54801046d0dfa47971690f35563908a42c4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/records.py @@ -0,0 +1,669 @@ +# 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 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, PathType, 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(PathType) + + @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 PathType.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(PathData) + + +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`. + """ + + #: str: The name of the package. + #: + #: Part of the :attr:`_pkey`. + name = StringField() + + #: str: The version of the package. + #: + #: Part of the :attr:`_pkey`. + version = StringField() + + #: str: The build string of the package. + #: + #: Part of the :attr:`_pkey`. + build = StringField(aliases=("build_string",)) + + #: int: The build number of the package. + #: + #: Part of the :attr:`_pkey`. + build_number = IntegerField() + + # the canonical code abbreviation for PackageRef is `pref` + # fields required to uniquely identifying a package + + #: :class:`conda.models.channel.Channel`: The channel where the package can be found. + channel = ChannelField(aliases=("schannel",)) + + #: str: The subdir, i.e. ``noarch`` or a platform (``linux-64`` or similar). + #: + #: Part of the :attr:`_pkey`. + subdir = SubdirField() + + #: str: The filename of the package. + #: + #: Only part of the :attr:`_pkey` if :ref:`separate_format_cache ` is ``true`` (default: ``false``). + fn = FilenameField(aliases=("filename",)) + + #: str: The md5 checksum of the package. + md5 = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + + #: str: If this is a ``.conda`` package and a corresponding ``.tar.bz2`` package exists, this may contain the md5 checksum of that package. + legacy_bz2_md5 = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + + #: str: If this is a ``.conda`` package and a corresponding ``.tar.bz2`` package exists, this may contain the size of that package. + legacy_bz2_size = IntegerField(required=False, nullable=True, default_in_dump=False) + + #: str: The download url of the package. + url = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + + #: str: The sha256 checksum of the package. + sha256 = StringField( + default=None, required=False, nullable=True, default_in_dump=False + ) + + @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. + """ + + #: str: Full path to the local package file. + package_tarball_full_path = StringField() + + #: str: Full path to the local extracted package. + extracted_package_dir = StringField() + + #: str: The md5 checksum of the package. + #: + #: If the package file exists locally, this class can calculate a missing checksum on-the-fly. + md5 = Md5Field() + + @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. + """ + + #: str: The :class:`MatchSpec` that the user requested or ``None`` if the package it was installed as a dependency. + requested_spec = StringField(required=False) + + +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`. + """ + + #: str: The path to the originating package file, usually in the local cache. + package_tarball_full_path = StringField(required=False) + + #: str: The path to the extracted package directory, usually in the local cache. + extracted_package_dir = StringField(required=False) + + #: list(str): The list of all files comprising the package as relative paths from the prefix root. + files = ListField(str, default=(), required=False) + + #: list(str): List with additional information about the files, e.g. checksums and link type. + paths_data = ComposableField( + PathsData, required=False, nullable=True, default_in_dump=False + ) + + #: :class:`Link`: Information about how the package was linked into the prefix. + link = ComposableField(Link, required=False) + + # 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. + #: str: Authentication information. + auth = StringField(required=False, nullable=True) + + # @classmethod + # def load(cls, conda_meta_json_path): + # return cls() diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/version.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/models/version.py new file mode 100644 index 0000000000000000000000000000000000000000..e8feac91fefaf38927daa43f1b23ac9c2b16bd67 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c1517621a9bb248d79269264697839e0af1a88 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..989c02dc302034999bd76477ade2994089e2b6c1 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/cache.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/cache.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35bd0e27cc2fe63e3d55f350abaf66e447ce38c Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/cache.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/core.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bd168afb14aa12604d458ae54b50a5fbbf6a116 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/core.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/fetch.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/fetch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e20e526d65fdb3b7b09b639e4f06fb2c598a0fcf Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/fetch.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/types.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ed98b293571cab31cd530bbf9423e19d13cb9c6 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/types.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/views.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/views.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de8927d8b10b158acc289146f681d23b5de28a7d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/__pycache__/views.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/cache.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..76f5eb1ff1f9e1eac44fc9f8837824c85b25723b --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/core.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/core.py new file mode 100644 index 0000000000000000000000000000000000000000..913675fd2f9393ccd9430f094112264d8c893bfa --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/fetch.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..7b1421e4d3db1671df2827b856fb717d97bc1b35 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/types.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/types.py new file mode 100644 index 0000000000000000000000000000000000000000..7ab69abd9e06b043dab27db0edf37bd3db7ad67a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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 + +#: Value to use for message ID when it is not provided +UNDEFINED_MESSAGE_ID = "undefined" + + +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 that are included in this particular set + channel_notices: Sequence[ChannelNotice] + + #: Total number of channel notices; not just the ones that will be displayed + total_number_channel_notices: int + + #: The number of channel notices that have already been viewed + viewed_channel_notices: int + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/views.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/notices/views.py new file mode 100644 index 0000000000000000000000000000000000000000..e67d1a5c3a297345aa0d12664695154989ba6a66 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8312a73c04d8fcdb12e1804e75c5dd3b3d3d3e68 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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`` subcommand +- :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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b438cc1b5710544399943f5c5d6acef741d7f950 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/config.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dbe906de1bfdd72ee54630e6d2000595e3b9a4a Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/config.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/hookspec.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/hookspec.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9254065adbc178a22a96d8bded9d120cb3bdbf8 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/hookspec.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/manager.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/manager.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caeed2c04935f0e29e5796a79fece7f79fb79629 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/manager.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/solvers.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/solvers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e8adc72e8cc7f19b4c61296318ef227997e4f97 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/solvers.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/types.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ee3c47a06c4783de6f9ba9e9449f5a36a62eac2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/__pycache__/types.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/config.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/config.py new file mode 100644 index 0000000000000000000000000000000000000000..24c99235da1a575aea45ad1cc0b82eae79c55e15 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f9565e7558a007af0fa40aec88eb656265adf6c3 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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 + +#: The list of environment exporter plugins for easier registration with pluggy +plugins = [environment_yml, explicit, requirements_txt] diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10a50f08d2c312da5dc1516c260876c09bd8fd96 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/environment_yml.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/environment_yml.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6904afd36987521251358fb35797f8327d3417dd Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/environment_yml.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/explicit.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/explicit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1d39ebfca8f3aacde8065eed421449bc3b9d4c9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/explicit.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/requirements_txt.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/requirements_txt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ebe3fc61b3ebaf759141ed375d15b8fcd85b7a2 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/__pycache__/requirements_txt.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/environment_yml.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/environment_yml.py new file mode 100644 index 0000000000000000000000000000000000000000..413907449cd652b8bfa09053ae9747cf3978b506 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/environment_yml.py @@ -0,0 +1,114 @@ +# 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 ruamel.yaml.error import YAMLError + +from ...common.serialize import json, yaml_safe_dump +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 + +#: The name of the environment-json format +ENVIRONMENT_JSON_FORMAT: Final = "environment-json" + +#: The name of the environment-yaml format +ENVIRONMENT_YAML_FORMAT: Final = "environment-yaml" + +#: Type alias for format validation +EnvironmentFormatType = Literal["environment-json", "environment-yaml"] + + +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_safe_dump(env_dict) + except 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/explicit.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/explicit.py new file mode 100644 index 0000000000000000000000000000000000000000..d1bce6cbe2e73887eca396100f426a95854243fb --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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 + + +#: The name of the explicit format +EXPLICIT_FORMAT: Final = "explicit" + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/requirements_txt.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_exporters/requirements_txt.py new file mode 100644 index 0000000000000000000000000000000000000000..c42ed383dd0867b9d178c0d7663362e2591f7d10 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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 + + +#: The name of the requirements format +REQUIREMENTS_FORMAT: Final = "requirements" + + +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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75bc196c0419d658d1d5e23410ed254f56c6bd57 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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 + +#: The list of environment specifier plugins for easier registration with pluggy +plugins = [cep_24, requirements_txt, environment_yml, explicit] diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48d8a5c20cf17e2ce1c7e066e0dc83e2eacf0210 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/cep_24.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/cep_24.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fceb9e1280b229938136c35a92839da5a388e14 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/cep_24.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/environment_yml.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/environment_yml.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed0e538c9c1ca3a493383a58b6bcba78d0b3e40f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/environment_yml.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/explicit.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/explicit.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3b063b3c4187219c6b1a71c9cbdea0150fe3d92 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/explicit.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/requirements_txt.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/requirements_txt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43b4987ebed8c587e666b7513b152c539e7da721 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/__pycache__/requirements_txt.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/cep_24.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/cep_24.py new file mode 100644 index 0000000000000000000000000000000000000000..78a347e8b41ba2c3a11f4971ac8c20a6a458235b --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/environment_yml.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/environment_yml.py new file mode 100644 index 0000000000000000000000000000000000000000..badb66137bec679476372ab9b4b6c0e349055837 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/explicit.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/explicit.py new file mode 100644 index 0000000000000000000000000000000000000000..d818e96ba4abe7ccfd9238eff3a3c1b2110d00eb --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/requirements_txt.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/environment_specifiers/requirements_txt.py new file mode 100644 index 0000000000000000000000000000000000000000..962aedee715535faf7567e8992cb15f1f9cc91f6 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/hookspec.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/hookspec.py new file mode 100644 index 0000000000000000000000000000000000000000..5178963d296d43b8a8b38bd1b85cd23ebb4d1d9c --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/hookspec.py @@ -0,0 +1,736 @@ +# 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, + 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.", +) + +#: Decorator to mark conda plugin hook specifications, used to register plugin hook types +_hookspec = pluggy.HookspecMarker(APP_NAME) + +#: Decorator to mark plugin hook implementations, used to register plugins +hookimpl = pluggy.HookimplMarker(APP_NAME) + + +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.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.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.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.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.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.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. + + **Example:** + + .. 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.CondaHealthCheck( + name="example-health-check", + action=example_health_check, + ) + """ + 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.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[plugins.CondaPreTransactionAction]: + yield plugins.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.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[plugins.CondaPostTransactionAction]: + yield plugins.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.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.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.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.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.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 () diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/manager.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..6785c6ecf7dfd6c5be6f7c44254f208a00830819 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/manager.py @@ -0,0 +1,850 @@ +# 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, + 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 ..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, + 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. + """ + + #: Cached version of the :meth:`~conda.plugins.manager.CondaPluginManager.get_solver_backend` + #: method. + get_cached_solver_backend: Callable[[str | None], type[Solver]] + + #: Cached version of the :meth:`~conda.plugins.manager.CondaPluginManager.get_session_headers` + #: method. + get_cached_session_headers: Callable[[str], dict[str, str]] + + #: Cached version of the :meth:`~conda.plugins.manager.CondaPluginManager.get_request_headers` + #: method. + get_cached_request_headers: Callable[[str, str], dict[str, str]] + + 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["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_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_health_checks(self, prefix: str, verbose: bool) -> None: + for hook in self.get_hook_results("health_checks"): + try: + hook.action(prefix, verbose) + except Exception as err: + log.warning(f"Error running health check: {hook.name} ({err})") + continue + + 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") + ] + + +@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, + *post_solves.plugins, + *reporter_backends.plugins, + *prefix_data_loaders.plugins, + *environment_specifiers.plugins, + *environment_exporters.plugins, + ) + plugin_manager.load_entrypoints(APP_NAME) + return plugin_manager diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce06f651282543a093310b6affe79dad715c9073 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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 + +#: The list of post-solve plugins for easier registration with pluggy +plugins = [signature_verification] diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fda8f6f3deda7c902d3e0315eb654ddbaeded515 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__pycache__/signature_verification.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__pycache__/signature_verification.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..678cda6219188690b817dbac746dfc78528c6dbf Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/__pycache__/signature_verification.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/signature_verification.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/signature_verification.py new file mode 100644 index 0000000000000000000000000000000000000000..4654a34558e59f5e313353ffce23dd9a852b9135 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/post_solves/signature_verification.py @@ -0,0 +1,16 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Register signature verification as a post-solve plugin.""" + +from .. import hookimpl +from ..types import CondaPostSolve + + +@hookimpl +def conda_post_solves(): + from ...trust.signature_verification import signature_verification + + yield CondaPostSolve( + name="signature-verification", + action=signature_verification, + ) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de899adfffc69c9594437ce8063789342512916a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9950c856999c0c06dbf7700b8836ca0c22eded Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93e2b8b9b26f7316cae4d32d53320a3fe9ab4299 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__init__.py @@ -0,0 +1,160 @@ +# 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 re +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 ....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 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 = get_python_site_packages_short_path(python_pkg_record.version) + site_packages_path = prefix_path / win_path_ok(site_packages_dir) + + if not 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( + site_packages_dir, python_records + ) + + # 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( + site_packages_path, 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 + + +def get_conda_anchor_files_and_records(site_packages_short_path, python_records): + """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 + + for prefix_record in python_records: + anchor_paths = tuple(fpath for fpath in prefix_record.files if matcher(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 + + +@hookimpl(tryfirst=True) +def conda_prefix_data_loaders(): + yield CondaPrefixDataLoader("pypi", load_site_packages) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d01a620ba2d31bef6d3c02d939bede032d5e066 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__pycache__/pkg_format.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__pycache__/pkg_format.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03f783eee241e780a41b23bef241d600e88722d8 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/__pycache__/pkg_format.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/pkg_format.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/pkg_format.py new file mode 100644 index 0000000000000000000000000000000000000000..74fc83e188839e9805fb763e2571522467a0e884 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/prefix_data_loaders/pypi/pkg_format.py @@ -0,0 +1,1298 @@ +# 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 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, PathType +from ....models.records import PathData, 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:] + 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=PathType.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=( + PathData(_path=path, path_type=PathType.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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d890f55343640de051d7521c68efd224f2fcf1cc --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40ced50279811b30a36d66737c23a2d425f6555c Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/console.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/console.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c0d955531114072f167eed787b445d09a0127d0 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/console.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/json.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/json.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..deb23f735ec1c45d83df504eeb77b585b005333a Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/__pycache__/json.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/console.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/console.py new file mode 100644 index 0000000000000000000000000000000000000000..d72621d0829fb79b8e7581db2776b8b3515a7996 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/console.py @@ -0,0 +1,298 @@ +# 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 .. 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 "" + + 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 " " + 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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/json.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/reporter_backends/json.py new file mode 100644 index 0000000000000000000000000000000000000000..7cba1f83778ccfa9393214a23a897f8e1217c93d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/solvers.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/solvers.py new file mode 100644 index 0000000000000000000000000000000000000000..abdb0f548d379955c4432bf6ec15b7914547fb97 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f195138e5d12bc0f06dfc2f60e484bca4e53bc77 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf45e1efc5a764c63e08a9f8544ff923bdcb72e1 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..358abac38a66d7496ddd3c7fc9bb17baf42f19c5 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__init__.py @@ -0,0 +1,48 @@ +# 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 + +from typing import TYPE_CHECKING + +from ....base.context import context +from ....cli.helpers import ( + add_parser_help, + add_parser_prefix, + add_parser_verbose, +) +from ....core.prefix_data import PrefixData +from ... import hookimpl +from ...types import CondaSubcommand + +if TYPE_CHECKING: + from argparse import ArgumentParser, Namespace + + +def configure_parser(parser: ArgumentParser): + add_parser_verbose(parser) + add_parser_help(parser) + add_parser_prefix(parser) + + +def execute(args: Namespace) -> None: + """Run registered health_check plugins.""" + prefix_data = PrefixData.from_context() + prefix_data.assert_environment() + prefix = str(prefix_data.prefix_path) + print(f"Environment Health Report for: {prefix}\n") + context.plugin_manager.invoke_health_checks(prefix, context.verbose) + + +@hookimpl +def conda_subcommands(): + yield CondaSubcommand( + name="doctor", + summary="Display a health report for your environment.", + action=execute, + configure_parser=configure_parser, + ) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9df4808fb43be53598790548288ac27278959d9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__pycache__/health_checks.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__pycache__/health_checks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d74e2cf4e03b8c6810775f306fa18fe9c7bd23ee Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/__pycache__/health_checks.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..d53ab07d3327ff81acaf3c6d0613a065ab6e5485 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/subcommands/doctor/health_checks.py @@ -0,0 +1,320 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +"""Backend logic implementation for `conda doctor`.""" + +from __future__ import annotations + +import os +from logging import getLogger +from pathlib import Path + +from requests.exceptions import RequestException + +from ....base.constants import PREFIX_PINNED_FILE +from ....base.context import context +from ....common.io import dashlist +from ....common.serialize import json, yaml_safe_dump +from ....core.envs_manager import get_user_environments_txt_file +from ....core.prefix_data import PrefixData +from ....exceptions import CondaError +from ....gateways.connection.session import get_session +from ....gateways.disk.lock import locking_supported +from ....gateways.disk.read import compute_sum +from ....models.match_spec import MatchSpec +from ... import hookimpl +from ...types import CondaHealthCheck + +logger = getLogger(__name__) + +OK_MARK = "✅" +X_MARK = "❌" + + +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: + # FileNotFoundError: path doesn't exist + 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 excluded_files_check(filename: str) -> bool: + 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", []): + # Add warnings if json file has missing "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 find_altered_packages(prefix: str | Path) -> dict[str, list[str]]: + """Finds altered packages""" + 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 missing_files(prefix: str, verbose: bool) -> None: + missing_files = find_packages_with_missing_files(prefix) + if missing_files: + print(f"{X_MARK} Missing Files:\n") + for package_name, missing_files in missing_files.items(): + if verbose: + delimiter = "\n " + print(f"{package_name}:{delimiter}{delimiter.join(missing_files)}") + else: + print(f"{package_name}: {len(missing_files)}\n") + else: + print(f"{OK_MARK} There are no packages with missing files.\n") + + +def altered_files(prefix: str, verbose: bool) -> None: + altered_packages = find_altered_packages(prefix) + if altered_packages: + print(f"{X_MARK} Altered Files:\n") + for package_name, altered_files in altered_packages.items(): + if verbose: + delimiter = "\n " + print(f"{package_name}:{delimiter}{delimiter.join(altered_files)}\n") + else: + print(f"{package_name}: {len(altered_files)}\n") + else: + print(f"{OK_MARK} There are no packages with altered files.\n") + + +def env_txt_check(prefix: str, verbose: bool) -> None: + 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 requests_ca_bundle_check(prefix: str, verbose: bool) -> None: + # 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" + ) + + +def consistent_env_check(prefix: str, verbose: bool) -> None: + # get the plugin manager from context + pm = context.plugin_manager + + # get prefix data + pd = PrefixData(prefix) + + # get virtual packages record + virtual_packages = { + record.name: record for record in pm.get_virtual_package_records() + } + + # collect missing dependency issues in a list + issues = {} + + # check if dependencies are present + for record in pd.iter_records(): + for dependency in record.depends: + match_spec = MatchSpec(dependency) + dependency_record = pd.get( + match_spec.name, default=virtual_packages.get(match_spec.name, None) + ) + if dependency_record is None: + issues.setdefault(record.name, {}).setdefault("missing", []).append( + str(match_spec) + ) + elif not match_spec.match(dependency_record): + inconsistent = { + "expected": str(match_spec), + "installed": str(dependency_record), + } + issues.setdefault(record.name, {}).setdefault( + "inconsistent", [] + ).append(inconsistent) + + for constrain in record.constrains: + package_found = pd.get( + MatchSpec(constrain).name, + default=virtual_packages.get(MatchSpec(constrain).name, None), + ) + if package_found is not None: + if not MatchSpec(constrain).match(package_found): + inconsistent_constrain = { + "expected": str(MatchSpec(constrain)), + "installed": f"{package_found.name}[version='{package_found.version}']", + } + issues.setdefault(record.name, {}).setdefault( + "inconsistent", [] + ).append(inconsistent_constrain) + + if issues: + print(f"{X_MARK} The environment is not consistent.\n") + if verbose: + print(yaml_safe_dump(issues)) + else: + print(f"{OK_MARK} The environment is consistent.\n") + + +def pinned_well_formatted_check(prefix: str, verbose: bool) -> None: + prefix_data = PrefixData(prefix_path=prefix) + + try: + pinned_specs = prefix_data.get_pinned_specs() + except OSError as err: + print( + f"{X_MARK} Unable to open pinned file at {prefix_data.prefix_path / PREFIX_PINNED_FILE}:\n\t{err}" + ) + except Exception as err: + print( + f"{X_MARK} An error occurred trying to read pinned file at {prefix_data.prefix_path / PREFIX_PINNED_FILE}:\n\t{err}" + ) + return + + # If there are no pinned specs, exit early + if not pinned_specs: + print( + f"{OK_MARK} No pinned specs found in {prefix_data.prefix_path / PREFIX_PINNED_FILE}." + ) + return + + # If there is a pinned package that does not exist in the prefix, that + # is an indication that it might be a typo. + maybe_malformed = [ + pinned for pinned in pinned_specs if not any(prefix_data.query(pinned.name)) + ] + + # Inform the user of any packages that might be malformed + if maybe_malformed: + print( + f"{X_MARK} The following specs in {prefix_data.prefix_path / PREFIX_PINNED_FILE} are maybe malformed:" + ) + print(dashlist((spec.name for spec in maybe_malformed), indent=4)) + return + + # If there are no malformed packages, the pinned file is well formatted + print( + f"{OK_MARK} The pinned file in {prefix_data.prefix_path / PREFIX_PINNED_FILE} seems well formatted." + ) + + +def file_locking_check(prefix: str, verbose: bool): + """ + Report if file locking is supported or not. + """ + 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(): + yield CondaHealthCheck(name="Missing Files", action=missing_files) + yield CondaHealthCheck(name="Altered Files", action=altered_files) + yield CondaHealthCheck(name="Environment.txt File Check", action=env_txt_check) + yield CondaHealthCheck( + name="REQUESTS_CA_BUNDLE Check", action=requests_ca_bundle_check + ) + yield CondaHealthCheck( + name="Consistent Environment Check", action=consistent_env_check + ) + yield CondaHealthCheck( + name=f"{PREFIX_PINNED_FILE} Well Formatted Check", + action=pinned_well_formatted_check, + ) + yield CondaHealthCheck( + name="File Locking Supported Check", + action=file_locking_check, + ) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/types.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/types.py new file mode 100644 index 0000000000000000000000000000000000000000..4b49d67bdf0d226e05f9a30d8e1a988afb58cb98 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/types.py @@ -0,0 +1,592 @@ +# 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], + ] + + SinglePlatformEnvironmentExport = Callable[[Environment], str] + MultiPlatformEnvironmentExport = Callable[[Iterable[Environment]], str] + + +@dataclass +class CondaPlugin: + """ + Base class for all conda plugins. + """ + + #: User-facing name of the plugin used for selecting & filtering plugins and error messages. + name: str + + 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. + """ + + name: str + action: Callable[[str, bool], 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}" + ) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0fd7a534bd4225e16ecfcae372984cfb46258895 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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 + +#: The list of virtual package plugins for easier registration with pluggy +plugins = [archspec, conda, cuda, freebsd, linux, osx, windows] diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cfa40305fedc38cf1aae4075c2d91209863803d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/archspec.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/archspec.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edeac57b30aaa491debcbb000ed6dbdf2841f3e9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/archspec.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/conda.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/conda.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1e99d7489c7d98b27a9ba8ca2b84b00c3d4c7e9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/conda.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/cuda.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/cuda.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..463fef0686cd24e7af6c8016f0522f2bbcdd5b78 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/cuda.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/freebsd.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/freebsd.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75b5475b677d7dfd3a5081f430c798c7a1953976 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/freebsd.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/linux.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/linux.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56c613c174835d65bfd6effbf50323c0b768c035 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/linux.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/osx.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/osx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95f5ddd55dd0acc43c885d6e725446b806beeae1 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/osx.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/windows.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/windows.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc60b05c2f139a100465fc74340141e42e2d73e1 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/__pycache__/windows.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/archspec.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/archspec.py new file mode 100644 index 0000000000000000000000000000000000000000..0496aad5b9cddd8d1c3b06413b74947c92405b3f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/conda.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/conda.py new file mode 100644 index 0000000000000000000000000000000000000000..76f3d6194ac1b15b13ae06e20f8a99b079a27558 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/cuda.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..45f0ccddc5db7209f06aa6f7617354fa3a2cabbc --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/freebsd.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/freebsd.py new file mode 100644 index 0000000000000000000000000000000000000000..5936f304ed65f9649354facbc292935f8a739012 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/linux.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/linux.py new file mode 100644 index 0000000000000000000000000000000000000000..8091686099e78dd15fb08d8c63f720a3d3b63986 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/osx.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/osx.py new file mode 100644 index 0000000000000000000000000000000000000000..7754ca8ef62f66453f53e39d5059f5eca7b49a11 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/windows.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/plugins/virtual_packages/windows.py new file mode 100644 index 0000000000000000000000000000000000000000..70b04c02410538f137fdf707384b734160e6a12e --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat new file mode 100644 index 0000000000000000000000000000000000000000..c8ee68989b53660ff2016bac41cd2d6fdc920fb4 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/Scripts/activate.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/Scripts/activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..99a7d88a79d24ca40a7da6c16482af6f6167435b --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/bin/activate b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/bin/activate new file mode 100644 index 0000000000000000000000000000000000000000..4cebf4d7698577655a38e1823a3a2c4631ebc99b --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/bin/deactivate b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/bin/deactivate new file mode 100644 index 0000000000000000000000000000000000000000..116a6f5798c242699130ab91ad4edb85ac39235a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/cli-32.exe b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/cli-32.exe new file mode 100644 index 0000000000000000000000000000000000000000..4e6d4af282b035a588c68ed9364d1f0ef2f53f63 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/cli-32.exe differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/cli-64.exe b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/cli-64.exe new file mode 100644 index 0000000000000000000000000000000000000000..c62a80ce33c321e43566bc1a5a6731248b4b5ff9 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/cli-64.exe differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/conda.xsh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/conda.xsh new file mode 100644 index 0000000000000000000000000000000000000000..088ccab454a981897d58e4157958317230b2e4f9 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/Conda.psm1 b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/Conda.psm1 new file mode 100644 index 0000000000000000000000000000000000000000..64f51c1d0c9f04e04658172b606ab4a13ce7a084 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/_conda_activate.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/_conda_activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..5e7db6413144b9db1153f6e52390943b2629894a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/_conda_activate.bat @@ -0,0 +1,53 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +:: Helper routine for activation, deactivation, and reactivation. +@ECHO OFF +SETLOCAL +SET "__conda_tmp=%TEMP%\__conda_tmp_%RANDOM%.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 %ERRORLEVEL% NEQ 0 ( + ECHO Failed to run 'conda %*'. + IF EXIST "%__conda_tmp%" DEL /F /Q "%__conda_tmp%" 2>NUL + ENDLOCAL & EXIT /B 1 +) + +:: Check if conda produced output +FOR /F "delims=" %%T IN (%__conda_tmp%) DO ( + IF NOT EXIST "%%T" ( + ECHO Failed to run 'conda %*'. + DEL /F /Q "%__conda_tmp%" 2>NUL + ENDLOCAL & EXIT /B 2 + ) ELSE ENDLOCAL & ( + FOR /F "tokens=1,* delims==" %%A IN (%%T) DO ( + IF "%%A"=="_CONDA_SCRIPT" ( + :: Script execution + CALL "%%B" + ) 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 Failed to run 'conda %*'. +IF EXIST "%__conda_tmp%" DEL /F /Q "%__conda_tmp%" 2>NUL +ENDLOCAL & EXIT /B 3 diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/activate.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..c49a240735327f9c393839c4bcc0920a391543cf --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda-hook.ps1 b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda-hook.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..65a911f92ee3debad596dc3e02822978c05c372d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda.bat new file mode 100644 index 0000000000000000000000000000000000000000..383f50eb60c52f401812acf3d06f615bde9491aa --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda_auto_activate.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda_auto_activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..6e78551fc6b51e3ed53de8e6a8d84ab51d854616 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda_hook.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/conda_hook.bat new file mode 100644 index 0000000000000000000000000000000000000000..4df22f14af50b0cf6a3f4baeb9892049b5490e46 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/deactivate.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/deactivate.bat new file mode 100644 index 0000000000000000000000000000000000000000..7bf8f53adf2ab0e25e9a08920e48c266410d57b2 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/rename_tmp.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/condabin/rename_tmp.bat new file mode 100644 index 0000000000000000000000000000000000000000..417d8fc170fd3a6a8ff3ca89b5916c5d0e7fd312 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish new file mode 100644 index 0000000000000000000000000000000000000000..ea27d135ac1466eecde4d75b4d6305857ca490b0 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh new file mode 100644 index 0000000000000000000000000000000000000000..7e48cc9cfd8408d6d8665c02ac8f39d0b783fa53 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a24b3a97f2489a2be04b0810d324efaa8f4cbf7 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..095db5a22e3cdb8486ff519a62578aed85e5ed73 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5256e617ade64e02085715351ef70e01ff81228a Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/cases.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/cases.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da85aaf013f1317dc7dd40be32074a6c5c325532 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/cases.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/fixtures.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/fixtures.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d3475a766b910309eca94eb38f3d72686ea4783 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/fixtures.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/helpers.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6600877c1f76ab409b2a5a6aab4163d8c7ff819e Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/helpers.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/integration.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/integration.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40a061b6c6ea2ccc9fe303afdcfffded87214d14 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/integration.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/solver_helpers.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/solver_helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6df8dc1c2ddbc333117b97d99fcd95f616b3092 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/__pycache__/solver_helpers.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/cases.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/cases.py new file mode 100644 index 0000000000000000000000000000000000000000..c1fa7fddff22fe3bbb158781218433df5cceaf91 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/fixtures.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0f233dd65319a7b99c0235039bf9631634755e --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/fixtures.py @@ -0,0 +1,643 @@ +# 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 +from ..base.context import context, reset_context +from ..cli.main import main_subshell +from ..common.configuration import YamlRawParameter +from ..common.serialize import json, yaml_round_trip_load +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: + 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, + *packages: str, + prefix: str | os.PathLike | None = None, + ) -> Iterator[Path]: + """Generate a conda environment with the provided packages. + + :param packages: The packages to install into environment + :param prefix: The prefix at which to install the conda environment + :return: The conda environment's prefix + """ + prefix = Path(prefix or self.get_path()) + + self.conda_cli("create", "--prefix", prefix, *packages, "--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(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_round_trip_load(TEST_CONDARC) + ) + } + ) diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0834d0d570428bf76b9555dfb3944757e689cd5d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__pycache__/fixtures.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__pycache__/fixtures.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccf76574414f19e75775d3cdf27cd5735b52b840 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/__pycache__/fixtures.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/fixtures.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/gateways/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..aeb44ee622e395eefe7d8bf2e5623754caefd54a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/helpers.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..7d821b805afae31a0e29f75c2612d3d2d0fa73d2 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/integration.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..ff867a8d25c675449fc370cd853f1dacb60fc38a --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89baace772768b1a316ab48e28e2395ed0d2650d --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..498ac220857865e43400c7efad5fa698afef6282 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/fixtures.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/fixtures.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efc7e38d9b71bf09467be8b8f0cb553c405cf49a Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/fixtures.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/helpers.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b509eb68c5618efce5122f0db0aaee51a05adf31 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/__pycache__/helpers.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/fixtures.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..b4889e062cad32fc6c48766f18049bb298c406fd --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/helpers.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/notices/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..5e5e1458eddda7d28b9015f19e01e168a8f07f43 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/solver_helpers.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/testing/solver_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..6e900a2a90526d1216f630ea50d3f81eb8a880de --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b601a4b66b017829b4b3733eaa823a94c07f9a13 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..968d0a7e80cb9f87e2b76740a452ab6ba168f37b Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/constants.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/constants.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de3091b401af29845ad501e15a651dcd8954f55f Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/constants.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/signature_verification.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/signature_verification.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ad40d3949d390a97e336866ccf8b26b9f131d6c Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/__pycache__/signature_verification.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/constants.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a65f0ff428a564d9c6d4d40c9fe420c99b37e4f2 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/signature_verification.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda/trust/signature_verification.py new file mode 100644 index 0000000000000000000000000000000000000000..80d4f9426373a6f34270fa6461bcf3f8dc3ac548 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28e97df75dd686a190838f8826423837823daac4 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/cli/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..257be2505e2176a8a934a36dfca503610426787f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/cli/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/cli/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e198428881a24317a0fff92cb17fea30f0595691 Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/cli/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/installers/__init__.py b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/installers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..257be2505e2176a8a934a36dfca503610426787f --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/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/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/installers/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/installers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5620dc2aeaf1687211d0c4cea7a6103e2d3f32d Binary files /dev/null and b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/conda_env/installers/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.bat new file mode 100644 index 0000000000000000000000000000000000000000..0ad5bbf860027e2f834080ee322e08e7b253a208 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.bat @@ -0,0 +1,5 @@ +@ECHO OFF +set TEST=teststringfromactivate + +set PATH_PRE_ACTIVATE_DEACTIVATE=%PATH% +set PATH=%TEST%/bin/test;%PATH% diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.sh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.sh new file mode 100644 index 0000000000000000000000000000000000000000..f8c8134df9765f8bdd718f4f262f34821b05aa56 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/activate.d/activate.sh @@ -0,0 +1,2 @@ +export TEST=teststringfromactivate +export PATH="${TEST}/bin/test:${PATH}" diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.bat b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.bat new file mode 100644 index 0000000000000000000000000000000000000000..0ec2c4324569af150280f197eb2431f9bcbeda80 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.bat @@ -0,0 +1,2 @@ +@ECHO OFF +set PATH=%PATH_PRE_ACTIVATE_DEACTIVATE% diff --git a/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.sh b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.sh new file mode 100644 index 0000000000000000000000000000000000000000..51f007911f4b4ee6b66f802eedc71f382b912242 --- /dev/null +++ b/data/miniconda3/pkgs/conda-25.11.1-py313h06a4308_0/lib/python3.13/site-packages/tests/data/recipes/activate_deactivate_package/src/etc/conda/deactivate.d/deactivate.sh @@ -0,0 +1,2 @@ +export TEST=teststringfromactivate +export PATH=`echo $PATH | sed "s|${TEST}/bin/test:||"` diff --git a/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/about.json b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/about.json new file mode 100644 index 0000000000000000000000000000000000000000..ad4c5a427bae176ab0f91fc6ce6f12bfc4a23b8d --- /dev/null +++ b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/about.json @@ -0,0 +1,139 @@ +{ + "channels": [ + "file:///jenkins/agent/cia-tf-rocky9-jenkins-master-1.client.nvidia.com/workspace/kitpicks/cuda-r12-8/conda-cuda-r12-8-linux-x86-64/scratch/out", + "file:///jenkins/agent/cia-tf-rocky9-jenkins-master-1.client.nvidia.com/workspace/kitpicks/cuda-r12-8/conda-cuda-r12-8-linux-x86-64/scratch/input", + "https://repo.anaconda.com/pkgs/main" + ], + "conda_build_version": "24.1.2", + "conda_version": "24.1.2", + "description": "Meta-package containing all available library runtime packages.\n", + "doc_url": "https://docs.nvidia.com/cuda/index.html", + "env_vars": { + "CIO_TEST": "" + }, + "extra": { + "copy_test_source_files": true, + "final": true, + "recipe-maintainers": [ + "conda-forge/cuda" + ] + }, + "home": "https://developer.nvidia.com/cuda-toolkit", + "identifiers": [], + "keywords": [], + "license": "LicenseRef-NVIDIA-End-User-License-Agreement", + "license_file": "LICENSE.txt", + "license_url": "https://docs.nvidia.com/cuda/eula/index.html", + "root_pkgs": [ + "_libgcc_mutex 0.1 main", + "_openmp_mutex 5.1 1_gnu", + "archspec 0.2.1 pyhd3eb1b0_0", + "boltons 23.0.0 py312h06a4308_0", + "brotli-python 1.0.9 py312h6a678d5_7", + "bzip2 1.0.8 h7b6447c_0", + "c-ares 1.19.1 h5eee18b_0", + "ca-certificates 2023.12.12 h06a4308_0", + "certifi 2024.2.2 py312h06a4308_0", + "cffi 1.16.0 py312h5eee18b_0", + "charset-normalizer 2.0.4 pyhd3eb1b0_0", + "conda 24.1.2 py312h06a4308_0", + "conda-content-trust 0.2.0 py312h06a4308_0", + "conda-libmamba-solver 23.12.0 pyhd3eb1b0_1", + "conda-package-handling 2.2.0 py312h06a4308_0", + "conda-package-streaming 0.9.0 py312h06a4308_0", + "cryptography 41.0.7 py312hdda0065_0", + "distro 1.8.0 py312h06a4308_0", + "expat 2.5.0 h6a678d5_0", + "fmt 9.1.0 hdb19cb5_0", + "icu 73.1 h6a678d5_0", + "idna 3.4 py312h06a4308_0", + "jsonpatch 1.32 pyhd3eb1b0_0", + "jsonpointer 2.1 pyhd3eb1b0_0", + "krb5 1.20.1 h143b758_1", + "ld_impl_linux-64 2.38 h1181459_1", + "libarchive 3.6.2 h6ac8c49_2", + "libcurl 8.5.0 h251f7ec_0", + "libedit 3.1.20230828 h5eee18b_0", + "libev 4.33 h7f8727e_1", + "libffi 3.4.4 h6a678d5_0", + "libgcc-ng 11.2.0 h1234567_1", + "libgomp 11.2.0 h1234567_1", + "libmamba 1.5.3 haf1ee3a_0", + "libmambapy 1.5.3 py312h2dafd23_0", + "libnghttp2 1.57.0 h2d74bed_0", + "libsolv 0.7.24 he621ea3_0", + "libssh2 1.10.0 hdbd6064_2", + "libstdcxx-ng 11.2.0 h1234567_1", + "libuuid 1.41.5 h5eee18b_0", + "libxml2 2.10.4 hf1b16e4_1", + "lz4-c 1.9.4 h6a678d5_0", + "menuinst 2.0.2 py312h06a4308_0", + "ncurses 6.4 h6a678d5_0", + "openssl 3.0.13 h7f8727e_0", + "packaging 23.1 py312h06a4308_0", + "pcre2 10.42 hebb0a14_0", + "pip 23.3.1 py312h06a4308_0", + "platformdirs 3.10.0 py312h06a4308_0", + "pluggy 1.0.0 py312h06a4308_1", + "pybind11-abi 4 hd3eb1b0_1", + "pycosat 0.6.6 py312h5eee18b_0", + "pycparser 2.21 pyhd3eb1b0_0", + "pysocks 1.7.1 py312h06a4308_0", + "python 3.12.1 h996f2a0_0", + "readline 8.2 h5eee18b_0", + "reproc 14.2.4 h295c915_1", + "reproc-cpp 14.2.4 h295c915_1", + "requests 2.31.0 py312h06a4308_1", + "ruamel.yaml 0.17.21 py312h5eee18b_0", + "setuptools 68.2.2 py312h06a4308_0", + "sqlite 3.41.2 h5eee18b_0", + "tk 8.6.12 h1ccaba5_0", + "tqdm 4.65.0 py312he106c6f_0", + "truststore 0.8.0 py312h06a4308_0", + "tzdata 2023d h04d1e81_0", + "urllib3 2.1.0 py312h06a4308_1", + "wheel 0.41.2 py312h06a4308_0", + "xz 5.4.5 h5eee18b_0", + "yaml-cpp 0.8.0 h6a678d5_0", + "zlib 1.2.13 h5eee18b_0", + "zstandard 0.19.0 py312h5eee18b_0", + "zstd 1.5.5 hc292b87_0", + "anaconda-anon-usage 0.4.3 py312hfc0e8ea_100", + "anaconda-client 1.12.3 py312h06a4308_0", + "attrs 23.1.0 py312h06a4308_0", + "beautifulsoup4 4.12.2 py312h06a4308_0", + "chardet 4.0.0 py312h06a4308_1003", + "click 8.1.7 py312h06a4308_0", + "conda-build 24.1.2 py312h06a4308_0", + "conda-index 0.4.0 pyhd3eb1b0_0", + "defusedxml 0.7.1 pyhd3eb1b0_0", + "filelock 3.13.1 py312h06a4308_0", + "jinja2 3.1.3 py312h06a4308_0", + "jsonschema 4.19.2 py312h06a4308_0", + "jsonschema-specifications 2023.7.1 py312h06a4308_0", + "jupyter_core 5.5.0 py312h06a4308_0", + "liblief 0.12.3 h6a678d5_0", + "markupsafe 2.1.3 py312h5eee18b_0", + "more-itertools 10.1.0 py312h06a4308_0", + "nbformat 5.9.2 py312h06a4308_0", + "patch 2.7.6 h7b6447c_1001", + "patchelf 0.17.2 h6a678d5_0", + "pkginfo 1.9.6 py312h06a4308_0", + "psutil 5.9.0 py312h5eee18b_0", + "py-lief 0.12.3 py312h6a678d5_0", + "python-dateutil 2.8.2 pyhd3eb1b0_0", + "python-fastjsonschema 2.16.2 py312h06a4308_0", + "python-libarchive-c 2.9 pyhd3eb1b0_1", + "pytz 2023.3.post1 py312h06a4308_0", + "pyyaml 6.0.1 py312h5eee18b_0", + "referencing 0.30.2 py312h06a4308_0", + "requests-toolbelt 1.0.0 py312h06a4308_0", + "rpds-py 0.10.6 py312hb02cf49_0", + "six 1.16.0 pyhd3eb1b0_1", + "soupsieve 2.5 py312h06a4308_0", + "traitlets 5.7.1 py312h06a4308_0", + "yaml 0.2.5 h7b6447c_0" + ], + "summary": "Meta-package containing all available library runtime packages.", + "tags": [] +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/files b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/files new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/git b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/git new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/index.json b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/index.json new file mode 100644 index 0000000000000000000000000000000000000000..b8c30e39a254165ce07f845d002f06793d900c7c --- /dev/null +++ b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/index.json @@ -0,0 +1,26 @@ +{ + "arch": "x86_64", + "build": "0", + "build_number": 0, + "depends": [ + "cuda-cudart 12.8.90.*", + "cuda-nvrtc 12.8.93.*", + "cuda-opencl 12.8.90.*", + "libcublas 12.8.4.1.*", + "libcufft 11.3.3.83.*", + "libcufile 1.13.1.3.*", + "libcurand 10.3.9.90.*", + "libcusolver 11.7.3.90.*", + "libcusparse 12.5.8.93.*", + "libnpp 12.3.3.100.*", + "libnvfatbin 12.8.90.*", + "libnvjitlink 12.8.93.*", + "libnvjpeg 12.3.5.92.*" + ], + "license": "LicenseRef-NVIDIA-End-User-License-Agreement", + "name": "cuda-libraries", + "platform": "linux", + "subdir": "linux-64", + "timestamp": 1741064468346, + "version": "12.8.1" +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/licenses/LICENSE.txt b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..6622367aff6567f25c18f500137a36caf101ea50 --- /dev/null +++ b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/licenses/LICENSE.txt @@ -0,0 +1,1632 @@ +End User License Agreement +-------------------------- + +NVIDIA Software License Agreement and CUDA Supplement to +Software License Agreement. + +The CUDA Toolkit End User License Agreement applies to the +NVIDIA CUDA Toolkit, the NVIDIA CUDA Samples, the NVIDIA +Display Driver, NVIDIA Nsight tools (Visual Studio Edition), +and the associated documentation on CUDA APIs, programming +model and development tools. If you do not agree with the +terms and conditions of the license agreement, then do not +download or use the software. + +Last updated: January 12, 2024. + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA toolkit. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +CUDA Samples are now located in +https://github.com/nvidia/cuda-samples, which includes +instructions for obtaining, building, and running the samples. +They are no longer included in the CUDA toolkit. + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Important Notice—Read before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Components Under Other Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, NVIDIA or third-party components with +separate legal notices or terms as may be described in +proprietary notices accompanying the SDK. If and to the extent +there is a conflict between the terms in this Agreement and +the license terms associated with the component, the license +terms associated with the components control only to the +extent necessary to resolve the conflict. + +Subject to the other terms of this Agreement, you may use the +SDK to develop and test applications released under Open +Source Initiative (OSI) approved open source software +licenses. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. You acknowledge that the SDK as delivered is not tested + or certified by NVIDIA for use in connection with the + design, construction, maintenance, and/or operation of any + system where the use or failure of such system could + result in a situation that threatens the safety of human + life or results in catastrophic damages (each, a "Critical + Application"). Examples of Critical Applications include + use in avionics, navigation, autonomous vehicle + applications, ai solutions for automotive products, + military, medical, life support or other life critical + applications. NVIDIA shall not be liable to you or any + third party, in whole or in part, for any claims or + damages arising from such uses. You are solely responsible + for ensuring that any product or service developed with + the SDK as a whole includes sufficient features to comply + with all applicable legal and regulatory standards and + requirements. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to products or + services that use the SDK in or for Critical Applications, + and for use of the SDK outside of the scope of this + Agreement or not in compliance with its terms. + + 8. You may not reverse engineer, decompile or disassemble + any portion of the output generated using SDK elements for + the purpose of translating such output artifacts to target + a non-NVIDIA platform. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights under Section + 1.3.2. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights under Section 1.3.1. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY (I) SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR (II) DAMAGES FOR (A) ANY +LOST PROFITS, LOSS OF USE, LOSS OF DATA OR LOSS OF GOODWILL, +OR THE COSTS OF PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF +OR IN CONNECTION WITH THIS AGREEMENT OR THE USE OR PERFORMANCE +OF THE SDK, WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED +UPON BREACH OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING +NEGLIGENCE), PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR +THEORY OF LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not located in a country currently +embargoed by the U.S. or otherwise prohibited from receiving +the SDK under U.S. law. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following CUDA Toolkit files may be distributed with +applications developed by you, including certain +variations of these files that have version number or +architecture specific information embedded in the file name - +as an example only, for release version 9.0 of the 64-bit +Windows software, the file cudart64_90.dll is redistributable. + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Windows + +nvjpeg.lib, nvjpeg.dll + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so, libnvrtc_static.a, libnvrtx-builtins_static.a + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA JIT Linking Library + +Windows + +libnvJitLink.dll, libnvJitLink.lib + +Linux + +libnvJitLink.so, libnvJitLink_static.a + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-ptxjitcompiler.so, libnvptxcompiler_static.a + +Component + +NVIDIA CUDA File IO Libraries and Header + +All + +cufile.h + +Linux + +libcufile.so, libcufile_rdma.so, libcufile_static.a, +libcufile_rdma_static.a + +In addition to the rights above, for parties that are +developing software intended solely for use on Jetson +development kits or Jetson modules, and running Linux for +Tegra software, the following shall apply: + + * The SDK may be distributed in its entirety, as provided by + NVIDIA, and without separation of its components, for you + and/or your licensees to create software development kits + for use only on the Jetson platform and running Linux for + Tegra software. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + 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, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with 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: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + 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 CONTRIBUTORS 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 WITH THE SOFTWARE. + + 5. Licensee's use of the PCRE third party component is + subject to the following terms and conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + 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 University of Cambridge nor the name of Google + Inc. nor the names of their 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 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. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + 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 University of California, Berkeley 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 AUTHOR "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 AUTHOR 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. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + 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. + * The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + 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 listed in this license in the documentation and/or + other materials provided with the distribution. + * Neither the name of the copyright holders 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 + 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. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + 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 STFC 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 STFC 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. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + 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 King Abdullah University of Science and + Technology 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 + HOLDERS 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 + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with 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: + * 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 + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + 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 CONTRIBUTORS 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 WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. 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 Hiroshima University 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 + 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. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + 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 D. E. Shaw Research 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 + 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. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + All rights reserved. + + 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. + + 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. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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. + + 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. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + 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, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google Inc. + + 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. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + 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. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license. + + 22. Components of the driver and compiler used for binary management, including + nvFatBin, nvcc, and cuobjdump, use the Zstandard library which is subject to + the following license: + + BSD License + + For Zstandard software + + Copyright (c) Meta Platforms, Inc. and affiliates. 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 Facebook, nor Meta, 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/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/paths.json b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/paths.json new file mode 100644 index 0000000000000000000000000000000000000000..03d81a3201aeefb71167ac453cd6d8c33bec10b9 --- /dev/null +++ b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/paths.json @@ -0,0 +1,4 @@ +{ + "paths": [], + "paths_version": 1 +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/repodata_record.json b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/repodata_record.json new file mode 100644 index 0000000000000000000000000000000000000000..4dd5d2342117c79a7b67d27f85220f538f4328da --- /dev/null +++ b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/repodata_record.json @@ -0,0 +1,33 @@ +{ + "name": "cuda-libraries", + "version": "12.8.1", + "build": "0", + "build_number": 0, + "channel": "https://conda.anaconda.org/nvidia/linux-64", + "subdir": "linux-64", + "fn": "cuda-libraries-12.8.1-0.conda", + "md5": "d669079ff2496cb0dfa4a7392af88ca4", + "url": "https://conda.anaconda.org/nvidia/linux-64/cuda-libraries-12.8.1-0.conda", + "sha256": "e04065575809d126f8dd42a247ded786edb93f2786516a0ca23a6a227a715f32", + "arch": "x86_64", + "platform": "linux", + "depends": [ + "cuda-cudart 12.8.90.*", + "cuda-nvrtc 12.8.93.*", + "cuda-opencl 12.8.90.*", + "libcublas 12.8.4.1.*", + "libcufft 11.3.3.83.*", + "libcufile 1.13.1.3.*", + "libcurand 10.3.9.90.*", + "libcusolver 11.7.3.90.*", + "libcusparse 12.5.8.93.*", + "libnpp 12.3.3.100.*", + "libnvfatbin 12.8.90.*", + "libnvjitlink 12.8.93.*", + "libnvjpeg 12.3.5.92.*" + ], + "constrains": [], + "license": "LicenseRef-NVIDIA-End-User-License-Agreement", + "timestamp": 1741064468000, + "size": 17014 +} \ No newline at end of file diff --git a/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/test/run_test.sh b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/test/run_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3cacc90844106a1b86fcc087456d4d6cbe2725d4 --- /dev/null +++ b/data/miniconda3/pkgs/cuda-libraries-12.8.1-0/info/test/run_test.sh @@ -0,0 +1,8 @@ + + +set -ex + + + +exit 0 +exit 0